• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why does this compile

 
pankaj patil
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Svend Rost
Ranch Hand
Posts: 904
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15441
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic