File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes is explicit conversion necessary for int to short Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "is explicit conversion necessary for int to short" Watch "is explicit conversion necessary for int to short" New topic

is explicit conversion necessary for int to short

viswanadha Nirmala

Joined: Feb 13, 2002
Posts: 2
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;
Rob Ross

Joined: Jan 07, 2002
Posts: 2205
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 ]

SCJP 1.4
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
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

I agree. Here's the link:
subject: is explicit conversion necessary for int to short
Similar Threads
Doubts with parameter assignment
char to short and vice versa
Literal Assignment for following Example