• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

cant assign final long to byte

 
Madushika Sewwandi
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49793
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2971
59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic