• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

is explicit conversion necessary for int to short

 
viswanadha Nirmala
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Though the maximum range of the short data type is 2^15-1(2 power 15 -1), why am i getting the error message as:"Explicit cast needed to convert
int to short" for the following code:
public class Shrt
{
public static void main(String args[])
{
short s =9;
short s1 = s+s;
System.out.println(s1);
}
}
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This statement:
short s1 = s+s;
is subject to arithmetic promotion; on the right hand side, each s is first widened to an int, then the addition is performed, and the type of the result is an int. Since an int is "too wide" to fit into a short, you can't assign the result to a short without an explicit cast.
short s1 = (short) (s+s);
[ February 13, 2002: Message edited by: Rob Ross ]
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
viswanadha
Whenever you do a binary operation on two opreands the operands are promoted to at least an int. For the real in depth explaination check out the JLS section 5.6.2.
The end result is that the result of the expression is an int, and to get it back into a short you'll have to cast it.
hope that helped
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic