Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I am returning integers instead of characters in the 3rd and 4th print statement?

Tags:

java

unicode

Can you please explain what's going in the last 2 print statements? That's where I get lost.

public class Something
{
    public static void main(String[] args){
        char whatever = '\u0041';

        System.out.println( '\u0041'); //prints A as expected

        System.out.println(++whatever); //prints B as expected

        System.out.println('\u0041' + 1); //prints 66 I understand the unicode of 1     adds up the 
        //unicode representing 66 but why am I even returning an integer when in the previous statement I returned a char?

        System.out.println('\u0041' + 'A'); //prints 130 I just wanted to show that adding an 
        //integer to the unicode in the previous print statement is not implicit casting because 
        //here I add a char which does not implicitly cast char on the returned value

    }
}
like image 473
Kacy Raye Avatar asked Apr 05 '13 04:04

Kacy Raye


2 Answers

This happens because of Binary Numeric Promotion

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:

  • If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed. Then:
  • 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.

Basically, both operands are converted to an int, and then the System.out.println(int foo) is called. The only types that can be returned by +, *, etc. are double, float, long, and int

like image 51
durron597 Avatar answered Nov 02 '22 04:11

durron597


'\u0041' + 1 produces int, you need to cast it to char so that javac binds the call to println(char) instead of prinln(int)

System.out.println((char)('\u0041' + 1)); 
like image 26
Evgeniy Dorofeev Avatar answered Nov 02 '22 06:11

Evgeniy Dorofeev