Welcome to “Algorithms and the Beauty of Programming” ↑ pay attention to us!

This article was first published on the wechat official account “Beauty of Algorithms and Programming”. Welcome to follow and learn more about this series of blogs in time.

String s = newString(“xyz”);

How many Stringobjects were created?

Can I inherit from the String class?

“Xyz” corresponds to an object that is placed in the string constant buffer, and the constant “xyz” is the same object in the buffer no matter how many times it occurs. Each time NewString is written, a new object is created, which uses the contents of the constant “xyz” object to create a NewString object. If you’ve used ‘xyz’ before, you don’t create ‘xyz’ here, you just take it from the buffer, and a StringObject is created; But if “XYZ” has not been used before, then an object is created and put into the buffer, in which case it creates two objects. As for whether the String class inherits, the answer is no, because String is final by default and is not inheritable.

The difference between String and StringBuffer

The JAVA platform provides two classes: String and StringBuffer, which store and manipulate strings, which are character data containing multiple characters. The String class provides a String with an immutable value. The string provided by this StringBuffer class can be modified. You use StringBuffer when you know the character data is going to change. Typically, you can use StringBuffer