This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
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

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’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: is explicit conversion necessary for int to short
It's not a secret anymore!