4

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.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Nari
  • 49
  • 7
  • Related: https://stackoverflow.com/questions/8688668/in-java-is-the-result-of-the-addition-of-two-chars-an-int-or-a-char – Lino Jul 08 '20 at 12:39

2 Answers2

6

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 = "+";
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • The first key point is that `+` is left-associative, so `x+w+y+"="+(x+y)` is equivalent to `((((x+w)+y)+"=")+(x+y))`; the second key point is that `+` is string concatenation if either operand is a `String`, and numeric addition otherwise. `x+w` is therefore evaluated using numeric addition (a `char` is not a `String`), so it's `3 + 43 = 46`. Then `46 + y` is evaluated using numeric addition, giving `53`. Then `53 + "="` is the first subexpression to be evaluated using string concatenation, because `"="` is a String. – Andy Turner Jul 08 '20 at 12:43
  • Wow thanks for such a kind comment! Really helped me a lot. – Nari Jul 08 '20 at 13:21
4

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.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97