Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

I cant believe my eyes?

 
james gong
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
Ashish Hareet
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 464
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic