Type Conversions in Java

Type Conversions in Java

by Sanjay Nair February 3, 2018

Type conversion in Java with Examples

  • When value of one data type is assigned to another, the two types might not be compatible with each other.
  • If the data types are compatible with each other, then Java performs the conversion automatically known as Automatic Type Conversion and if they are not compatible, then they need to be casted or converted separately.
  • For example, assigning an int value to a long variable.

Widening Conversion or Automatic Type Conversion

  • Widening conversion takes place when two data types are automatically converted to become compatible with each other. This takes place when:
  • The two data types are compatible with one another.
  • When value of a smaller data type is assigned to a bigger data type.
  • For Example, in java the numeric data types are compatible with each other but there is no automatic conversion supported between numeric type and char or boolean.
  • Also, char and boolean are not compatible with each other.
  • Automatic conversion sequence.

Sequence of Widening Conversion

Example of Automatic or Widening Conversion

Output:

Int value 100

Long value 100

Float value 100.0

  • If we wish to assign a value of larger data type to a variable of smaller data type, we perform narrowing conversion or explicit type conversion.
  • This is useful for data types that are incompatible where automatic conversion cannot take place by itself.
  • Here, target-type specifies the desired type we want our assigned value to get converted into.
  • Sequence of Narrowing Conversion

  • Example of an incorrect Narrowing Conversion

Output:

7: error: incompatible types: possible lossy conversion from int to char

ch = num;

^

1 error

Correct Way of Making a Narrowing Conversion

Output:

Double value 100.04

Long value 100

Int value 100

  • While assigning a numeric value to a byte type the fractional part is lost and the value is reduced to modulo 256(range of byte).

Example:

//Java program to illustrate Conversion of int and double to byte

Output:

Conversion of int to byte.

i = 257 b = 1

Conversion of double to byte.

d = 323.142 b = 67

Type promotions

  • While an expression is evaluated, the intermediate value may sometimes exceed the range of operands and hence the value of the expression will be promoted. Some conditions for type promotion are:
  • Java automatically promotes each byte, short, or char operand to int when evaluating an expression.
  • If one operand is a long, float or double the whole expression is promoted to either long, float or double respectively.

 

Example of a Type Promotion in Java

Output

Result = 626.7784146484375

You may also like