-
In JDK1.8, the internal storage structure of String is a Char array
-
String has four constructors
- A constructor that takes a String
- Constructor that takes char()
- Constructor that takes a StringBuffer as an argument
- Constructor that takes StringBuilder as an argument
-
equals()
- String overrides the equals() method of Object. Equals () needs to pass an Object parameter value. The equals() method will check whether it is String or false if it is not
- If the argument type is String, each character in the two strings is cyclically compared, returning true if all characters are equal and false otherwise
- EqualsIgnoreCase (), similar to equals(), compares hulve case
-
CompareTo (), returns the number
- CompareTo () loops over all characters and returns char1-char2 if either character is different
- CompareTo () returns 0, indicating that the two strings are identical
Difference between compareTo() and equals()
-
Equals () can accept an Object argument, and compareTo() can only accept a String argument
-
Equals () returns Boolean, and compareTo() returns int
The interview questions
1. Equals (
**== : ** for basic data types, is used to compare “values” for equality; For reference types, it is used to compare whether reference addresses are the same. The equals() method in Object is equal to ==
**equals() : **String overrides the equals() method to compare the values of two strings
2. The benefits of final modification
-
Using final is more efficient and allows you to cache results without worrying about who might change the value when passing a parameter. If String is a mutable class, you might need to copy a new value to pass through, which degrades code performance
String constant pooling can only be implemented if the string is immutable
-
With Final, it is safer, and there is some validation when other methods are called. If a class is mutable, the internal values will change after validation
3. The difference between String and StringBuilder and StringBuffer
Because String is immutable, String concatenation is inefficient
Stringbuffers use synchronized to ensure thread-safety, and therefore perform poorly
StringBuilder has no synchronized modifier, performs better than StringBuffer, and can be used in non-concurrent environments
4. The String with the JVM
There are two common ways to create a String:
** New String() : ** This method creates a String object on the heap and then queries the constant pool to see if the value of the substring already exists
** Direct assignment: ** Direct assignment checks the string constant pool to see if it already exists, and if so, points the reference address to the value, otherwise it will be created in the constant pool first, and then refers the reference to the value