Forum Stats

  • 3,837,375 Users
  • 2,262,252 Discussions
  • 7,900,266 Comments

Discussions

Strings

873158
873158 Member Posts: 2
Hi,

I wanted to know how many objects are created when the below code is executed.

String s1 = "abc";
String s2 = s1 + "def";

Answers

  • Kayaman
    Kayaman Member Posts: 3,844 Silver Trophy
    user8926181 wrote:
    Hi,

    I wanted to know how many objects are created when the below code is executed.

    String s1 = "abc";
    String s2 = s1 + "def";
    Go google for it.
  • 3 object are created
    1st "abc"
    2nd "def"
    3rd "abcdef"
  • 802316
    802316 Member Posts: 532
    My answer would be there is one StringBuilder and one String which contains two objects each

    The "abc" and "def" are string literals, they will be created when the class loads (if they don't exist already)

    There two objects created each time this code is run.

    There is a StringBuilder (1) which contains a char[] (2) and this creates a String (3) which contains another char[] (4)

    Note, if the first String were final, the compiler would simplify the code so that
    final String s1 = "abc";
    String s2 = s1 + "def";
    is the same as
    final String s1 = "abc";
    String s2 = "abcdef";
    and no new objects would be created each time this code is run.
This discussion has been closed.