aspose file tools*
The moose likes Beginning Java and the fly likes Why this raises ab error? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why this raises ab error?" Watch "Why this raises ab error?" New topic
Author

Why this raises ab error?

Brian Smith
Ranch Hand

Joined: Oct 26, 2002
Posts: 232
hi folks,
why this is a problem?
short a, b, c;
b = 3;
b = 1;
c = a + b; //raises an error Why?
c = (short) a + b; //okay
or
int c = a + b; //okay
thanks.
Paul Morano
Greenhorn

Joined: Jun 18, 2003
Posts: 7
I believe it is because the addition promotes the shorts to int's. Or, the result of the addition is an int. I forget which.
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
The addition promotes the operands to ints is correct, sir!
From The JLS (�5.6.2):
When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value of a numeric type, the following rules apply, in order, using widening conversion (�5.1.2) to convert operands as necessary:
  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.

  • [ June 22, 2003: Message edited by: Dirk Schreckmann ]

    [How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Why this raises ab error?
     
    Similar Threads
    Question on Wrapper classes
    More than one!!
    Adding short values
    java.lang
    Generic Array Creation