1. Why is there a String class
In C language, you can only use character arrays or character pointers to represent strings. You can use String series functions provided by the standard library to complete most operations. However, this way of separating data from data operation methods does not accord with the idea of face objects, and character strings are widely used. Therefore, Java language provides String classes.
2. Construction method of string
2.1 using constant string construction
String s1="hello world"; System.out.println(s1);
2.2 direct new String object
String s2 = new String("hello world"); System.out.println(s1);
2.3 construction using character arrays
char[] array = {'h','e','l','l','o','w','o','r','l','d'}; String s3 = new String(array); System.out.println(s1);
3. Comparison of string objects
3.1 use = = compare
For built-in types, the values in variables are compared; For reference types, the address in the reference is compared.
public static void main(String[] args) { int a = 10; int b = 20; int c = 10; // For basic type variables, = = compares whether the values stored in the two variables are the same System.out.println(a == b); // false System.out.println(a == c); // true // For reference type variables, = = compare whether two reference variables refer to the same object String s1 = new String("hello"); String s2 = new String("hello"); String s3 = new String("world"); String s4 = s1; System.out.println(s1 == s2); // false System.out.println(s2 == s3); // false System.out.println(s1 == s4); // true }
3.2 compare using equals method (compare in dictionary order)
String class overrides the equals method in the parent class Object. Equals in Object is compared by = = by default. String overrides the equals method and compares the contents of strings in dictionary order.
public static void main(String[] args) { String s1 = new String("hello"); String s2 = new String("hello"); String s3 = new String("Hello"); System.out.println(s1.equals(s2)); // true System.out.println(s1.equals(s3)); // false }
equals comparison: character by character in a String object
Although s1 and s2 do not refer to the same object, the contents placed in the two objects are the same, so true is output
s1 and s3 do not refer to the same object, and the contents of the two objects are different, so false is output
3.3 use the compareTo(String s) method (compare in dictionary order)
Difference from equals:
equals returns the boolean type, while compareTo returns the int type.
Specific comparison method:
- First, compare the size according to the dictionary order. If unequal characters appear, directly return the size difference between the two characters
- If the first k characters are equal (k is the minimum length of two characters), the return value is the difference between the two string lengths
public static void main(String[] args) { String s1 = new String("abc"); String s2 = new String("ac"); String s3 = new String("abc"); String s4 = new String("abcdef"); System.out.println(s1.compareTo(s2)); // Difference between different output characters - 1 System.out.println(s1.compareTo(s3)); // Same output 0 System.out.println(s1.compareTo(s4)); // The first k characters are exactly the same, and the output length difference is - 3 }
3.4 use the compareToIgnoreCase(String str) method (the same as compareTo, but case is ignored)
public static void main(String[] args) { String s1 = new String("abc"); String s2 = new String("ac"); String s3 = new String("ABc"); String s4 = new String("abcdef"); System.out.println(s1.compareToIgnoreCase(s2)); // Difference between different output characters - 1 System.out.println(s1.compareToIgnoreCase(s3)); // Same output 0 System.out.println(s1.compareToIgnoreCase(s4)); // The first k characters are exactly the same, and the output length difference is - 3 }
4. String search method
method | function |
---|---|
char charAt(int index) | Returns the character at the index position. If the index is negative or out of bounds, an IndexOutOfBoundsException exception is thrown |
int indexOf(int ch) | Returns the first occurrence of ch, not - 1 |
int indexOf(int ch, int fromIndex) | Start from the fromIndex position to find the position where ch first appears, and - 1 is not returned |
int indexOf(String str) | Returns the location where str first appears, without returning - 1 |
int indexOf(String str, int fromIndex) | Start from the fromIndex position to find the position where str first appears, and - 1 is not returned |
int lastIndexOf(int ch) | Look forward from the back and return to the position where ch first appeared, without returning - 1 |
int lastIndexOf(int ch, int fromIndex) | Start from the fromIndex position and look for the position where ch first appears from back to front. It does not return - 1 |
int lastIndexOf(String str) | Look forward from the back and return to the position where str first appears. No - 1 is returned |
int lastIndexOf(String str, int fromIndex) | Start from the fromIndex position and look for the position where str first appears from back to front. It does not return - 1 |
public static void main(String[] args) { String s="aabbbcccddaa"; System.out.println(s.charAt(1));//a System.out.println(s.indexOf('b'));//2 System.out.println(s.indexOf("ccc"));//5 System.out.println(s.indexOf("aa",4));//10 System.out.println(s.indexOf('a',9));//10 System.out.println(s.lastIndexOf('a'));//11 System.out.println(s.lastIndexOf("aa"));//10 }
5. String conversion
5.1 numeric and string conversion
1. Number to string
public static void main(String[] args) { String s1=String.valueOf(123); String s2=String.valueOf(12.34); System.out.println(s1); System.out.println(s2); }
2. String to number
public static void main(String[] args) { int a=Integer.parseInt("123"); int b=Integer.parseInt("12.34"); System.out.println(a); System.out.println(b); }
5.2 string case conversion
public static void main(String[] args) { String s1 = "hello"; String s2 = "HELLO"; // Lowercase to uppercase System.out.println(s1.toUpperCase()); // Capital to lowercase System.out.println(s2.toLowerCase()); }
5.3 string to array
public static void main(String[] args) { String s = "hello"; // String to array char[] ch = s.toCharArray(); for (int i = 0; i < ch.length; i++) { System.out.print(ch[i]); } System.out.println(); // Array to string String s2 = new String(ch); System.out.println(s2); }
5.4 format control
public static void main(String[] args) { String s = String.format("%d-%d-%d", 2019, 9,14); System.out.println(s); }
6. String constant pool
In order to make the program run faster and save memory, Java provides constant pools for eight basic data types and String classes.
The string constant pool is a StringTable class in the JVM. In fact, it is a hashtable of fixed size (a data structure used for efficient search). The location and default size of the string constant pool are different in different JDK versions:
JDK version | String constant pool location | Size setting |
---|---|---|
Java6 | (method area) permanent generation | Fixed size: 1009 |
Java7 | Heap | It can be set without size limit. The default size is 60013 |
Java8 | Heap | It can be set with range limit. The minimum is 1009 |
The following is a code description
public static void main(String[] args) { String s1="hello"; String s2="hello"; String s3=new String("hello"); System.out.println(s1==s2);//true System.out.println(s1==s3);//false }
It can be seen from the output result that s1 and s2 refer to the same object because the string constants in the bytecode file will be saved in the string constant pool when the class is loaded. s3 points to the new object of new, so s1 and s3 are different.
Constructor for String
public String(String original) { this.value = original.value;// String, and value is the reference of the character array this.hash = original.hash;//The default is 0 }
7.intern method
intern is a Native method (Native method means that the underlying is implemented in C + +, and the source code of its implementation cannot be seen). The function of this method is to manually add the created String object to the constant pool.
public static void main(String[] args) { char[] ch = new char[]{'a', 'b', 'c'}; String s1 = new String(ch); // The s1 object is not in the constant pool //s1. Intern(); / / after calling s1. Intern(); the reference of s1 object will be put into the constant pool String s2 = "abc"; // "abc" exists in the constant pool. When s2 is created, the reference of "abc" in the constant pool is directly used System.out.println(s1 == s2); } // Output false // After the above method is turned on, true will be output
- String str = "hello"
It will only open up a heap memory space, save it in the String constant pool, and then str shares the String object in the constant pool - String str = new String("hello")
Two heap memory spaces will be opened up, the String "hello" is saved in the String constant pool, and then the String object in the constant pool will be used to assign a value to the newly opened String object. - String str = new String(new char[]{'h', 'e', 'l', 'l', 'o'})
First create a String object on the heap, and then use copyof to reopen the array space and copy the contents of the parameter String array to the String object
7. Immutability of string
1. The String class cannot be changed at design time. It has been described in the String class implementation description.
2. All operations involving possible modification of string contents are to create a new object and change the new object
3. Why should String be immutable? (what are the benefits of immutable objects?)
(1) . it is convenient to implement the String object pool. If the String is variable, the object pool needs to consider when to deep copy the String. (2) immutable objects are thread safe. (3) immutable objects are more convenient to cache hash code s and can be saved to HashMap more efficiently as key s
StringBuilder and StringBuffer
7.1 introduction to StringBuilder and StringBuffer
Due to the immutability of String, in order to facilitate String modification, Java provides StringBuilder and StringBuffer classes. Most of the functions of these two classes are the same. Here are some common methods of StringBuilder
method | explain |
---|---|
StringBuff append(String str) | Append at the end, which is equivalent to + =. Variables such as boolean, char, char [], double, float, int, long, Object, String and StringBuff can be appended |
char charAt(int index) | Gets the character of the index position |
int length() | Gets the length of the string |
int capacity() | Gets the total size of the underlying save string space |
void ensureCapacity(int mininmumCapacity) | Capacity expansion |
void setCharAt(int index, char ch) | Set the character in the index position to ch |
int indexOf(String str) | Returns the first occurrence of str |
int indexOf(String str, int fromIndex) | Find the location where str first appears from the fromIndex location |
int lastIndexOf(String str) | Returns the last occurrence of str |
int lastIndexOf(String str, int fromIndex) | Start from the fromIndex location to find the location where str last appeared |
StringBuff insert(int offset, String str) | Insert at offset: eight base class types & string type & object type data |
StringBuffer deleteCharAt(int index) | Delete index position character |
StringBuffer delete(int start, int end) | Delete the characters in the [start, end) interval |
StringBuffer replace(int start, int end, String str) | Replace the character at [start, end) with str |
String substring(int start) | The characters from start to end are returned in the form of String |
String substring(int start,int end) | Return the characters in the range of [start, end] in the form of String |
StringBuffer reverse() | Invert String String toString() returns all characters as a String |
StringBuilder is more efficient than StringBuffer, but StringBuffer is thread safe.