Java – how many string objects are created for the following?

String summer = new String("Summer");
String summer = new String("Summer");
String summer2 = "Summer";
System.out.println("Summer");
System.out.println("autumn");
System.out.println("autumn" == "summer");
String autumn = new String("Summer");

My answer is 2 0 0 1 1 1 = 5 Is that right?

Solution

That sounds reasonable to me

String summer = new String("Summer");

Created 2 instances The first is the word "summer" The second is because the constructor is called

String summer2 = "Summer";

0 instances: This is just a reference assignment

System.out.println("Summer");

0 instances The text "summer" is taken from the cache

System.out.println("autumn");

1 instance "autumn"

System.out.println("autumn" == "summer");

1 example "summer"

String autumn = new String("Summer");

1 instance caused by constructor call The text "summer" is taken from the cache

Bottom line: 2 0 0 1 1 1 = 5

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>