Java Reference
In-Depth Information
2.20
How do you obtain the current minute using the System.currentTimeMillis()
method?
2.15 Numeric Type Conversions
Floating-point numbers can be converted into integers using explicit casting.
Key
Point
Can you perform binary operations with two operands of different types? Yes. If an integer
and a floating-point number are involved in a binary operation, Java automatically converts
the integer to a floating-point value. So, 3 * 4.5 is same as 3.0 * 4.5 .
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, how-
ever, assign a value to a variable of a type with a 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.
Casting a type with a small range to a type with a larger range is known as widening a type. Cast-
ing a type with a large range to a type with a smaller range is known as narrowing a type. Java
will automatically widen a type, but you must narrow a type explicitly.
The syntax for casting a type is to specify the target type in parentheses, followed by the
variable's name or the value to be cast. For example, the following statement
casting
widening a type
narrowing a type
System.out.println(( int ) 1.7 );
displays 1 . When a double value is cast into an int value, the fractional part is truncated.
The following statement
System.out.println(( double ) 1 / 2 );
displays 0.5 , because 1 is cast to 1.0 first, then 1.0 is divided by 2 . However, the statement
System.out.println( 1 / 2 );
displays 0 , because 1 and 2 are both integers and the resulting value should also be an integer.
Caution
Casting is necessary if you are assigning a value to a variable of a smaller type range,
such as assigning a double value to an int variable. A compile error will occur if cast-
ing is not used in situations of this kind. However, be careful when using casting, as loss
of information might lead to inaccurate results.
possible loss of precision
Note
Casting does not change the variable being cast. For example, d is not changed after
casting in the following code:
double d = 4.5 ;
int i = ( int )d; // i becomes 4, but d is still 4.5
Note
In Java, an augmented expression of the form x1 op= x2 is implemented as x1 =
(T)(x1 op x2) , where T is the type for x1 . Therefore, the following code is correct.
casting in an augmented
expression
int sum = 0 ;
sum += 4.5 ; // sum becomes 4 after this statement
sum += 4.5 is equivalent to sum = (int)(sum + 4.5) .
 
 
Search WWH ::




Custom Search