• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why do int varibles and int literals operands behave differently?  RSS feed

 
Steven Kissh
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does the first assignment compile and the second fails to compile?
 
Henry Wong
author
Sheriff
Posts: 22678
113
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

First, here is the related portion of the JLS that specifies this...

http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.2


It's not just related to literals. It is related to a special case regarding compile time constants, of which literals is such.

Henry
 
Junilu Lacar
Sheriff
Posts: 10762
154
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here are more JLS references. (Caveat: the JLS can be difficult to read/understand):

http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.6.2
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.18.2

Since the right-hand side of line 7 involves only constants, the value of the expression can be determined at compile time and the Java compiler can see that a loss-less narrowing conversion to byte is possible.

On line 8, the expression involves variables, so the rules for binary numeric promotion apply. 

If you declare the variables on line 3 and 4 as final, the code will compile because the value of the expression can be evaluated at compile time and the compiler can see that it can be narrowed to fit into a byte.

This won't compile though because the value 128 won't fit into a byte
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!