-3

IntelliJ IDEA Capture

Why i am getting 152, I think it will give me an error. Please explain it.

    public class character {
    public static void main(String[] args) {
        char myCharValue1 = 'A';
        char myCharValue2 = '2';
        char myCharValue3 = '%';

        System.out.println(myCharValue1 + myCharValue2 + myCharValue3);
    }
}
aman5319
  • 662
  • 5
  • 16
Piyush
  • 123
  • 1
  • 7

2 Answers2

1

That is because chars refer to a number, which in turn has an ASCII representation.

Looking at an ASCII table you can see that the chars A, 2 and % have following values respectivly: 65, 50 and 37.

Adding those numbers together, you'll end up with 152 which is what you got in your example.


To print out those chars you could use following:

System.out.printf("%s%s%s&n", myCharValue1 + myCharValue2 + myCharValue3);

Which will print A2% (and a newline)

Lino
  • 19,604
  • 6
  • 47
  • 65
0

The concatenation + is for String. What you're doing is adding the numeric values of your chars and printing them together.

If you start with "" and then use + as Patrick Parker shows in his comment, it will become concatenation instead of simple addition and you'll get the result you expect.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • Hmm, just try to use it in different way. and Now i get that what is the actual problem. Thank you Kayaman. – Piyush Jul 19 '18 at 08:48