• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Short literal representation

 
Greg Werner
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Short and sweet. The following obviously does not compile.



Other than casting line 3 RHS to be a short, is there any other notation I can use for a valid line of code (such as 14s which obviously is not Java).
 
fred rosenberger
lowercase baba
Bartender
Posts: 12186
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe this works:
 
Rob Spoor
Sheriff
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Casting is the only option. The reason is because the result of any mathematical operation is at least int, never short, char or byte.
 
Mina Daoud
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One of the main rules in Java is that any mathematical operation's result will be stored in a large size variable to avoid truncation. For example if you are adding int with long the result will be long. Hence, any operation on byte, char, or short will result an int even if you added 1 to a byte.There are 2 ways to store the result in the same data type:

a) you do explicit casting:

b) You can use the auto increment of short hand operations to ask the JVM to do implicit casting:


OR
 
Rob Spoor
Sheriff
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mina Daoud wrote:One of the main rules in Java is that any mathematical operation's result will be stored in a large size variable to avoid truncation. For example if you are adding int with long the result will be long. Hence, any operation on byte, char, or short will result an int even if you added 1 to a byte.

That's true, but even the following will fail:
Because like I said, the result is never smaller than int.
 
Mina Daoud
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Prime wrote:
That's true, but even the following will fail:
Because like I said, the result is never smaller than int.


Yea, that's why i mentioned if you added 1 to a byte the result will be int

 
Rob Spoor
Sheriff
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That case is slightly different since technically, 1 is an int value.
 
Mina Daoud
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes I agree with you in that.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic