Java Reference
In-Depth Information
is a type cast. The expression takes an int (in this example the value of m ) and evalu-
ates to an “equivalent” value of type double . So, if the value of m is 2 , the expression
(double)m evaluates to the double value 2.0 .
Note that (double)m does not change the value of the variable m . If m has the value 2
before this expression is evaluated, then m still has the value 2 after the expression is
evaluated.
You may use other type names in place of double to obtain a type cast to another
type. We said this produces an “equivalent” value of the target type. The word “equiv-
alent” is in quotes because there is no clear notion of equivalent that applies between
any two types. In the case of a type cast from an integer type to a floating-point type,
the effect is to add a decimal point and a zero. A type cast in the other direction, from
a floating-point type to an integer type, simply deletes the decimal point and all digits
after the decimal point. Note that when type casting from a floating-point type to an
integer type, the number is truncated not rounded: (int)2.9 is 2 ; it is not 3 .
As we noted earlier, you can always assign a value of an integer type to a variable of
a floating-point type, as in
double d = 5;
In such cases Java performs an automatic type cast, converting the 5 to 5.0 and placing
5.0 in the variable d . You cannot store the 5 as the value of d without a type cast, but
sometimes Java does the type cast for you. Such an automatic type cast is sometimes
called a type coercion .
By contrast, you cannot place a double value in an int variable without an explicit
type cast. The following is illegal:
type coercion
int i = 5.5; //Illegal
Instead, you must add an explicit type cast, like so:
int i = ( int )5.5;
Increment and Decrement Operators
The increment operator ++ adds one to the value of a variable. The decrement oper-
ator −− subtracts one from the value of a variable. They are usually used with variables
of type int , but they can be used with any numeric type. If n is a variable of a numeric
type, then n++ increases the value of n by one and n −− decreases the value of n by one.
So, n++ and n −− (when followed by a semicolon) are executable statements. For exam-
ple, the statements
int n = 1, m = 7;
n++;
System.out.println("The value of n is changed to " + n);
m −− ;
System.out.println("The value of m is changed to " + m);
Search WWH ::




Custom Search