Java – how do I know how many objects will be created using the following code?
•
Java
For strings, I'm a little confused about the object situation, so I want to know how many objects will be created with the following code, and give some explanations for string objects and heap creation of string objects
public static void main(String[] args) { String str1 = "String1"; String str2 = new String("String1"); String str3 = "String3"; String str4 = str2 + str3; }
Solution
Four objects are created
Two notes:
>New string ("something") always creates a new object The string literal "something" creates only one object for all instances The best practice is never to use a new string ("something") – instantiation is redundant. > Concatenation of two strings is converted to StringBuilder Append (first) append(second). Tostring(), so create another object here
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
二维码