Sunday, February 17, 2008

Concept of Broadening, Widening, and Casting in JAVA 1.5

Compile the following thing:
code:

Byte b= new Byte(100);
Long d=new Long(100);


First line fail to compile, where as Second line compiled successfully..Why..why why ??
Lets try to find out:
when you write :
byte b = 120;
its compiles fine..!! why because compiler see that int 120 in in RANGE of byte..
Now when you write
byte b = 150;
Compiler complains since 150 is out of RANGE..!!
Now lets come to your question :
Part 1 :
Byte b = new Byte(100);
When ever compiler encounters new keyword, it let the Object creation on JVM..!! so in case of new Object..Objects are created at run time..!! so according to compiler point of view:
Byte b = new Byte(int);
Here int may or may not be in the RANGE of byte, if it is in range then its ok, if it is not then !!!! SCARY THINGS!!!!..so as a friend compiler wont let you to write something that has possibility of crashing..that why it gives you an error..
in case of
Long l = new Long(int);
now whatsoever be the value of int ,it ALWAYS be in the RANGE of long..so compiler allows..!!!
You got to know now..take a deep breath now..!!see the next line of code
code:
Byte b=100;
Long d=100;


Ohh My god..!! Now first line workd but second doesn't..Let see why?

In JAVA 5, we can not WIDEN and BOX Together...!!! Repeat this line 5 times..!!! Done..lets move forward.
Now in
Long l = 100;
In this case 100 is an integer..so first we have to widen it to long then we have to box long to Long...!!
so compiler complain..
Long l = new Long(100);

Here we are widening int(100) to long..but we are not boxing it...!! as we have used new keyword here..so we have explicitly defined the Object creation syntax..
so compile successfully...!!!
now
Byte b = new Byte(100)..

this i already explain you why it can not be compile..!!
now come to following:

Byte b = 100;

Here we have int 100....we are not widening it...infact we are narrowing it..but we call it implicit casting..!!
and since this implicit casting is in range..and the object will be created at compile time..so it works..
so here we can say that..
implicit casting(with in range) + Boxing is acceptable..!!

But again one thing concern me..!!
suppose the following condition..

public static void printMe(Byte b) { }

public static void main(String... args)
{
printMe(100);

}

from compiler point of view...it is calling printMe(int)..again possibility of crashing..so It wont allow..