Java Reference
In-Depth Information
1.6.2 Type checking for assignments and casting
1.6.2.1 Type checking. Whenever assigning a variable, the compiler javac
checks that the type of the expression coincides with the type of the variable.
If not, the compiler reports an error message and aborts (without generating
proper bytecode). For example, consider the code below:
class TypeError{
public static void main (String[ ] args)
{
double myFavoriteReal=3.141592;
int myFavoriteNat=2.71;
}
}
Compiling this code will generate an error as follow:
prompt%javac TypeError.java
TypeError.java:5: possible loss of precision
found : double
required: int
int myFavoriteNat=2.71;
^
1 error
prompt%
That is, the compiler performed the type checking and found that the type
of the expression (here, the real constant 2 . 71 of type double ) does not agree
with the type of the int variable myFavoriteNat . Typing provides an essential
safeguard mechanism for writing more coherent programs, that is programs
without obvious bugs.
1.6.2.2 Casting types. We can eventually transform that real 2 . 71 by
truncating it into the integer 2 by a casting operation:
int myFavoriteNat=(int)2.71;
This results in a loss of precision, as noticed by the compiler.
In general, we can explicitly cast a type TypeExpr into a TypeVar using the
following syntax:
TypeVar myVar=(TypeExpr)(Expression);
Typed languages such as Java are useful to abstract notions and types of
variables characterizing semantic parameters. In college, we are familiar with
similar notions to assign quantity of the same units. For example, it does not
make sense to assign to a velocity (type m
s 2 ).
In fact, some earlier casting operations were already carried out when declaring
and initializing constants:
s 1 ) an acceleration (type m
×
×
 
Search WWH ::




Custom Search