This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes primitive type convert Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "primitive type convert" Watch "primitive type convert" New topic

primitive type convert

Jello Yao

Joined: Jan 05, 2003
Posts: 13
class MyClass
public static void main(String []args)
final int i=100;
byte b = i;
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

Joined: Dec 10, 2002
Posts: 35
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

Joined: Jan 10, 2003
Posts: 284
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?

giddee up
John Lee
Ranch Hand

Joined: Aug 05, 2001
Posts: 2545
Once it is declared as final, it won't change. So the compiler know for sure i=100 is ok with byte.
I agree. Here's the link:
subject: primitive type convert
It's not a secret anymore!