How many String objects would be created when concatenating multiple Strings?Is an array a primitive type or...

How do proponents of Sola Scriptura address the ministry of those Apostles who authored no parts of Scripture?

Nothing like a good ol' game of ModTen

Did anyone try to find the little box that held Professor Moriarty and his wife after the crash?

Can RMSE and MAE have the same value?

Are the players on the same team as the DM?

How to prevent clipped screen edges on my TV, HDMI-connected?

Uri tokenizer as a simple state machine

How do I, an introvert, communicate to my friend and only colleague, an extrovert, that I want to spend my scheduled breaks without them?

“T” in subscript in formulas

Duplicate Files

How long do you think advanced cybernetic implants would plausibly last?

What are some interesting features that are common cross-linguistically but don't exist in English?

Compelling story with the world as a villain

Why does Windows store Wi-Fi passwords in a reversable format?

Duplicate instruments in unison in an orchestra

Another solution to create a set with two conditions

Round towards zero

What should come first—characters or plot?

"Sorry to bother you" in an email?

What verb is かまされる?

Why doesn't 'd /= d' throw a division by zero exception?

Where was Carl Sagan working on a plan to detonate a nuke on the Moon? Where was he applying when he leaked it?

How do you harvest carrots in creative mode?

Did a flight controller ever answer Flight with a no-go?



How many String objects would be created when concatenating multiple Strings?


Is an array a primitive type or an object (or something else entirely)?How to concatenate text from multiple rows into a single text string in SQL server?How do I iterate over the words of a string?How do I read / convert an InputStream into a String in Java?Creating multiline strings in JavaScriptCount the number of occurrences of a character in a string in JavascriptHow do I make the first letter of a string uppercase in JavaScript?How to replace all occurrences of a string?How to check whether a string contains a substring in JavaScript?How to concatenate string variables in BashHow do I convert a String to an int in Java?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







10















I was asked in an interview about the number of objects that will be created on the given problem:



String str1 = "First";
String str2 = "Second";
String str3 = "Third";
String str4 = str1 + str2 + str3;


I answered that there would be 6 objects created in the string pool.




3 would be for each of the three variables.

