How to find out how many objects will be created using the following code?

I got a little confused about objects when it comes to Strings, so I wanted to know how many objects would be created using the following code, with some explanation for creating String objects with respect to the string pool and heap.

 public static void main(String[] args) {

    String str1 = "String1";

    String str2 = new String("String1");

    String str3 = "String3";

    String str4 = str2 + str3;

    }
+3
source share
2 answers

4 objects will be created.

Two notes:

  • new String("something")always creates a new object. A string literal "something"creates only one object for all occurrences. The best practice is never to use new String("something")- the instance is redundant.
  • the concatenation of two strings is converted to StringBuilder.append(first).append(second).toString(), so another object is created here.
+13
source

str1, str2, str3, str4 - String.

str1: "String1" - , Java String , .

str2: String String

str3: str1

str4: , str1

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

+1

Source: https://habr.com/ru/post/1767772/


All Articles