CODE
class TypeConversion
{
public static void main(String arg[])
{
byte b = 50;
short s = 4125;
int i = 800000;
long l = 107343L;
s = b; // LINE A
i = s; // LINE B
l = i; // LINE C
float f = 25.0f;
double d = 327.98;
f = i;
d = f;
System.out.println("b = " + b );
System.out.println("s = " + s );
System.out.println("i = " + i );
System.out.println("l = " + l );
System.out.println("d = " + d );
System.out.println("f = " + f );
}
}
b = 50
s = 50
i = 50
l = 50
d = 50.0
f = 50.0
Initially we declared all integer type variables and converted from lower size to higher size. The conversion is automatic since every assignment follows the two rules mentioned above.
The reason why i
prints 50
instead of 4125
is, when s = b;
is executed the value of s
is over written with 50
and the later when i = s;
is executed, i
will become 50
. That is the reason why all other values are also 50
.
Also note that floating point variables d
and f
print 50.0
instead of 50
.
LINE A
, LINE B
and LINE C
in the order LINE C
, LINE B
and LINE A
and see the output.107343L
to 107343
and see if type conversion happens automatically for literals as well. Note that 107343
is an int
literal where as 107343L
is a long
literal.