1

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?

2
  • 3
    Because char is being promoted to int before the addition, basically. If you use a string instead (string c1 = "H";) it'll be fine.
    – Jon Skeet
    Jan 18, 2021 at 8:34
  • 2
    In a situation like char + int, the char gets converted to int first (its corresponding Unicode value (for beginners, the index in the ASCII table in this case)) and then it is a regular int + int addition.
    – Zabuzard
    Jan 18, 2021 at 8:35

3 Answers 3

6

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.

3
  • 1
    Well, to be accurate, 'H' is 72 even without the promotion to int, since char is a 16-bit unsigned integer according to the Java Language Specification.
    – Andreas
    Jan 18, 2021 at 8:41
  • Nice explanation, however using StringBuilder is safer.
    – IQbrod
    Jan 18, 2021 at 8:43
  • 3
    @IQbrod Safer might be the wrong term to explain why StringBuilder should be prefered. Performance might be more accurate. However, note that in this particular situation it does not apply since Java already optimizes single-statement concatenation, i.e. a + b + c + d (by using a StringBuilder itself in earlier versions and even better mechanisms afterwards).
    – Zabuzard
    Jan 18, 2021 at 8:46
2

You should use a StringBuilder introduced in Java 5 which has methods .append() with char/int/long etc... This class is the correct String concatenator in Java and allow you to concatenate any primitive (char/int/long ...) by its String representation.

System.out.println(4+3+"s"); // will print "7s"
System.out.println(StringBuilder.append(4).append(3).append("s").toString()); // will print "43s"

As mentionned by @Zabuzard Java compiler will replace String sum (+) by a StringBuilder but char+int does return an int (and int isn't a String). To get a detailed explanation about char + int returning int. I suggest you @JonSkeet answer :)

public class Main {
    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 = new StringBuilder()
                .append(c1)
                .append(num1)
                .append(c2)
                .append(b)
                .append(c3)
                .append(y)
                .append(c4)
                .append(f)
                .append(bool)
                .toString();
        System.out.println(s);
    }
}
5
  • While this answer gives a valuable solution, it would also be nice if it would explain OPs issue and why it fixes the problem.
    – Zabuzard
    Jan 18, 2021 at 8:44
  • @Zabuzard Jon did it perfectly, I won't copy paste his answer
    – IQbrod
    Jan 18, 2021 at 8:45
  • 2
    Fair. Note however that in this particular situation StringBuilder does not have any advantages to a plain concatenation a + b + c + d. Since the JLS demands that any Java implementation has to optimize such concatenations already. StringBuilder only has performance benefits if the concatenation happens over multiple statements (typically in a loop).
    – Zabuzard
    Jan 18, 2021 at 8:47
  • 1
    OP expect + as a String concatenator but in Java the correct String concatenator is StringBuilder.append() which prevents confusion of char+int returning an int
    – IQbrod
    Jan 18, 2021 at 8:54
  • 1
    That is fair, thats why I would suggest adding a more detailed explanation to highlight this aspect.
    – Zabuzard
    Jan 18, 2021 at 9:05
0

An other solution for this problem may be the usage of the static method

String.valueOf(c1)

A beter way is using the early mentioned StringBuilder but using String.valueOf is another solution with less effect op the code then using StringBuilder.

1
  • Thank you all for the detailed explanation Jan 18, 2021 at 9:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.