• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

primitive type convert  RSS feed

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class MyClass
{
public static void main(String []args)
{
final int i=100;
byte b = i;
System.out.println(b);
}
}
After run the above code, it compile and print 100. Why it does not need an explicitly cast? i is larger than byte, right? Please help! Thanks
 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it works only if the int is declared as final. if the int is not a constant the compiler gives a loss of precision error.
 
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that is really bizarre, i had not heard of this (i am of course still learning).
i guess, it is allowed, because if the int is final (not allowed to be changed), and fits in the range of a byte, then it can be done?
 
Ranch Hand
Posts: 2545
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Once it is declared as final, it won't change. So the compiler know for sure i=100 is ok with byte.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!