Type Conversion
Assigning
variables of same data type is normal.
Assigning lower
to higher can be known as widening conversion. It is correct. Here implicit
casting(Automatic type conversion) will be made by java run time automatically.
Assigning higher
to lower can be known as narrowing conversion. The error will be raised for
these statements. Because lower type can’t have enough memory to accommodate
the value from higher type. Here explicit casting must be needed.
Automatic
type conversion
int c=100;
float a=c;//Automatic
type conversion
Here
RHS data type range is lesser than LHS data type range. Now automatically conversion
will be done by JRE.
Casting
float a=10.5f;
int c=a; //
error
int c=(int)a; //
explicit casting
How casting can be made
The following
example illustrates one surprise fact.
int x=900;
byte y=(byte)x;
This
is legal. The compile time error will not be raised. But how 900 can be stored
in y. The answer is simple.
Here
java first calculates 900%256. The remainder is 132. 132 can’t be stored in y.
Because byte range is -128 to 127. So JRE stores -124 in y. How? The answer is
following program.
Run
following prg, and analyze carefully.
class A
{
public static void main(String args[])
{
for (int x=256;x<=1000;x++)
{
byte y=(byte)x;
System.out.println("x="+x+"y="+y);
}
}
}
Automatic type promotion
In mixed expressions, lower data type will be converted to higher data
type automatically if LHS is higher data type. If LHS is lower than RHS,
explicit cast is needed.
Consider following example
byte b=b*2; //
error because 2 will be treated as integer.
int x=b*50; //
correct. Here b will be promoted to int.
long y=x*20; //
correct
int z=y*2; // error
because RHS is larger.
double p=y*z //
correct
Type
promotion Rules
· All byte and short
values are promoted to int.
· If one expression
is long, the whole expression is promoted to long.
· If one expression
is float, the whole expression is promoted to float.
· If one expression
is double, the whole expression is promoted to double.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.