• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

is explicit conversion necessary for int to short

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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);
}
}
 
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
reply
    Bookmark Topic Watch Topic
  • New Topic