简体   繁体   中英

How can a string accept an integer?

Can a variable String accept integer value as well. Or can we concat integer with a string ?

Example:

public class TestString1 {
        public static void main(String[] args) {
        String str = "420";
        str += 42;
        System.out.print(str);
    }
}

I was expecting compilation error over here because String was getting concatenated with an integer.

JLS documentation on String concatination operator( + )-

15.18.1 String Concatenation Operator +

If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time. The result is a reference to a String object (newly created, unless the expression is a compile-time constant expression (§15.28))that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string. If an operand of type String is null, then the string "null" is used instead of that operand

That is why String + int does not produce any error. And it prints 42042

None of the other answers have explained what's actually being executed here.

Your code will be converted to something like:

String str = "420";

// str += 42;
StringBuilder sb = new StringBuilder(str);
sb.append(42);  // which internally does something similar to String.valueOf()
str = sb.toString();

System.out.print(str);

int添加到String会将int附加到字符串,从而将int转换为字符串。

Anything that is given in double quotes is String and + is for concatenating string with an any value(int value).
So the integer value will be appended to the string. Here

String str = "420";
     str += 42; // 42 will be appended to 420 and result will be 42042

x=20 y=10

I am showing the Order of precedence below from Higher to Low:

B - Bracket O - Power DM - Division and Multiplication AS - Addition and Substraction

This works from Left to Right if the Operators are of Same precedence

Now

System.out.println("printing: " + x + y);

"printing: " : Is a String"

"+" : Is the only overloaded operator in Java which will concatenate Number to String. As we have 2 "+" operator here, and x+y falls after the "printing:" + as already taken place, Its considering x and y as Strings too.

So the output is 2010.

System.out.println("printing: " + x * y);

Here the

"*": Has higher precedence than +

So its x*y first then printing: +

So the output is 200

Do it like this if you want 200 as output in first case:

System.out.println("printing: "+ (x+y));

The Order of precedence of Bracket is higher to Addition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM