• Post Reply Bookmark Topic Watch Topic
  • New Topic

short variables and int literals  RSS feed

 
Georgios Peditis
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!
Im studying for the oca exams. (java 8) and in the book i read that literals are considered int.
So im wondering why the first code works and the second doesnt.





I can understand why the second doesnt work but i cant understand why the first one works.

Thanks in advance or your hep.
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simply, it is possible to assign to a short from a compile‑time constant (officially called a constant expression) known to the compiler to be within the range of a short. Line 2 of the second piece of code has a variable to its right; had you marked the int as final in line 1, that would become a constant rather than a variable.

The compiler does not check whether you wrote a line 1½ similar to this:-
y = 1234567890;
 
Georgios Peditis
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Campbell for the fast reply!
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a pleasure
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!