How to know how many objects will be created with the following code?

前端 未结 2 1192
谎友^
谎友^ 2020-12-06 22:40

I am bit confused in case of objects when it comes to Strings, So wanted to know how many objects will be created with following code, with some explanation about String obj

相关标签:
2条回答
  • 2020-12-06 23:08

    4 objects will be created.

    Two notes:

    • new String("something") always creates a new object. The string literal "something" creates only one object for all occurrences. The best practice is to never use new String("something") - the instantiation is redundant.
    • the concatenation of two strings is transformed to StringBuilder.append(first).append(second).toString(), so another object is created here.
    0 讨论(0)
  • 2020-12-06 23:09

    each of the str1, str2, str3, str4 are String objects .

    str1 : "String1" is a string literal and Java creates a String object whenever it encounters a string literal.

    str2 : as you are using the new keyword and constructor of the class String a String object is created

    str3 : similar to str1

    str4 : concatenated string literal, similar to str1

    edit : http://download.oracle.com/javase/tutorial/java/data/strings.html

    0 讨论(0)
提交回复
热议问题