Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0125-preview· openaiHugging Face Suzhen/CodeChat

I am using java 21 and noticed that if I add an int to a string, the result will the be…

  1. 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?

  2. Assistant

    The ability to concatenate an int or any other primitive type or object with a String via 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 a String and an int (or any other primitive type), the non-string value is converted to a String, and both strings are then concatenated. This process is facilitated by the StringBuilder (or StringBuffer in 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 StringBuilder for 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.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.