This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why this raises ab error?

 
Brian Smith
Ranch Hand
Posts: 232
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7023
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
     
    Don't get me started about those stupid light bulbs.
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic