Type conversion and casting in Java - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Thursday, November 1, 2018

Type conversion and casting in Java

Type conversion and casting in Java

Type Conversion

When you assign one type of variable into another type of variable, the two type might not be compatible with each other. If the data types are compatible the Java will automatically perform conversion and if not then need to be casted or converted explicitly. For example, assigning an int value to long variable.

Automatic type conversion

When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met:

  • The two data types are compatible.
  • The destination type is larger than the source type.

When these two conditions are met, a widening conversion takes place. For widening conversions, the numeric types, including integer and floating-point types, are compatible with each other.

There are no automatic conversions from the numeric types to char or boolean. Also, char and boolean are not compatible with each other.

Java also performs an automatic type conversion when storing a literal integer constant into variables of type byte, short, long, or char.

Example of widening conversion

public class WideningDemo {
  public static void main(String[] args) {
    int x = 50;

    // automatic type conversion
    long l = x;

    // automatic type conversion
    float f = x;
    System.out.println("Value of x, l, and f " + x + " " + l + " " + f);
  }
}

Explanation: The int type variable x is compatible with long and float data type and value of x is assigning to variable l and f. Destination data type long and float is larger than int.

Output of the above program

Value of x, l, and f 50 50 50.0

Narrowing or explicit type conversion

If you want to assign a value of larger data type to a smaller data type then you need to perform explicit type casting that is called a narrowing conversion.

To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion.

(target-type) value

Here, target-type specifies the desired type to convert the specified value to.

Example of narrowing conversion

Lets assign char to int data type. It will give a compile time error.

public class IntToCharDemo {
  public static void main(String[] args) {
    int x = 40;
    char ch = x; // error
  }
}

Line 4: incompatible types: possible lossy conversion from int to char.

Lets see an example of explicit type conversion.

public class NarrowingConversionDemo {
  public static void main(String[] args) {
    double d = 20.204;

    // narrowing conversion from double to float
    float f = (float) d;

    // casting from double to long
    long l1 = (long) d;

    // casting from float to long
    long l2 = (long) f;

    // casting from float to int
    int x = (int) f;

    // casting from double to int
    int y = (int) d;

    // casting from double to short
    short s = (short) x;

    // casting from double to byte
    byte b = (byte) x;

    System.out.println("Double value:: " + d);
    System.out.println("Double to float:: " + f);
    System.out.println("Double to long:: " + l1 + ", Float to long:: " + l2);
    System.out.println("Float to int:: " + x + ", Double to int:: " + y);
    System.out.println("Double to short:: " + s);
    System.out.println("Double to byte:: " + b);
  }
}

Explanation: When floating-point value is assigned to an integer type truncation happen. As you know integers type do not have fractional components. Thus when a floating-point value is assigned to an integer type, the fractional component is lost.

Output of the above program:

Double value:: 20.204
Double to float:: 20.204
Double to long:: 20, Float to long:: 20
Float to int:: 20, Double to int:: 20
Double to short:: 20
Double to byte:: 20

Important point: If the larger data type value is larger than the range of smaller data type, it will be reduced modulo target type’s range.

Lets understand it with an example.

public class Conversion {
  public static void main(String[] args) {
    byte b;
    int i = 257;
    double d = 323.142;

    System.out.println("Conversion of int to byte.");
    b = (byte) i;
    System.out.println("i and b " + i + " " + b);

    i = -260;
    System.out.println("\nAgain conversion of int to byte.");
    b = (byte) i;
    System.out.println("i and b " + i + " " + b);

    System.out.println("\nConversion of double to int.");
    i = (int) d;
    System.out.println("d and i " + d + " " + i);

    d = -2147483656.456;
    System.out.println("\nAgain conversion of double to int.");
    i = (int) d;
    System.out.println("d and i " + d + " " + i);

    d = 323.142;
    System.out.println("\nConversion of double to byte.");
    b = (byte) d;
    System.out.println("d and b " + d + " " + b);

    d = -2147483651.456;
    System.out.println("\nAgain conversion of double to byte.");
    b = (byte) d;
    System.out.println("d and b " + d + " " + b);
  }
}

Output of the program:

Conversion of int to byte.
i and b 257 1

Again conversion of int to byte.
i and b -260 -4

Conversion of double to int.
d and i 323.142 323

Again conversion of double to int.
d and i -2.147483656456E9 -2147483648

Conversion of double to byte.
d and b 323.142 67

Again conversion of double to byte.
d and b -2.147483651456E9 0

Explanation: When the value 257 is cast into a byte variable, the result is the remainder of the division of 257 by 256 (the range of a byte), which is 1 in this case.

when the d is converted to an int, its fractional component is lost. When d is converted to a byte, its fractional component is lost, and the value is reduced modulo 256, which in this case is 67.

Automatic type promotion in expressions

While evaluating expressions, the intermediate value may exceed the range of either operands and hence the expression value will be promoted. Some conditions for type promotion rule:

  • 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 long, float or double respectively.
public class AutomaticPromotionDemo {
  public static void main(String[] args) {
    byte a = 40;
    byte b = 50;
    byte c = 100;

    int d = a * b / c;

    System.out.println("Value of d:: " + d);
  }
}

Explanation: The result of the intermediate term a * b easily exceeds the range of either of its byte operands. Java automatically promotes to int when evaluating an expression. This means that the subexpression a*b is performed using integers—not bytes. Thus, 2,000, the result of the intermediate expression, 50 * 40, is legal even though a and b are both specified as type byte.

Output of the program:

Value of d:: 20

Explicit type casting in expression

While evaluating expressions, the intermediate result is automatically promoted to larger data type of the operand. But if we store that result in any smaller data type it generates compile time error, due to which we need to type cast the result.

// Java program to illustrate type casting int to byte
public class ExpressionCastingDemo {
  public static void main(String[] args) {
    byte b = 50;
    b = (byte) (b * 2);
    System.out.println("Value of b:: " + b);
  }
}

The result of term b * 2 is promoted to int and then need to cast it accordingly.

Output of the program:

Value of b:: 100

No comments :

Post a Comment