• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why does this compile

 
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 904
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic