Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Binary numeric promotion

 
Harwinder Bhatia
Ranch Hand
Posts: 150
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How does
char primitiveChar = 'b'-'a';
work? Why isn't binary numeric promotion being applied to ('b' - 'a') and the result not an integer?
I know I'm missing something here.
Thanks
Harwinder
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Harwinder,
You are correct, binary promotion does occur. The type of 'b' - 'a' is int.
Since 'b' and 'a' are literals, 'b' - 'a' is a constant expression.
A constant expression of type int can be assigned to a char without casting.
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is a way to prove that 'b'-'a' is of type int.
 
Lakshmi Saradha
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Harwinder,
The result is an integer.

public class a
{
public static void main(String args[])
{
char a = 'b' - 'a';
System.out.println(a);
}

}
In the above mentioned code, it prints a character corresponding to the value 1(since 'b'-'a' will lead to 1).
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
char a = 'b' - 'a';
'b' and 'a' are literals of type char.
When the expression 'b'-'a' is evaluated, 'b' and 'a' are promoted to type int. The result of the expression 'b'-'a' is of type int.
When the = operation is performed, the value of the expression 'b'-'a' is converted to type char. The variable a holds a value of type char.
[ December 11, 2003: Message edited by: Marlene Miller ]
 
Sagarika nair
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A constant expression of type int can be assigned to a char without casting.
The above statement is true only if the integer value doesn't exceed 65535 right?Please correct me if I am wrong.
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whoops, I am getting sloppy. Thank you Sagarika for making the explanation better.
The value of the constant expression must be representable in the type of the variable.
[ December 11, 2003: Message edited by: Marlene Miller ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic