• Post Reply Bookmark Topic Watch Topic
  • New Topic

Numeric Promotion Rules  RSS feed

 
jnrohit Jain
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Following is the Numeric Promotion Rule in "Jeanne Boyarsky" book at Page #56:
"Smaller data types, namely byte, short, and char, are first promoted to int any time they're used with a Java binary arithmetic operator, even if neither of the operands is int."


Output:
a1 : 99

Why c1 and c2 not promoted to int before binary arithmetic operator applied?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
jnrohit Jain wrote:
Why c1 and c2 not promoted to int before binary arithmetic operator applied?


Please explain what you mean by this -- as the sum of the two char variables is definitely an int type?  Or are you expecting Java to promote the char to an int before the arithmetic operation (in the previous line)?

Henry
 
jnrohit Jain
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As per the rule, I was expecting Java to promote the char to an int before the arithmetic operation. I was expecting output number 3 (1 + 2).
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
jnrohit Jain wrote:I was expecting output number 3 (1 + 2).


Oh, I see the confusion... Basically, it is the type that is promoted. The char type is promoted to an int for the binary operation. Promoting the type (widening, in this case) has no effect on the value.

A '1' has an ASCII value of 49, and a '2' has an ACSII value of 50. So, when promoted to an int, and added, the sum is 99.

Henry
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
jnrohit Jain wrote:. . . I was expecting Java to promote the char to an int before the arithmetic operation. . . .
But they are promoted to ints. The value of '1' is not 1 however; it is 49 in decimal. 49 + 50 = 99
You can find the values of the ASCII subset of the char datatype here (and many other plcaes), where you can see '1' is 0x0031 which in decimal comes out as 49.
 
jnrohit Jain
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it. Thanks :-)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!