Search code examples
stringheap-memorystring-pool

Where a String saves when the object creation has a concatenation?


As we know the following String is saved in the String Constant Pool.

String a = "AB";

The String objects created as below will be saved in Heap.

String b = new String("AB");

String e = b.concat("C");

At this time, Can anyone explain where the following Strings getting saved?

String c = new String("A"+ "B");

String d = "A" + "B";

Appreciate if you can clearly explain with reasons.


Solution

  • Before proceeding to your target statements, one minor correction to your question.

    String b = new String("AB");
    
    String e = b.concat("C");
    

    Above statements will create a String object in Heap as well as in String Pool for further references.

    Now your first question statement:

    String c = new String("A"+ "B");
    

    Here, first two Strings, "A" and "B", are created in String Pool and are concatenated to form "AB" which is also stored in String Pool. --->Point-I

    Then new String(dataString) constructor is called with "AB" as the parameter. This will create one String in Heap and one in String Pool, both having value as "AB". --->Point-II

    String "AB" created in String Pool at Point-I and II are equal but not the same.

    Now your second question statement:

    String d = "A" + "B";
    

    Here there are two cases:

    1. If the second statement is executed after the first statement, no new String is created in String Pool as "A", "B" and "AB" are already present in the String Pool and can be reused using Interning.
    2. If the second statement is executed individually, then initially two Strings "A" and "B" are created in String Pool and then they are concatenated to form "AB" which is also stored in String Pool.

    Hopefully this answers your question. Cheers!