Dwarakanjali
Dwarakanjali

Reputation: 21

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?

Upvotes: 1

Views: 197

Answers (3)

IQbrod
IQbrod

Reputation: 2265

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);
    }
}

Upvotes: 2

jljvdm
jljvdm

Reputation: 66

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.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502016

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.

Upvotes: 6

Related Questions