File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Why does this compile Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why does this compile" Watch "Why does this compile" New topic
Author

Why does this compile

pankaj patil
Ranch Hand

Joined: Dec 19, 2004
Posts: 98
code 1)
final int i=50;
byte b=i;
code 2)
int i=50;
byte b=(byte)i;


in code 1) i dont have to typecast
in code 2) i have to typecast

can any one tell me the reason

with regards
pankaj


Regards,
Pankaj Patil
Svend Rost
Ranch Hand

Joined: Oct 23, 2002
Posts: 904
Guessing here, so please correct me if im wrong.

in 1) i is final, ie. the compiler knows it'll stay at 50
which isn't the case in 2).

/Svend Rost
pankaj patil
Ranch Hand

Joined: Dec 19, 2004
Posts: 98
but the size of int is more then the byte.

and final dose not allow the value to be changed . is that the final variable allocates only that much size, which is required at the initialization.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14156
    
  19

But the value of the final int i is 50 and cannot be changed. The compiler is smart enough to understand that the fixed value 50 fits into a byte (because the range for byte is -128 to +127). Try this:

This will give you an error.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Originally posted by pankaj patil:
but the size of int is more then the byte.

and final dose not allow the value to be changed . is that the final variable allocates only that much size, which is required at the initialization.


Because the variable is declared as final, the compiler will not allocate any memory for it. As mentioned above, the compiler is also smart enough to see that 50 is small enough to fit in a byte.

Layne


Java API Documentation
The Java Tutorial
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Why does this compile