Often it is necessary to mix numeric values of different types in a computation.
When performing a binary operation involving two operands of different types. Java automatically converts the operand based on the following rules:
if one of the operands is double, the other is converted into double.
Otherwise, if one of the operands is float, the other is converted into float.
Otherwise, if one of the operands is long, the other is converted into long.
Otherwise, both operands are converted into an int.
The range of numeric types increases in this order:
range increases
----------------------------------------->
byte, short, int, long, float, double
You can always assign a value to a numeric variable whose type supports a larger range of values; thus for instance, you can assign a long value to a float variable. You cannot, however, assign a value to a variable of a type with smaller range unless you use type casting.
Casting is an operation that converts a value of one data type into a value of another data type.
The syntax for casting gives the target type in parentheses, followed by the variable's name or the value to be cast.
a) output of the following statement is 1.7.
System.out.println(1.7);
b) output of the following statement is 1.
System.out.println((int)1.7);
c) output of the following statement is 0.
System.out.println(1/2);
d) output of the following statement of 0.5.
System.out.println((double)1/2);