Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

primitive type convert

 
Jello Yao
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
 
kishor rao
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.
 
Jasper Vader
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?
 
John Lee
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