File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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!