When I run the following code:
public class LianXi1
{
public static void main(String args[])
{
int a=12;
int b=23;
System.out.println("case 1"+a); //
System.out.println("case 2"+b); //
}
}
I get this result:
@ubuntu:~/mycode/test$ java LianXi1
case 112
case 223
But I don’t understand the result, who can help?
When you add a string and an integer together, it performs “String concatenation”, where it’s converting your integer into a string and sticking it on the end of the other string.
… is the same as
So your result will be the first string with the characters
12stuck on after it.Thus:
Case 112From the Java documentation on Strings:
But be careful! Adding works left to right, so what would the follwing print?
First, it does
1 + 2, which is equal to3.Then it does
3(the result of the last step)+ "test", which causes"3test"Next, it does
"3test" + 3, which results in"3test3".And finally,
"3test3 + 4is"3test34.As you can see, its a good idea to put parentheses around things to ensure they come out in the order you want.
(1 + 2) + "test" + (3 + 4)would be “3test7” because the math in the parentheses has precedence.