| Author |
cant assign final long to byte
|
Madushika Sewwandi
Greenhorn
Joined: Oct 05, 2012
Posts: 1
|
|
final int X=100;
byte b=X;
the above two statements do not give any compile error.but
final long X=100;
byte b=X;
gives a compile time error..I can,t imagine why?
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3860
|
|
Hi Madushika. Welcome to the Ranch!
The first example you give is explicitly allowed in the Java Language Specification - see here. It says:
In addition, if the expression is a constant expression (ยง15.28) of type byte, short, char, or int:
- A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
But you'll notice it doesn't mention long, so that isn't allowed. Why? I can't tell, other than to say it's hard to think of a good reason why you'd need it.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32830
|
|
|
Maybe they forgot to allow longs. It is likely, however, there is a reason for that omission; presumably they thought that longs, which are intended for larger numbers, are unlikely to be used as bytes. Unless you meet one of the original designers and ask them, you will probably never know.
|
 |
Tony Docherty
Bartender
Joined: Aug 07, 2007
Posts: 1223
|
|
Wow, I've been writing Java code since 1996 and have helped out on Java forums since 2005 and I've never noticed that before now, which just goes to show:
1. You learn something new every day
2. Matthew is correct when he says "it's hard to think of a good reason why you'd need it".
|
 |
Jeff Verdegan
Bartender
Joined: Jan 03, 2004
Posts: 6109
|
|
Tony Docherty wrote:Wow, I've been writing Java code since 1996 and have helped out on Java forums since 2005 and I've never noticed that before now, which just goes to show:
1. You learn something new every day
'98 and '99 for me, but otherwise, ditto.
|
 |
 |
|
|
subject: cant assign final long to byte
|
|
|