• Post Reply Bookmark Topic Watch Topic
  • New Topic

Short Data Type  RSS feed

 
Dipti Lokhande
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following example,
short a =100, b = 50, c;
c = (short)a+b;
In the above eg, compiler gives error as "Loss of presicion val"

Consider another example,
short c;
c = 100 + 50;
Here, this statement compiles successfully.

In the both cases, c var stores data 150, which is allowed in the second caes but not in the first case. So what could be the reason behind this?
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess you are probably aware when two data types shorter than ints are added they are promoted to int. The first program would work if you apply the case on the result like this c = (short)(a+b);.

The second program works because 100 and 50 are compile time constants.
[ May 21, 2007: Message edited by: Anupam Sinha ]
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are a few things happening here.

First of all, be aware that this line of code: c = (short)a + b;
is essentially this: c = ((short)a) + b;

Note that the cast has higher precedence than the + operator. So, you are first casting 'a' to a short (which does nothing because 'a' is already a short), and then you are performing the addition.

Second, note that the + operator produces an int (a 32-bit integer), even when you use it to add two shorts (16-bit integers) together. So the result of the expression on the right-hand side is a 32-bit int, and you're trying to put it into a 16-bit short - that's why you get the warning about a possible loss of precision.

Third, you could then ask why the following statement does not give you the warning: c = 100 + 50;

That is because the right-hand side of the expression (100 + 50) is a compile-time constant, and the compiler is smart enough to see that the result (150) will fit into a 16-bit short, and it doesn't need to warn you.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!