Java – In Java, why the output of int a=(‘a’+’b’+’c’); are different form System.out.println(‘a’+’b’+’c’+””)

java

the original question is like this.

public class test {
    public static void main(String[] args){
        int i = '1' + '2' + '3' + "";
        System.out.println(i);
    }
}

and this gives me an error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Type mismatch: cannot convert from String to int

then I changed the code like this:

public class test {
    public static void main(String[] args){
        int i = '1' + '2' + '3';
        System.out.println(i);
    }
}

the out put is 150.

but when I write my code like this:

public class test {
    public static void main(String[] args){
        System.out.println('a'+'b'+'c'+"");
    }
}

the output become 294.

I wonder why.

Best Solution

  • The first one does not compile, because you concatenate a String at the end which cause the value to be a String which can't be converted directly to int.
  • The output of the second one is 150, because ASCII value for character 1,2,3 are 49,50,51 which return 150 when doing the addition.
  • The output of the last one is 294, because you are doing an addition of char values in the ASCII table (97+98+99)

You can verify the values here for a,b and c (or any other character).

Edit : To explain why the last one output the correct value instead of throwing an error, you first sum all the values as explained before, then convert it to a String adding "" to the sum of the ASCII values of the chars. However, the println method expect a String which is why it does not throw any error.

The first one would work if you would do Integer.parseInt('1' + '2' + '3' + "");