Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

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

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 objects creation with respect to 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;

    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...