Search code examples
javatype-conversionstring-concatenation

char + int gives unexpected result


I need to print 'H3110 w0r1d 2.0 true' as output. Below is the code written and getting output as '3182 w0r1d 2.0 true'.

public class HelloWorld {
    public static void main (String[] args){

        char c1= 'H';
        int num1 = 3110;
        char c2='w';
        byte b=0;
        char c3='r';
        int y=1;
        char c4='d';

        float f = 2.0f;
        boolean bool= true;
        String s = c1+num1 + " " + c2+b+c3+y+c4 + " " + f + " " + bool;
        System.out.println(s);
    }
}

Query: If I concatenate H and 3110, it is printing as 3182. Why so?


Solution

  • The + operator does not use string concatenation unless at least one operand is of type String. Ignoring the remainder of the + operators, you're basically looking for "what happens if I add char and int together" - and the answer is "char is promoted to int, and normal integer addition is performed". The promoted value of 'H' is 72 (as that's the UTF-16 numeric value of 'H'), hence the result of 3182.

    The simplest fix for this in your case would be to change the type of c1 to String instead of char:

    String c1 = "H";
    

    That will then use string concatenation instead of integer addition.