aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes I cant believe my eyes? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "I cant believe my eyes?" Watch "I cant believe my eyes?" New topic
Author

I cant believe my eyes?

james gong
Ranch Hand

Joined: May 29, 2001
Posts: 48

public class ADirtyOne
{
private final int i =10;
private byte k = i;

}

I had thought the code wouldn't compile(it need a explicit cast),but when I compile ,it compile clearly without any warning.
I thought the int is wide than byte ,so when convert a int to a byte ,need a explicit cast( private byte k=(byte)i
Am I right?
Guoqiao Sun
Ranch Hand

Joined: Jul 18, 2001
Posts: 317
Hi, james, the compiler takes initialised final primitive variables as constants, so you code is the same as:

Note that the following code does not compile:

when the final identifier is removed.
Hope it helps.
Guoqiao

[This message has been edited by Guoqiao Sun (edited July 31, 2001).]


Guoqiao Sun<br />SCJP2 SCWCD2<br />Creator of <a href="http://www.jiris.com/" target="_blank" rel="nofollow">www.jiris.com</a>, Java resource, mock exam, forum
Ashish Hareet
Ranch Hand

Joined: Jul 14, 2001
Posts: 375
Hi James,
private final int i = 127;
byte k = i ;
This will compile . The reason being that 127 fit's as a byte & the fact that i is final which means it won't change throughout it's lifetime .
Now try
private final int i = 128;
byte k = i ;
This won't compile cause i doesn't fit the byte range .
Ashish
Ragu Sivaraman
Ranch Hand

Joined: Jul 20, 2001
Posts: 464
Bottom line... check for 2 things
1. Range of values
2. Final declaration
int i = 127;
byte b = i; //This will never compile unless explicitly casted
//or make i as final
byte b = 127; //Narrowing conversion looks for only for range
HTH
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: I cant believe my eyes?