char + int gives unexpected result

送分小仙女□ 提交于 2021-02-05 08:06:31

问题


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?


回答1:


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.




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



回答3:


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.



来源:https://stackoverflow.com/questions/65771038/char-int-gives-unexpected-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!