Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

char

println

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.

like image 293
Nari Avatar asked Dec 23 '22 17:12

Nari


1 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 = "+";
like image 77
Konrad Rudolph Avatar answered Dec 30 '22 11:12

Konrad Rudolph