Java - why won't char '+' appear on the console?

Viewed 69

I am making a simple calculator and here is my code.

public static void main(String[] args) {
    int x = 3;
    int y = 7;
    char w = '+';
    
    System.out.println(x+w+y+"="+(x+y));
}

The result appears as '53 = 10' and I don't get why '+' won't appear and where 53 came from. The correct result '3+7=10' appears when I use (w) instead of w at the last line.

2 Answers

chars are implicitly convertible to integers in Java. x + w + y adds their values. The integer value of the character '+' happens to be 43, so you get 3 + 43 + 7 (= 53).

Putting the w into parentheses does not change that, contrary to what you said.

To fix this, make w into a String:

String w = "+";

this behavior is due the fact that the expression

x + w + y

is actually evaluated as 3 + 43 + 7, why, you may want to know? well because + is a char which is actually a number and 43 is is't value as integer.

Related