I am using java 21 and noticed that if I add an int to a string, the result will the be…
- User
I am using java 21 and noticed that if I add an int to a string, the result will the be a new string that is the concatenation of the original string with the number. Since when can you do this in java?
- Assistant
The ability to concatenate an
intor any other primitive type or object with aStringvia the+operator in Java has been available since early versions of Java, specifically Java 1.0. This feature has been part of the language for a very long time and has remained consistent across Java versions.When you use the
+operator between aStringand anint(or any other primitive type), the non-string value is converted to aString, and both strings are then concatenated. This process is facilitated by theStringBuilder(orStringBufferin synchronized contexts or older versions) class behind the scenes in the compiled bytecode, converting the operation into something similar to:new StringBuilder().append("YourString").append(yourIntValue).toString();This behavior is very convenient for quick and readable string concatenation, and it's one of the first things many developers learn in Java. However, for complex concatenations or those happening in a loop, it's often recommended to explicitly use
StringBuilderfor performance reasons.So, to directly answer your question: This ability has been in Java since the beginning, and as of Java 21, no changes have been made to remove or significantly alter this feature.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.