1 would be for str1 + str2 (let's say str).

1 would be for str2 + str3.

1 would be for the str + str3 (str = str1 + str2).




Is the answer I gave correct? If not, what is the correct answer?










share|improve this question









New contributor



bhpsh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

















  • 10





    Why would str2 + str3 be one of the objects?

    – Jacob G.
    yesterday






  • 4





    I am not entirely sure whether it is defined in the JLS, but when concatenating Strings, the compiler normally generates a StringBuilder to concatenate the Strings. I am not entirely sure how the StringBuilder internally handles the concatenation, but I would say that at least five Objects are created: one for str1 to str3, one StringBuilder and the final String for String4.

    – Turing85
    yesterday






  • 1





    Update: The JLS actually defines that "a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression." In other words: without further information, the question cannot be definitively answered.

    – Turing85
    yesterday






  • 4





    Nothing against you, but I hate questions like that. What is the deeper meaning of such questions? Especially in an interview? What skills does the interviewer want to find out?

    – RedCam
    yesterday






  • 2





    And we have... "Interview questions by people who think it's a good idea to second guess an extremely tuned compiler on trivial stuff". "I will take the daily double for 10'000, Alex!"

    – David Tonhofer
    19 hours ago


















10















I was asked in an interview about the number of objects that will be created on the given problem:



String str1 = "First";
String str2 = "Second";
String str3 = "Third";
String str4 = str1 + str2 + str3;


I answered that there would be 6 objects created in the string pool.




3 would be for each of the three variables.

1 would be for str1 + str2 (let's say str).

1 would be for str2 + str3.

1 would be for the str + str3 (str = str1 + str2).




Is the answer I gave correct? If not, what is the correct answer?










share|improve this question









New contributor



bhpsh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

















  • 10





    Why would str2 + str3 be one of the objects?

    – Jacob G.
    yesterday






  • 4





    I am not entirely sure whether it is defined in the JLS, but when concatenating Strings, the compiler normally generates a StringBuilder to concatenate the Strings. I am not entirely sure how the StringBuilder internally handles the concatenation, but I would say that at least five Objects are created: one for str1 to str3, one StringBuilder and the final String for String4.

    – Turing85
    yesterday






  • 1





    Update: The JLS actually defines that "a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression." In other words: without further information, the question cannot be definitively answered.

    – Turing85
    yesterday






  • 4





    Nothing against you, but I hate questions like that. What is the deeper meaning of such questions? Especially in an interview? What skills does the interviewer want to find out?

    – RedCam
    yesterday






  • 2





    And we have... "Interview questions by people who think it's a good idea to second guess an extremely tuned compiler on trivial stuff". "I will take the daily double for 10'000, Alex!"

    – David Tonhofer
    19 hours ago














10












10








10


3






I was asked in an interview about the number of objects that will be created on the given problem:



String str1 = "First";
String str2 = "Second";
String str3 = "Third";
String str4 = str1 + str2 + str3;


I answered that there would be 6 objects created in the string pool.




3 would be for each of the three variables.

1 would be for str1 + str2 (let's say str).

1 would be for str2 + str3.

1 would be for the str + str3 (str = str1 + str2).




Is the answer I gave correct? If not, what is the correct answer?










share|improve this question









New contributor



bhpsh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











I was asked in an interview about the number of objects that will be created on the given problem:



String str1 = "First";
String str2 = "Second";
String str3 = "Third";
String str4 = str1 + str2 + str3;


I answered that there would be 6 objects created in the string pool.




3 would be for each of the three variables.

1 would be for str1 + str2 (let's say str).

1 would be for str2 + str3.

1 would be for the str + str3 (str = str1 + str2).




Is the answer I gave correct? If not, what is the correct answer?







java string string-concatenation string-pool string-building






share|improve this question









New contributor



bhpsh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










share|improve this question









New contributor



bhpsh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








share|improve this question




share|improve this question








edited 19 hours ago









Dukeling

46.2k10 gold badges66 silver badges112 bronze badges




46.2k10 gold badges66 silver badges112 bronze badges






New contributor



bhpsh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








asked yesterday









bhpshbhpsh

604 bronze badges




604 bronze badges




New contributor



bhpsh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




New contributor




bhpsh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.













  • 10





    Why would str2 + str3 be one of the objects?

    – Jacob G.
    yesterday






  • 4





    I am not entirely sure whether it is defined in the JLS, but when concatenating Strings, the compiler normally generates a StringBuilder to concatenate the Strings. I am not entirely sure how the StringBuilder internally handles the concatenation, but I would say that at least five Objects are created: one for str1 to str3, one StringBuilder and the final String for String4.

    – Turing85
    yesterday






  • 1





    Update: The JLS actually defines that "a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression." In other words: without further information, the question cannot be definitively answered.

    – Turing85
    yesterday






  • 4





    Nothing against you, but I hate questions like that. What is the deeper meaning of such questions? Especially in an interview? What skills does the interviewer want to find out?

    – RedCam
    yesterday






  • 2





    And we have... "Interview questions by people who think it's a good idea to second guess an extremely tuned compiler on trivial stuff". "I will take the daily double for 10'000, Alex!"

    – David Tonhofer
    19 hours ago














  • 10





    Why would str2 + str3 be one of the objects?

    – Jacob G.
    yesterday






  • 4





    I am not entirely sure whether it is defined in the JLS, but when concatenating Strings, the compiler normally generates a StringBuilder to concatenate the Strings. I am not entirely sure how the StringBuilder internally handles the concatenation, but I would say that at least five Objects are created: one for str1 to str3, one StringBuilder and the final String for String4.

    – Turing85
    yesterday






  • 1





    Update: The JLS actually defines that "a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression." In other words: without further information, the question cannot be definitively answered.

    – Turing85
    yesterday






  • 4





    Nothing against you, but I hate questions like that. What is the deeper meaning of such questions? Especially in an interview? What skills does the interviewer want to find out?

    – RedCam
    yesterday






  • 2





    And we have... "Interview questions by people who think it's a good idea to second guess an extremely tuned compiler on trivial stuff". "I will take the daily double for 10'000, Alex!"

    – David Tonhofer
    19 hours ago








10




10





Why would str2 + str3 be one of the objects?

– Jacob G.
yesterday





Why would str2 + str3 be one of the objects?

– Jacob G.
yesterday




4




4





I am not entirely sure whether it is defined in the JLS, but when concatenating Strings, the compiler normally generates a StringBuilder to concatenate the Strings. I am not entirely sure how the StringBuilder internally handles the concatenation, but I would say that at least five Objects are created: one for str1 to str3, one StringBuilder and the final String for String4.

– Turing85
yesterday





I am not entirely sure whether it is defined in the JLS, but when concatenating Strings, the compiler normally generates a StringBuilder to concatenate the Strings. I am not entirely sure how the StringBuilder internally handles the concatenation, but I would say that at least five Objects are created: one for str1 to str3, one StringBuilder and the final String for String4.

– Turing85
yesterday




1




1





Update: The JLS actually defines that "a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression." In other words: without further information, the question cannot be definitively answered.

– Turing85
yesterday





Update: The JLS actually defines that "a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression." In other words: without further information, the question cannot be definitively answered.

– Turing85
yesterday




4




4





Nothing against you, but I hate questions like that. What is the deeper meaning of such questions? Especially in an interview? What skills does the interviewer want to find out?

– RedCam
yesterday





Nothing against you, but I hate questions like that. What is the deeper meaning of such questions? Especially in an interview? What skills does the interviewer want to find out?

– RedCam
yesterday




2




2





And we have... "Interview questions by people who think it's a good idea to second guess an extremely tuned compiler on trivial stuff". "I will take the daily double for 10'000, Alex!"

– David Tonhofer
19 hours ago





And we have... "Interview questions by people who think it's a good idea to second guess an extremely tuned compiler on trivial stuff". "I will take the daily double for 10'000, Alex!"

– David Tonhofer
19 hours ago












6 Answers
6






active

oldest

votes


















16















Any answer to your question will depend on the JVM implementation and the Java version currently being used. It's a stupid an unreasonable question to ask in an interview.



Java 8



On my machine, with Java 1.8.0_201, your snippet results in this bytecode



L0
LINENUMBER 13 L0
LDC "First"
ASTORE 1
L1
LINENUMBER 14 L1
LDC "Second"
ASTORE 2
L2
LINENUMBER 15 L2
LDC "Third"
ASTORE 3
L3
LINENUMBER 16 L3
NEW java/lang/StringBuilder
DUP
INVOKESPECIAL java/lang/StringBuilder.<init> ()V
ALOAD 1
INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
ALOAD 2
INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
ALOAD 3
INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
ASTORE 4


which proves that 5 objects are being created (3 String literals*, 1 StringBuilder, 1 dynamically produced String instance by StringBuilder#toString).



Java 12



On my machine, with Java 12.0.2, the bytecode is



// identical to the bytecode above
L3
LINENUMBER 16 L3
ALOAD 1
ALOAD 2
ALOAD 3
INVOKEDYNAMIC makeConcatWithConstants(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; [
// handle kind 0x6 : INVOKESTATIC
java/lang/invoke/StringConcatFactory.makeConcatWithConstants(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;
// arguments:
"u0001u0001u0001"
]
ASTORE 4


which magically changes "the correct answer" to 4 objects since there is no intermediate StringBuilder involved.





*Let's dig a bit deeper.




12.5. Creation of New Class Instances



A new class instance may be implicitly created in the following situations:




  • Loading of a class or interface that contains a string literal (§3.10.5) may create a new String object to represent the literal. (This will not occur if a string denoting the same sequence of Unicode code points has previously been interned.)




In other words, when you start an application, there are already objects in the String pool. You barely know what they are and where they come from (unless you scan all loaded classes for all literals they contain).



The java.lang.String class will be undoubtedly loaded as an essential JVM class, meaning all its literals will be created and placed into the pool.



Let's take a randomly selected snippet from the source code of String, pick a couple of literals from it, put a breakpoint at the very beginning of our programme, and examine if the pool contains these literals.



public final class String
implements java.io.Serializable, Comparable<String>, CharSequence,
Constable, ConstantDesc {
...
public String repeat(int count) {
// ...
if (Integer.MAX_VALUE / count < len) {
throw new OutOfMemoryError("Repeating " + len + " bytes String " + count +
" times will produce a String exceeding maximum size.");
}
}
...
}


They are there indeed.





As an interesting find, this IDEA's filtering has a side effect: the substrings I was looking for have been added to the pool as well. The pool size increased by one ("bytes String" was added) after I applied this.contains("bytes String").



Where does this leave us?



We have no idea whether "First" was created and interned before we call String str1 = "First";, so we can't state firmly that the line creates a new instance.






share|improve this answer























  • 2





    each string also contains a byte[], same for StringBuilder (and first one will also create a static byte[0]) and eventually (haven't checked) the StringBuilder can create a new, bigger buffer (if needed) (just proving your 2nd sentence true)

    – Carlos Heuberger
    yesterday








  • 1





    thinking about it, is LDC creating a (new) Object? or just using one? (the literal could have been used before)

    – Carlos Heuberger
    yesterday













  • @CarlosHeuberger "Loading of a class or interface that contains a string literal may create a new String object to represent the literal. (This will not occur if a string denoting the same sequence of Unicode code points has previously been interned.)"

    – Andrew Tobilko
    21 hours ago













  • not new and just confirming what I wrote: "the literal could have been used before" exactly because that would mean it is already created/interned! But loading a class or interface is not part of code posted in question (despite "on the given problem" is quite open)

    – Carlos Heuberger
    15 hours ago













  • "unreasonable question to ask in an interview" - the funny part that you found question useful and interesting and most of your answer actually does not need anything you will not have at typical interview but good understanding how Java handles strings. I.e. I doubt you need anything to explain that concatenation can be optimized into method call at compile time. Indeed it would be hard to come up with diassembled code and precise versions... but answer like that may show how well someone knows the language/framework and things like defined/unspecified behavior...

    – Alexei Levenkov
    5 hours ago





















13















With the given information, the question cannot be definitely answered. As is stated in the JLS, §15.18.1:




... To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.




This means that the answer depends at least on the concrete Java compiler used.



I think the best we can do is give an interval as answer:




  • a smart compiler may be able to infer that str1 to str3 are never used and fold the concatenation during compilation, such that only one String-object is created (the one referenced by str4)

  • The maximum sensible number of Strings created should be 5: one each for str1 to str3, one for tmp = str1 + str2 and one for str4 = tmp + str3.


So... my answer would be "something between one to five String-objects". As to the total number of objects created just for this operation... I do not know. This may also depend how exactly e.g. StringBuffer is implemented.



As an aside: I wonder what the reason behind asking such questions is. Normally, one does not need to care about those details.






share|improve this answer























  • 9





    "I wonder what the reason behind asking such questions is." - It reminds me of the "I-read-it-yesterday-I-will-ask-it-tomorrow" type of interviewers

    – Andrew Tobilko
    yesterday








  • 1





    I'd think it could just be a conversation starter on how Strings are modelled and to get some insight into how a candidate thinks about java objects, whether the candidate is aware of potential instantiation through the '+' operator etc. It's likely less important to know the exact answer, but to make some sense when arguing about it. Not exactly a question I would ask, but I could see it as reasonable if used in that regard.

    – Frank Hopkins
    yesterday











  • Either a trivia question, or a really deep question (as answered above). Why is it important? The more temporaries, the more often garbage must be collected, which affects performance.

    – ChuckCottrill
    yesterday











  • @ChuckCottrill your statement about the GC is true, but I think this situation is a little bit different. We are talking about compile-time constants and compiler transformations. These processes are designed to improve performance and should be opaque to the programmer. I really hope it was meant as a conversational starter...

    – Turing85
    23 hours ago






  • 2





    The smart compiler might notice that str4 isn't used anywhere either, so I think the minimum count should be 0 :-)

    – Bergi
    13 hours ago





















4















Java 8 will likely create 5 objects:




  • 3 for the 3 variables

  • 1 StringBuilder

  • 1 for the concatenated String


With Java 9 things changed though and String concatenation does not use StringBuilder anymore.






share|improve this answer























  • 4





    Good answer, but for Java 8, I think you're overlooking the char[] object used by the implementation of StringBuilder.

    – Andy Thomas
    yesterday








  • 1





    stackoverflow.com/questions/12806739/…

    – 17slim
    yesterday






  • 5





    @3limin4t0r "char[] is a primitive value" - Nope.

    – Turing85
    yesterday








  • 2





    @AndyThomas if you count the char[] you will end up with even more as also String uses char[] and some constructors also create copies of char[].

    – Puce
    yesterday











  • That's a good point actually, which leads me to believe @Turing85's answer is more correct without further clarification from the interviewers.

    – 17slim
    yesterday



















1















It should be 5:




  • three for the three literals (assigned to str1, str2 and str3)


  • one for str1 + str2


  • one for (result from the previous operation) + str3 (assigned to str4)







share|improve this answer




























  • str1 + str2 will not be concatenated to a String in all Java since quite many years.

    – Puce
    yesterday



















0















Concatenation operation doesn't create those many String objects. It creates aStringBuilder and then appends the strings. So there may be 5 objects,
3 (variables) + 1 (sb) + 1 (Concatenated string).






share|improve this answer























  • 1





    It might be 5.

    – Nexevis
    yesterday











  • As was stated many times, the JLS says that "a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression." Emphasis is on may.

    – Turing85
    yesterday













  • @Turing85 agreed. Updated.

    – javaaddict
    yesterday



















0















A conformant Java implementation can concatenate the strings any number of ways, at run time or at compile time, needing any number of run-time objects, including zero objects if it detects that the result is not needed at run time.






share|improve this answer




























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });






    bhpsh is a new contributor. Be nice, and check out our Code of Conduct.










    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57630924%2fhow-many-string-objects-would-be-created-when-concatenating-multiple-strings%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    6 Answers
    6






    active

    oldest

    votes








    6 Answers
    6






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    16















    Any answer to your question will depend on the JVM implementation and the Java version currently being used. It's a stupid an unreasonable question to ask in an interview.



    Java 8



    On my machine, with Java 1.8.0_201, your snippet results in this bytecode



    L0
    LINENUMBER 13 L0
    LDC "First"
    ASTORE 1
    L1
    LINENUMBER 14 L1
    LDC "Second"
    ASTORE 2
    L2
    LINENUMBER 15 L2
    LDC "Third"
    ASTORE 3
    L3
    LINENUMBER 16 L3
    NEW java/lang/StringBuilder
    DUP
    INVOKESPECIAL java/lang/StringBuilder.<init> ()V
    ALOAD 1
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 2
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 3
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
    ASTORE 4


    which proves that 5 objects are being created (3 String literals*, 1 StringBuilder, 1 dynamically produced String instance by StringBuilder#toString).



    Java 12



    On my machine, with Java 12.0.2, the bytecode is



    // identical to the bytecode above
    L3
    LINENUMBER 16 L3
    ALOAD 1
    ALOAD 2
    ALOAD 3
    INVOKEDYNAMIC makeConcatWithConstants(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; [
    // handle kind 0x6 : INVOKESTATIC
    java/lang/invoke/StringConcatFactory.makeConcatWithConstants(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;
    // arguments:
    "u0001u0001u0001"
    ]
    ASTORE 4


    which magically changes "the correct answer" to 4 objects since there is no intermediate StringBuilder involved.





    *Let's dig a bit deeper.




    12.5. Creation of New Class Instances



    A new class instance may be implicitly created in the following situations:




    • Loading of a class or interface that contains a string literal (§3.10.5) may create a new String object to represent the literal. (This will not occur if a string denoting the same sequence of Unicode code points has previously been interned.)




    In other words, when you start an application, there are already objects in the String pool. You barely know what they are and where they come from (unless you scan all loaded classes for all literals they contain).



    The java.lang.String class will be undoubtedly loaded as an essential JVM class, meaning all its literals will be created and placed into the pool.



    Let's take a randomly selected snippet from the source code of String, pick a couple of literals from it, put a breakpoint at the very beginning of our programme, and examine if the pool contains these literals.



    public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence,
    Constable, ConstantDesc {
    ...
    public String repeat(int count) {
    // ...
    if (Integer.MAX_VALUE / count < len) {
    throw new OutOfMemoryError("Repeating " + len + " bytes String " + count +
    " times will produce a String exceeding maximum size.");
    }
    }
    ...
    }


    They are there indeed.





    As an interesting find, this IDEA's filtering has a side effect: the substrings I was looking for have been added to the pool as well. The pool size increased by one ("bytes String" was added) after I applied this.contains("bytes String").



    Where does this leave us?



    We have no idea whether "First" was created and interned before we call String str1 = "First";, so we can't state firmly that the line creates a new instance.






    share|improve this answer























    • 2





      each string also contains a byte[], same for StringBuilder (and first one will also create a static byte[0]) and eventually (haven't checked) the StringBuilder can create a new, bigger buffer (if needed) (just proving your 2nd sentence true)

      – Carlos Heuberger
      yesterday








    • 1





      thinking about it, is LDC creating a (new) Object? or just using one? (the literal could have been used before)

      – Carlos Heuberger
      yesterday













    • @CarlosHeuberger "Loading of a class or interface that contains a string literal may create a new String object to represent the literal. (This will not occur if a string denoting the same sequence of Unicode code points has previously been interned.)"

      – Andrew Tobilko
      21 hours ago













    • not new and just confirming what I wrote: "the literal could have been used before" exactly because that would mean it is already created/interned! But loading a class or interface is not part of code posted in question (despite "on the given problem" is quite open)

      – Carlos Heuberger
      15 hours ago













    • "unreasonable question to ask in an interview" - the funny part that you found question useful and interesting and most of your answer actually does not need anything you will not have at typical interview but good understanding how Java handles strings. I.e. I doubt you need anything to explain that concatenation can be optimized into method call at compile time. Indeed it would be hard to come up with diassembled code and precise versions... but answer like that may show how well someone knows the language/framework and things like defined/unspecified behavior...

      – Alexei Levenkov
      5 hours ago


















    16















    Any answer to your question will depend on the JVM implementation and the Java version currently being used. It's a stupid an unreasonable question to ask in an interview.



    Java 8



    On my machine, with Java 1.8.0_201, your snippet results in this bytecode



    L0
    LINENUMBER 13 L0
    LDC "First"
    ASTORE 1
    L1
    LINENUMBER 14 L1
    LDC "Second"
    ASTORE 2
    L2
    LINENUMBER 15 L2
    LDC "Third"
    ASTORE 3
    L3
    LINENUMBER 16 L3
    NEW java/lang/StringBuilder
    DUP
    INVOKESPECIAL java/lang/StringBuilder.<init> ()V
    ALOAD 1
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 2
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 3
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
    ASTORE 4


    which proves that 5 objects are being created (3 String literals*, 1 StringBuilder, 1 dynamically produced String instance by StringBuilder#toString).



    Java 12



    On my machine, with Java 12.0.2, the bytecode is



    // identical to the bytecode above
    L3
    LINENUMBER 16 L3
    ALOAD 1
    ALOAD 2
    ALOAD 3
    INVOKEDYNAMIC makeConcatWithConstants(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; [
    // handle kind 0x6 : INVOKESTATIC
    java/lang/invoke/StringConcatFactory.makeConcatWithConstants(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;
    // arguments:
    "u0001u0001u0001"
    ]
    ASTORE 4


    which magically changes "the correct answer" to 4 objects since there is no intermediate StringBuilder involved.





    *Let's dig a bit deeper.




    12.5. Creation of New Class Instances



    A new class instance may be implicitly created in the following situations:




    • Loading of a class or interface that contains a string literal (§3.10.5) may create a new String object to represent the literal. (This will not occur if a string denoting the same sequence of Unicode code points has previously been interned.)




    In other words, when you start an application, there are already objects in the String pool. You barely know what they are and where they come from (unless you scan all loaded classes for all literals they contain).



    The java.lang.String class will be undoubtedly loaded as an essential JVM class, meaning all its literals will be created and placed into the pool.



    Let's take a randomly selected snippet from the source code of String, pick a couple of literals from it, put a breakpoint at the very beginning of our programme, and examine if the pool contains these literals.



    public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence,
    Constable, ConstantDesc {
    ...
    public String repeat(int count) {
    // ...
    if (Integer.MAX_VALUE / count < len) {
    throw new OutOfMemoryError("Repeating " + len + " bytes String " + count +
    " times will produce a String exceeding maximum size.");
    }
    }
    ...
    }


    They are there indeed.





    As an interesting find, this IDEA's filtering has a side effect: the substrings I was looking for have been added to the pool as well. The pool size increased by one ("bytes String" was added) after I applied this.contains("bytes String").



    Where does this leave us?



    We have no idea whether "First" was created and interned before we call String str1 = "First";, so we can't state firmly that the line creates a new instance.






    share|improve this answer























    • 2





      each string also contains a byte[], same for StringBuilder (and first one will also create a static byte[0]) and eventually (haven't checked) the StringBuilder can create a new, bigger buffer (if needed) (just proving your 2nd sentence true)

      – Carlos Heuberger
      yesterday








    • 1





      thinking about it, is LDC creating a (new) Object? or just using one? (the literal could have been used before)

      – Carlos Heuberger
      yesterday













    • @CarlosHeuberger "Loading of a class or interface that contains a string literal may create a new String object to represent the literal. (This will not occur if a string denoting the same sequence of Unicode code points has previously been interned.)"

      – Andrew Tobilko
      21 hours ago













    • not new and just confirming what I wrote: "the literal could have been used before" exactly because that would mean it is already created/interned! But loading a class or interface is not part of code posted in question (despite "on the given problem" is quite open)

      – Carlos Heuberger
      15 hours ago













    • "unreasonable question to ask in an interview" - the funny part that you found question useful and interesting and most of your answer actually does not need anything you will not have at typical interview but good understanding how Java handles strings. I.e. I doubt you need anything to explain that concatenation can be optimized into method call at compile time. Indeed it would be hard to come up with diassembled code and precise versions... but answer like that may show how well someone knows the language/framework and things like defined/unspecified behavior...

      – Alexei Levenkov
      5 hours ago
















    16














    16










    16









    Any answer to your question will depend on the JVM implementation and the Java version currently being used. It's a stupid an unreasonable question to ask in an interview.



    Java 8



    On my machine, with Java 1.8.0_201, your snippet results in this bytecode



    L0
    LINENUMBER 13 L0
    LDC "First"
    ASTORE 1
    L1
    LINENUMBER 14 L1
    LDC "Second"
    ASTORE 2
    L2
    LINENUMBER 15 L2
    LDC "Third"
    ASTORE 3
    L3
    LINENUMBER 16 L3
    NEW java/lang/StringBuilder
    DUP
    INVOKESPECIAL java/lang/StringBuilder.<init> ()V
    ALOAD 1
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 2
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 3
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
    ASTORE 4


    which proves that 5 objects are being created (3 String literals*, 1 StringBuilder, 1 dynamically produced String instance by StringBuilder#toString).



    Java 12



    On my machine, with Java 12.0.2, the bytecode is



    // identical to the bytecode above
    L3
    LINENUMBER 16 L3
    ALOAD 1
    ALOAD 2
    ALOAD 3
    INVOKEDYNAMIC makeConcatWithConstants(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; [
    // handle kind 0x6 : INVOKESTATIC
    java/lang/invoke/StringConcatFactory.makeConcatWithConstants(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;
    // arguments:
    "u0001u0001u0001"
    ]
    ASTORE 4


    which magically changes "the correct answer" to 4 objects since there is no intermediate StringBuilder involved.





    *Let's dig a bit deeper.




    12.5. Creation of New Class Instances



    A new class instance may be implicitly created in the following situations:




    • Loading of a class or interface that contains a string literal (§3.10.5) may create a new String object to represent the literal. (This will not occur if a string denoting the same sequence of Unicode code points has previously been interned.)




    In other words, when you start an application, there are already objects in the String pool. You barely know what they are and where they come from (unless you scan all loaded classes for all literals they contain).



    The java.lang.String class will be undoubtedly loaded as an essential JVM class, meaning all its literals will be created and placed into the pool.



    Let's take a randomly selected snippet from the source code of String, pick a couple of literals from it, put a breakpoint at the very beginning of our programme, and examine if the pool contains these literals.



    public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence,
    Constable, ConstantDesc {
    ...
    public String repeat(int count) {
    // ...
    if (Integer.MAX_VALUE / count < len) {
    throw new OutOfMemoryError("Repeating " + len + " bytes String " + count +
    " times will produce a String exceeding maximum size.");
    }
    }
    ...
    }


    They are there indeed.





    As an interesting find, this IDEA's filtering has a side effect: the substrings I was looking for have been added to the pool as well. The pool size increased by one ("bytes String" was added) after I applied this.contains("bytes String").



    Where does this leave us?



    We have no idea whether "First" was created and interned before we call String str1 = "First";, so we can't state firmly that the line creates a new instance.






    share|improve this answer















    Any answer to your question will depend on the JVM implementation and the Java version currently being used. It's a stupid an unreasonable question to ask in an interview.



    Java 8



    On my machine, with Java 1.8.0_201, your snippet results in this bytecode



    L0
    LINENUMBER 13 L0
    LDC "First"
    ASTORE 1
    L1
    LINENUMBER 14 L1
    LDC "Second"
    ASTORE 2
    L2
    LINENUMBER 15 L2
    LDC "Third"
    ASTORE 3
    L3
    LINENUMBER 16 L3
    NEW java/lang/StringBuilder
    DUP
    INVOKESPECIAL java/lang/StringBuilder.<init> ()V
    ALOAD 1
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 2
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 3
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
    ASTORE 4


    which proves that 5 objects are being created (3 String literals*, 1 StringBuilder, 1 dynamically produced String instance by StringBuilder#toString).



    Java 12



    On my machine, with Java 12.0.2, the bytecode is



    // identical to the bytecode above
    L3
    LINENUMBER 16 L3
    ALOAD 1
    ALOAD 2
    ALOAD 3
    INVOKEDYNAMIC makeConcatWithConstants(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; [
    // handle kind 0x6 : INVOKESTATIC
    java/lang/invoke/StringConcatFactory.makeConcatWithConstants(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;
    // arguments:
    "u0001u0001u0001"
    ]
    ASTORE 4


    which magically changes "the correct answer" to 4 objects since there is no intermediate StringBuilder involved.





    *Let's dig a bit deeper.




    12.5. Creation of New Class Instances



    A new class instance may be implicitly created in the following situations:




    • Loading of a class or interface that contains a string literal (§3.10.5) may create a new String object to represent the literal. (This will not occur if a string denoting the same sequence of Unicode code points has previously been interned.)




    In other words, when you start an application, there are already objects in the String pool. You barely know what they are and where they come from (unless you scan all loaded classes for all literals they contain).



    The java.lang.String class will be undoubtedly loaded as an essential JVM class, meaning all its literals will be created and placed into the pool.



    Let's take a randomly selected snippet from the source code of String, pick a couple of literals from it, put a breakpoint at the very beginning of our programme, and examine if the pool contains these literals.



    public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence,
    Constable, ConstantDesc {
    ...
    public String repeat(int count) {
    // ...
    if (Integer.MAX_VALUE / count < len) {
    throw new OutOfMemoryError("Repeating " + len + " bytes String " + count +
    " times will produce a String exceeding maximum size.");
    }
    }
    ...
    }


    They are there indeed.





    As an interesting find, this IDEA's filtering has a side effect: the substrings I was looking for have been added to the pool as well. The pool size increased by one ("bytes String" was added) after I applied this.contains("bytes String").



    Where does this leave us?



    We have no idea whether "First" was created and interned before we call String str1 = "First";, so we can't state firmly that the line creates a new instance.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 21 hours ago

























    answered yesterday









    Andrew TobilkoAndrew Tobilko

    33.2k10 gold badges53 silver badges103 bronze badges




    33.2k10 gold badges53 silver badges103 bronze badges











    • 2





      each string also contains a byte[], same for StringBuilder (and first one will also create a static byte[0]) and eventually (haven't checked) the StringBuilder can create a new, bigger buffer (if needed) (just proving your 2nd sentence true)

      – Carlos Heuberger
      yesterday








    • 1





      thinking about it, is LDC creating a (new) Object? or just using one? (the literal could have been used before)

      – Carlos Heuberger
      yesterday













    • @CarlosHeuberger "Loading of a class or interface that contains a string literal may create a new String object to represent the literal. (This will not occur if a string denoting the same sequence of Unicode code points has previously been interned.)"

      – Andrew Tobilko
      21 hours ago













    • not new and just confirming what I wrote: "the literal could have been used before" exactly because that would mean it is already created/interned! But loading a class or interface is not part of code posted in question (despite "on the given problem" is quite open)

      – Carlos Heuberger
      15 hours ago













    • "unreasonable question to ask in an interview" - the funny part that you found question useful and interesting and most of your answer actually does not need anything you will not have at typical interview but good understanding how Java handles strings. I.e. I doubt you need anything to explain that concatenation can be optimized into method call at compile time. Indeed it would be hard to come up with diassembled code and precise versions... but answer like that may show how well someone knows the language/framework and things like defined/unspecified behavior...

      – Alexei Levenkov
      5 hours ago
















    • 2





      each string also contains a byte[], same for StringBuilder (and first one will also create a static byte[0]) and eventually (haven't checked) the StringBuilder can create a new, bigger buffer (if needed) (just proving your 2nd sentence true)

      – Carlos Heuberger
      yesterday








    • 1





      thinking about it, is LDC creating a (new) Object? or just using one? (the literal could have been used before)

      – Carlos Heuberger
      yesterday













    • @CarlosHeuberger "Loading of a class or interface that contains a string literal may create a new String object to represent the literal. (This will not occur if a string denoting the same sequence of Unicode code points has previously been interned.)"

      – Andrew Tobilko
      21 hours ago













    • not new and just confirming what I wrote: "the literal could have been used before" exactly because that would mean it is already created/interned! But loading a class or interface is not part of code posted in question (despite "on the given problem" is quite open)

      – Carlos Heuberger
      15 hours ago













    • "unreasonable question to ask in an interview" - the funny part that you found question useful and interesting and most of your answer actually does not need anything you will not have at typical interview but good understanding how Java handles strings. I.e. I doubt you need anything to explain that concatenation can be optimized into method call at compile time. Indeed it would be hard to come up with diassembled code and precise versions... but answer like that may show how well someone knows the language/framework and things like defined/unspecified behavior...

      – Alexei Levenkov
      5 hours ago










    2




    2





    each string also contains a byte[], same for StringBuilder (and first one will also create a static byte[0]) and eventually (haven't checked) the StringBuilder can create a new, bigger buffer (if needed) (just proving your 2nd sentence true)

    – Carlos Heuberger
    yesterday







    each string also contains a byte[], same for StringBuilder (and first one will also create a static byte[0]) and eventually (haven't checked) the StringBuilder can create a new, bigger buffer (if needed) (just proving your 2nd sentence true)

    – Carlos Heuberger
    yesterday






    1




    1





    thinking about it, is LDC creating a (new) Object? or just using one? (the literal could have been used before)

    – Carlos Heuberger
    yesterday







    thinking about it, is LDC creating a (new) Object? or just using one? (the literal could have been used before)

    – Carlos Heuberger
    yesterday















    @CarlosHeuberger "Loading of a class or interface that contains a string literal may create a new String object to represent the literal. (This will not occur if a string denoting the same sequence of Unicode code points has previously been interned.)"

    – Andrew Tobilko
    21 hours ago







    @CarlosHeuberger "Loading of a class or interface that contains a string literal may create a new String object to represent the literal. (This will not occur if a string denoting the same sequence of Unicode code points has previously been interned.)"

    – Andrew Tobilko
    21 hours ago















    not new and just confirming what I wrote: "the literal could have been used before" exactly because that would mean it is already created/interned! But loading a class or interface is not part of code posted in question (despite "on the given problem" is quite open)

    – Carlos Heuberger
    15 hours ago







    not new and just confirming what I wrote: "the literal could have been used before" exactly because that would mean it is already created/interned! But loading a class or interface is not part of code posted in question (despite "on the given problem" is quite open)

    – Carlos Heuberger
    15 hours ago















    "unreasonable question to ask in an interview" - the funny part that you found question useful and interesting and most of your answer actually does not need anything you will not have at typical interview but good understanding how Java handles strings. I.e. I doubt you need anything to explain that concatenation can be optimized into method call at compile time. Indeed it would be hard to come up with diassembled code and precise versions... but answer like that may show how well someone knows the language/framework and things like defined/unspecified behavior...

    – Alexei Levenkov
    5 hours ago







    "unreasonable question to ask in an interview" - the funny part that you found question useful and interesting and most of your answer actually does not need anything you will not have at typical interview but good understanding how Java handles strings. I.e. I doubt you need anything to explain that concatenation can be optimized into method call at compile time. Indeed it would be hard to come up with diassembled code and precise versions... but answer like that may show how well someone knows the language/framework and things like defined/unspecified behavior...

    – Alexei Levenkov
    5 hours ago















    13















    With the given information, the question cannot be definitely answered. As is stated in the JLS, §15.18.1:




    ... To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.




    This means that the answer depends at least on the concrete Java compiler used.



    I think the best we can do is give an interval as answer:




    • a smart compiler may be able to infer that str1 to str3 are never used and fold the concatenation during compilation, such that only one String-object is created (the one referenced by str4)

    • The maximum sensible number of Strings created should be 5: one each for str1 to str3, one for tmp = str1 + str2 and one for str4 = tmp + str3.


    So... my answer would be "something between one to five String-objects". As to the total number of objects created just for this operation... I do not know. This may also depend how exactly e.g. StringBuffer is implemented.



    As an aside: I wonder what the reason behind asking such questions is. Normally, one does not need to care about those details.






    share|improve this answer























    • 9





      "I wonder what the reason behind asking such questions is." - It reminds me of the "I-read-it-yesterday-I-will-ask-it-tomorrow" type of interviewers

      – Andrew Tobilko
      yesterday








    • 1





      I'd think it could just be a conversation starter on how Strings are modelled and to get some insight into how a candidate thinks about java objects, whether the candidate is aware of potential instantiation through the '+' operator etc. It's likely less important to know the exact answer, but to make some sense when arguing about it. Not exactly a question I would ask, but I could see it as reasonable if used in that regard.

      – Frank Hopkins
      yesterday











    • Either a trivia question, or a really deep question (as answered above). Why is it important? The more temporaries, the more often garbage must be collected, which affects performance.

      – ChuckCottrill
      yesterday











    • @ChuckCottrill your statement about the GC is true, but I think this situation is a little bit different. We are talking about compile-time constants and compiler transformations. These processes are designed to improve performance and should be opaque to the programmer. I really hope it was meant as a conversational starter...

      – Turing85
      23 hours ago






    • 2





      The smart compiler might notice that str4 isn't used anywhere either, so I think the minimum count should be 0 :-)

      – Bergi
      13 hours ago


















    13















    With the given information, the question cannot be definitely answered. As is stated in the JLS, §15.18.1:




    ... To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.




    This means that the answer depends at least on the concrete Java compiler used.



    I think the best we can do is give an interval as answer:




    • a smart compiler may be able to infer that str1 to str3 are never used and fold the concatenation during compilation, such that only one String-object is created (the one referenced by str4)

    • The maximum sensible number of Strings created should be 5: one each for str1 to str3, one for tmp = str1 + str2 and one for str4 = tmp + str3.


    So... my answer would be "something between one to five String-objects". As to the total number of objects created just for this operation... I do not know. This may also depend how exactly e.g. StringBuffer is implemented.



    As an aside: I wonder what the reason behind asking such questions is. Normally, one does not need to care about those details.






    share|improve this answer























    • 9





      "I wonder what the reason behind asking such questions is." - It reminds me of the "I-read-it-yesterday-I-will-ask-it-tomorrow" type of interviewers

      – Andrew Tobilko
      yesterday








    • 1





      I'd think it could just be a conversation starter on how Strings are modelled and to get some insight into how a candidate thinks about java objects, whether the candidate is aware of potential instantiation through the '+' operator etc. It's likely less important to know the exact answer, but to make some sense when arguing about it. Not exactly a question I would ask, but I could see it as reasonable if used in that regard.

      – Frank Hopkins
      yesterday











    • Either a trivia question, or a really deep question (as answered above). Why is it important? The more temporaries, the more often garbage must be collected, which affects performance.

      – ChuckCottrill
      yesterday











    • @ChuckCottrill your statement about the GC is true, but I think this situation is a little bit different. We are talking about compile-time constants and compiler transformations. These processes are designed to improve performance and should be opaque to the programmer. I really hope it was meant as a conversational starter...

      – Turing85
      23 hours ago






    • 2





      The smart compiler might notice that str4 isn't used anywhere either, so I think the minimum count should be 0 :-)

      – Bergi
      13 hours ago
















    13














    13










    13









    With the given information, the question cannot be definitely answered. As is stated in the JLS, §15.18.1:




    ... To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.




    This means that the answer depends at least on the concrete Java compiler used.



    I think the best we can do is give an interval as answer:




    • a smart compiler may be able to infer that str1 to str3 are never used and fold the concatenation during compilation, such that only one String-object is created (the one referenced by str4)

    • The maximum sensible number of Strings created should be 5: one each for str1 to str3, one for tmp = str1 + str2 and one for str4 = tmp + str3.


    So... my answer would be "something between one to five String-objects". As to the total number of objects created just for this operation... I do not know. This may also depend how exactly e.g. StringBuffer is implemented.



    As an aside: I wonder what the reason behind asking such questions is. Normally, one does not need to care about those details.






    share|improve this answer















    With the given information, the question cannot be definitely answered. As is stated in the JLS, §15.18.1:




    ... To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.




    This means that the answer depends at least on the concrete Java compiler used.



    I think the best we can do is give an interval as answer:




    • a smart compiler may be able to infer that str1 to str3 are never used and fold the concatenation during compilation, such that only one String-object is created (the one referenced by str4)

    • The maximum sensible number of Strings created should be 5: one each for str1 to str3, one for tmp = str1 + str2 and one for str4 = tmp + str3.


    So... my answer would be "something between one to five String-objects". As to the total number of objects created just for this operation... I do not know. This may also depend how exactly e.g. StringBuffer is implemented.



    As an aside: I wonder what the reason behind asking such questions is. Normally, one does not need to care about those details.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 23 hours ago

























    answered yesterday









    Turing85Turing85

    7,2263 gold badges19 silver badges43 bronze badges




    7,2263 gold badges19 silver badges43 bronze badges











    • 9





      "I wonder what the reason behind asking such questions is." - It reminds me of the "I-read-it-yesterday-I-will-ask-it-tomorrow" type of interviewers

      – Andrew Tobilko
      yesterday








    • 1





      I'd think it could just be a conversation starter on how Strings are modelled and to get some insight into how a candidate thinks about java objects, whether the candidate is aware of potential instantiation through the '+' operator etc. It's likely less important to know the exact answer, but to make some sense when arguing about it. Not exactly a question I would ask, but I could see it as reasonable if used in that regard.

      – Frank Hopkins
      yesterday











    • Either a trivia question, or a really deep question (as answered above). Why is it important? The more temporaries, the more often garbage must be collected, which affects performance.

      – ChuckCottrill
      yesterday











    • @ChuckCottrill your statement about the GC is true, but I think this situation is a little bit different. We are talking about compile-time constants and compiler transformations. These processes are designed to improve performance and should be opaque to the programmer. I really hope it was meant as a conversational starter...

      – Turing85
      23 hours ago






    • 2





      The smart compiler might notice that str4 isn't used anywhere either, so I think the minimum count should be 0 :-)

      – Bergi
      13 hours ago
















    • 9





      "I wonder what the reason behind asking such questions is." - It reminds me of the "I-read-it-yesterday-I-will-ask-it-tomorrow" type of interviewers

      – Andrew Tobilko
      yesterday








    • 1





      I'd think it could just be a conversation starter on how Strings are modelled and to get some insight into how a candidate thinks about java objects, whether the candidate is aware of potential instantiation through the '+' operator etc. It's likely less important to know the exact answer, but to make some sense when arguing about it. Not exactly a question I would ask, but I could see it as reasonable if used in that regard.

      – Frank Hopkins
      yesterday











    • Either a trivia question, or a really deep question (as answered above). Why is it important? The more temporaries, the more often garbage must be collected, which affects performance.

      – ChuckCottrill
      yesterday











    • @ChuckCottrill your statement about the GC is true, but I think this situation is a little bit different. We are talking about compile-time constants and compiler transformations. These processes are designed to improve performance and should be opaque to the programmer. I really hope it was meant as a conversational starter...

      – Turing85
      23 hours ago






    • 2





      The smart compiler might notice that str4 isn't used anywhere either, so I think the minimum count should be 0 :-)

      – Bergi
      13 hours ago










    9




    9





    "I wonder what the reason behind asking such questions is." - It reminds me of the "I-read-it-yesterday-I-will-ask-it-tomorrow" type of interviewers

    – Andrew Tobilko
    yesterday







    "I wonder what the reason behind asking such questions is." - It reminds me of the "I-read-it-yesterday-I-will-ask-it-tomorrow" type of interviewers

    – Andrew Tobilko
    yesterday






    1




    1





    I'd think it could just be a conversation starter on how Strings are modelled and to get some insight into how a candidate thinks about java objects, whether the candidate is aware of potential instantiation through the '+' operator etc. It's likely less important to know the exact answer, but to make some sense when arguing about it. Not exactly a question I would ask, but I could see it as reasonable if used in that regard.

    – Frank Hopkins
    yesterday





    I'd think it could just be a conversation starter on how Strings are modelled and to get some insight into how a candidate thinks about java objects, whether the candidate is aware of potential instantiation through the '+' operator etc. It's likely less important to know the exact answer, but to make some sense when arguing about it. Not exactly a question I would ask, but I could see it as reasonable if used in that regard.

    – Frank Hopkins
    yesterday













    Either a trivia question, or a really deep question (as answered above). Why is it important? The more temporaries, the more often garbage must be collected, which affects performance.

    – ChuckCottrill
    yesterday





    Either a trivia question, or a really deep question (as answered above). Why is it important? The more temporaries, the more often garbage must be collected, which affects performance.

    – ChuckCottrill
    yesterday













    @ChuckCottrill your statement about the GC is true, but I think this situation is a little bit different. We are talking about compile-time constants and compiler transformations. These processes are designed to improve performance and should be opaque to the programmer. I really hope it was meant as a conversational starter...

    – Turing85
    23 hours ago





    @ChuckCottrill your statement about the GC is true, but I think this situation is a little bit different. We are talking about compile-time constants and compiler transformations. These processes are designed to improve performance and should be opaque to the programmer. I really hope it was meant as a conversational starter...

    – Turing85
    23 hours ago




    2




    2





    The smart compiler might notice that str4 isn't used anywhere either, so I think the minimum count should be 0 :-)

    – Bergi
    13 hours ago







    The smart compiler might notice that str4 isn't used anywhere either, so I think the minimum count should be 0 :-)

    – Bergi
    13 hours ago













    4















    Java 8 will likely create 5 objects:




    • 3 for the 3 variables

    • 1 StringBuilder

    • 1 for the concatenated String


    With Java 9 things changed though and String concatenation does not use StringBuilder anymore.






    share|improve this answer























    • 4





      Good answer, but for Java 8, I think you're overlooking the char[] object used by the implementation of StringBuilder.

      – Andy Thomas
      yesterday








    • 1





      stackoverflow.com/questions/12806739/…

      – 17slim
      yesterday






    • 5





      @3limin4t0r "char[] is a primitive value" - Nope.

      – Turing85
      yesterday








    • 2





      @AndyThomas if you count the char[] you will end up with even more as also String uses char[] and some constructors also create copies of char[].

      – Puce
      yesterday











    • That's a good point actually, which leads me to believe @Turing85's answer is more correct without further clarification from the interviewers.

      – 17slim
      yesterday
















    4















    Java 8 will likely create 5 objects:




    • 3 for the 3 variables

    • 1 StringBuilder

    • 1 for the concatenated String


    With Java 9 things changed though and String concatenation does not use StringBuilder anymore.






    share|improve this answer























    • 4





      Good answer, but for Java 8, I think you're overlooking the char[] object used by the implementation of StringBuilder.

      – Andy Thomas
      yesterday








    • 1





      stackoverflow.com/questions/12806739/…

      – 17slim
      yesterday






    • 5





      @3limin4t0r "char[] is a primitive value" - Nope.

      – Turing85
      yesterday








    • 2





      @AndyThomas if you count the char[] you will end up with even more as also String uses char[] and some constructors also create copies of char[].

      – Puce
      yesterday











    • That's a good point actually, which leads me to believe @Turing85's answer is more correct without further clarification from the interviewers.

      – 17slim
      yesterday














    4














    4










    4









    Java 8 will likely create 5 objects:




    • 3 for the 3 variables

    • 1 StringBuilder

    • 1 for the concatenated String


    With Java 9 things changed though and String concatenation does not use StringBuilder anymore.






    share|improve this answer















    Java 8 will likely create 5 objects:




    • 3 for the 3 variables

    • 1 StringBuilder

    • 1 for the concatenated String


    With Java 9 things changed though and String concatenation does not use StringBuilder anymore.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 23 hours ago









    Andrew Tobilko

    33.2k10 gold badges53 silver badges103 bronze badges




    33.2k10 gold badges53 silver badges103 bronze badges










    answered yesterday









    PucePuce

    29.1k9 gold badges61 silver badges117 bronze badges




    29.1k9 gold badges61 silver badges117 bronze badges











    • 4





      Good answer, but for Java 8, I think you're overlooking the char[] object used by the implementation of StringBuilder.

      – Andy Thomas
      yesterday








    • 1





      stackoverflow.com/questions/12806739/…

      – 17slim
      yesterday






    • 5





      @3limin4t0r "char[] is a primitive value" - Nope.

      – Turing85
      yesterday








    • 2





      @AndyThomas if you count the char[] you will end up with even more as also String uses char[] and some constructors also create copies of char[].

      – Puce
      yesterday











    • That's a good point actually, which leads me to believe @Turing85's answer is more correct without further clarification from the interviewers.

      – 17slim
      yesterday














    • 4





      Good answer, but for Java 8, I think you're overlooking the char[] object used by the implementation of StringBuilder.

      – Andy Thomas
      yesterday








    • 1





      stackoverflow.com/questions/12806739/…

      – 17slim
      yesterday






    • 5





      @3limin4t0r "char[] is a primitive value" - Nope.

      – Turing85
      yesterday








    • 2





      @AndyThomas if you count the char[] you will end up with even more as also String uses char[] and some constructors also create copies of char[].

      – Puce
      yesterday











    • That's a good point actually, which leads me to believe @Turing85's answer is more correct without further clarification from the interviewers.

      – 17slim
      yesterday








    4




    4





    Good answer, but for Java 8, I think you're overlooking the char[] object used by the implementation of StringBuilder.

    – Andy Thomas
    yesterday







    Good answer, but for Java 8, I think you're overlooking the char[] object used by the implementation of StringBuilder.

    – Andy Thomas
    yesterday






    1




    1





    stackoverflow.com/questions/12806739/…

    – 17slim
    yesterday





    stackoverflow.com/questions/12806739/…

    – 17slim
    yesterday




    5




    5





    @3limin4t0r "char[] is a primitive value" - Nope.

    – Turing85
    yesterday







    @3limin4t0r "char[] is a primitive value" - Nope.

    – Turing85
    yesterday






    2




    2





    @AndyThomas if you count the char[] you will end up with even more as also String uses char[] and some constructors also create copies of char[].

    – Puce
    yesterday





    @AndyThomas if you count the char[] you will end up with even more as also String uses char[] and some constructors also create copies of char[].

    – Puce
    yesterday













    That's a good point actually, which leads me to believe @Turing85's answer is more correct without further clarification from the interviewers.

    – 17slim
    yesterday





    That's a good point actually, which leads me to believe @Turing85's answer is more correct without further clarification from the interviewers.

    – 17slim
    yesterday











    1















    It should be 5:




    • three for the three literals (assigned to str1, str2 and str3)


    • one for str1 + str2


    • one for (result from the previous operation) + str3 (assigned to str4)







    share|improve this answer




























    • str1 + str2 will not be concatenated to a String in all Java since quite many years.

      – Puce
      yesterday
















    1















    It should be 5:




    • three for the three literals (assigned to str1, str2 and str3)


    • one for str1 + str2


    • one for (result from the previous operation) + str3 (assigned to str4)







    share|improve this answer




























    • str1 + str2 will not be concatenated to a String in all Java since quite many years.

      – Puce
      yesterday














    1














    1










    1









    It should be 5:




    • three for the three literals (assigned to str1, str2 and str3)


    • one for str1 + str2


    • one for (result from the previous operation) + str3 (assigned to str4)







    share|improve this answer















    It should be 5:




    • three for the three literals (assigned to str1, str2 and str3)


    • one for str1 + str2


    • one for (result from the previous operation) + str3 (assigned to str4)








    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited yesterday

























    answered yesterday









    Laurenz AlbeLaurenz Albe

    62.9k11 gold badges44 silver badges66 bronze badges




    62.9k11 gold badges44 silver badges66 bronze badges
















    • str1 + str2 will not be concatenated to a String in all Java since quite many years.

      – Puce
      yesterday



















    • str1 + str2 will not be concatenated to a String in all Java since quite many years.

      – Puce
      yesterday

















    str1 + str2 will not be concatenated to a String in all Java since quite many years.

    – Puce
    yesterday





    str1 + str2 will not be concatenated to a String in all Java since quite many years.

    – Puce
    yesterday











    0















    Concatenation operation doesn't create those many String objects. It creates aStringBuilder and then appends the strings. So there may be 5 objects,
    3 (variables) + 1 (sb) + 1 (Concatenated string).






    share|improve this answer























    • 1





      It might be 5.

      – Nexevis
      yesterday











    • As was stated many times, the JLS says that "a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression." Emphasis is on may.

      – Turing85
      yesterday













    • @Turing85 agreed. Updated.

      – javaaddict
      yesterday
















    0















    Concatenation operation doesn't create those many String objects. It creates aStringBuilder and then appends the strings. So there may be 5 objects,
    3 (variables) + 1 (sb) + 1 (Concatenated string).






    share|improve this answer























    • 1





      It might be 5.

      – Nexevis
      yesterday











    • As was stated many times, the JLS says that "a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression." Emphasis is on may.

      – Turing85
      yesterday













    • @Turing85 agreed. Updated.

      – javaaddict
      yesterday














    0














    0










    0









    Concatenation operation doesn't create those many String objects. It creates aStringBuilder and then appends the strings. So there may be 5 objects,
    3 (variables) + 1 (sb) + 1 (Concatenated string).






    share|improve this answer















    Concatenation operation doesn't create those many String objects. It creates aStringBuilder and then appends the strings. So there may be 5 objects,
    3 (variables) + 1 (sb) + 1 (Concatenated string).







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited yesterday

























    answered yesterday









    javaaddictjavaaddict

    1571 silver badge8 bronze badges




    1571 silver badge8 bronze badges











    • 1





      It might be 5.

      – Nexevis
      yesterday











    • As was stated many times, the JLS says that "a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression." Emphasis is on may.

      – Turing85
      yesterday













    • @Turing85 agreed. Updated.

      – javaaddict
      yesterday














    • 1





      It might be 5.

      – Nexevis
      yesterday











    • As was stated many times, the JLS says that "a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression." Emphasis is on may.

      – Turing85
      yesterday













    • @Turing85 agreed. Updated.

      – javaaddict
      yesterday








    1




    1





    It might be 5.

    – Nexevis
    yesterday





    It might be 5.

    – Nexevis
    yesterday













    As was stated many times, the JLS says that "a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression." Emphasis is on may.

    – Turing85
    yesterday







    As was stated many times, the JLS says that "a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression." Emphasis is on may.

    – Turing85
    yesterday















    @Turing85 agreed. Updated.

    – javaaddict
    yesterday





    @Turing85 agreed. Updated.

    – javaaddict
    yesterday











    0















    A conformant Java implementation can concatenate the strings any number of ways, at run time or at compile time, needing any number of run-time objects, including zero objects if it detects that the result is not needed at run time.






    share|improve this answer






























      0















      A conformant Java implementation can concatenate the strings any number of ways, at run time or at compile time, needing any number of run-time objects, including zero objects if it detects that the result is not needed at run time.






      share|improve this answer




























        0














        0










        0









        A conformant Java implementation can concatenate the strings any number of ways, at run time or at compile time, needing any number of run-time objects, including zero objects if it detects that the result is not needed at run time.






        share|improve this answer













        A conformant Java implementation can concatenate the strings any number of ways, at run time or at compile time, needing any number of run-time objects, including zero objects if it detects that the result is not needed at run time.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 12 hours ago









        BoannBoann

        38.7k13 gold badges93 silver badges123 bronze badges




        38.7k13 gold badges93 silver badges123 bronze badges

























            bhpsh is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            bhpsh is a new contributor. Be nice, and check out our Code of Conduct.













            bhpsh is a new contributor. Be nice, and check out our Code of Conduct.












            bhpsh is a new contributor. Be nice, and check out our Code of Conduct.
















            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57630924%2fhow-many-string-objects-would-be-created-when-concatenating-multiple-strings%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

            Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

            Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...