Kacy Raye
Kacy Raye

Reputation: 1322

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

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

    }
}

Upvotes: 8

Views: 178

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136102

'\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)); 

Upvotes: 2

Ankit
Ankit

Reputation: 6622

whatever is a char, and ++whatever means whatever = whatever + 1 (ignoring prefix order)

since there is an assignment involved, result is converted to char, so the char method is called. But in 3-4th print, there is no assignment, and as per rule, all the sum operation are by default happens in int. So before print operation, it sums up the char + char and char+int, and since there is no back assignment, it remains as int after the opration, so the integer method is called.

Upvotes: 0

durron597
durron597

Reputation: 32343

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

Upvotes: 8

Related Questions