1
0

Type Casting in Java

In an assignment statement, ie. if there’s an equals sign, Java compares the type of the left-hand side variable to the final type of the result of the right-hand side expression. It won’t change the type of the left-hand side variable, but it will check to make sure that the data type of the variable on the left side can accommodate the value of right side expression. Anything can fit in a double. Anything except a double can fit in a float. Any integral type can fit in a long, but a float or a double can’t, and ints, shorts, and bytes can fit inside ints. If the right-hand side can fit inside the left-hand side, the assignment takes place without any problem. Here the data type of the resultant value will automatically get converted into the data-type variable on the left side. This process is called automatic type conversion.

Assigning long values to int variables or double values to float variables is not allowed by the Java compiler. So if you want to make such assignments then you need type casting. When it’s necessary to force a value into a particular type, use a cast. To cast a variable or a literal or an expression to a different data type just precede it with the type in parentheses. For instance:

int i-(int) (9.0/4.0);

A cast lets the compiler know that you’re serious about the conversion you plan to make.

When a value is cast down before assignment, a series of operations take place to chop the right-hand side down to size. For conversion between a floating point number and an int or a long, the fractional part of the floating point number is truncated or rounded toward zero. This produces an integer. If the integer is small enough to fit on the left-hand side, the assignment is completed. On the other hand, if the number is too large, then the integer is set to the largest possible value of its type. If the floating point number is too small the integer is set to the smallest possible value of its type.

Leave a Reply