What happens if concate String value and int?

Can you predict the output/result of the following code?

String s = "A String ";
s += 12345;
System.out.print(s);

The answer is: “A String 12345“.

The reason for that is described in the desciption of String class in Java 2 Platform SE 5.0 API:

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java.

Previous Post
Next Post