permaculture playing cards*
The moose likes Java in General and the fly likes cant assign final long to byte Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "cant assign final long to byte" Watch "cant assign final long to byte" New topic
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: 4396
    
    8

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: 39044
    
  23
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: 2297
    
  49
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
    
    6

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.


 
GeeCON Prague 2014
 
subject: cant assign final long to byte