This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach 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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets 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
Author

is explicit conversion necessary for int to short

viswanadha Nirmala
Greenhorn

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;
System.out.println(s1);
}
}
Rob Ross
Bartender

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 ]

Rob
SCJP 1.4
Dave Vick
Ranch Hand

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


Dave
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: is explicit conversion necessary for int to short
 
Similar Threads
Doubts with parameter assignment
Literal Assignment for following Example
operators
char to short and vice versa
Assignments