String classString
String is a special wrapper class data.
public final class String
implements java.io.Serializable.Comparable<String>, CharSequence
Copy the code
String = new String(” ABC “); String STR =” ABC “; Is created in the form of
Common methods in strings
The method name | Introduction to the | Methods described |
---|---|---|
public String concat(String str) | Concatenation of strings | The method takes one parameterStringClass to concatenate the string STR after the original string. |
public int length() | Find the length of the string | Returns the length of the string, where length refers to the number of Unicode characters in the string. |
public char charAt(int index) | Find the character at a position in a string | This method indexes a string at a specific position to get the character at the specified position in the string. It’s worth noting that, The index of the first character in the string is 0, the index of the second character is 1, and so on, and the index of the last character is length()-1. |
public boolean equals(Object anObject) | String comparison | This method compares two strings, similar to the equals method provided by the Character class because they are methods that override the Object class. This method compares the current string with the argument string and returns true if the two strings are equal, false otherwise. |
public String subString(int beginIndex) | Extracts substrings from strings | This method starts at the beginIndex position and returns the remaining characters from the current string as a new string. |
public int indexOf(int ch) | The search for a single character in a string | This method is used to find the occurrence of a particular character ch in the current string. This method looks backwards from the beginning. If the character CH is found in the string, it returns the position where the character ch first appears in the string. If the character ch is not found in the entire string, -1 is returned. |
public String trim() | The removal of redundant whitespace from a string | This method simply strips the leading and trailing whitespace and returns the resulting new string. Note that the Spaces in the middle of the original string are not removed. |
public native String intern(); | Points to an object in a specific constant pool in a string pool | If the String constant pool already contains a String equal to this String, return a String representing the String in the pool; Otherwise, the characters contained in this String are added to the constant pool and a reference to this String is returned. |
Why is String set to immutable
Mainly from the following three aspects:
1. Ensure the security of String objects. Assuming strings are mutable, strings can be maliciously modified.
2. Ensure that the hash attribute value will not change frequently to ensure uniqueness, so that the corresponding key-value caching function can be realized by containers like HashMap.
String constant pool can be implemented
String storage in the JVM
Code sample
String str1 = "123";
String str2 = "123";
String str3 = "123";
String str4 = new String("123");
String str5 = new String("123");
String str6 = new String("123"); Str1 = = str2:trueStr2 = = str3:trueStr3 = = str4:falseStr4 = = str5:falseStr5 = = str6:false
Copy the code
JVM storage examples
Process for creating a String object
For the underlying JVM, String STR = new String(“123”) what is the process for creating an object?
- Check the constant pool for the presence of the string “123”; If yes, the corresponding reference instance is returned. If no, create the corresponding instance object.
- New a String object of type “123” in the heap;
- Copy the object address to STR, and then create an application.
Note: If there is no string “123” in the constant pool, two objects are created; If it exists, an object and its reference are created.
Creating a String object
Question:
1.String str =”ab” + “cd”; Number of objects?
Analysis: if the string constant pool the string object
- String constant pool :(1 object) “abcd”;
- Heap: no
- Stack: (1 reference) STR total: 1 object +1 reference
2.String str = new String(“abc”); Number of objects?
Analysis: if the string constant pool the string object
String constant pool :(1 object) “ABC “;
Heap :(1 object) new String(” ABC “)
Stack :(1 reference) STR
Total: 2 objects +1 reference
3.String str = new String(“a” + “b”); Number of objects?
Analysis: if the string constant pool the string object
- String constant pool :(3 objects) “a”, “b”, “ab”;
- Heap :(1 object) new String(“ab”)
- Stack: (1 reference) STR total: 4 objects +1 reference
4.String str = new String(“ab”) + “ab”; Number of objects?
Analysis: if the string constant pool the string object
- String constant pool :(1 object) “ab”;
- Heap :(1 object) new String(“ab”)
- Stack: (1 reference) STR total: 2 objects +1 reference
5.String str = new String(“ab”) + new String(“ab”); Number of objects?
Analysis: if the string constant pool the string object
- String constant pool :(1 object) “ab”;
- Heap (2 objects) New String(“ab”), new String(“ab”)
- Stack: (1 reference) STR total: 3 objects +1 reference
6.String str = new String(“ab”) + new String(“cd”); Number of objects?
Analysis: if the string constant pool the string object
- String constant pool :(2 objects) “ab”, “CD “;
- Heap :(2 objects) new String(“ab”), new String(” CD “)
- Stack: (1 reference) STR total: 4 objects +1 reference
7.String str3 = str1 + str2; Number of objects?
String str1 = "ab"; String str2 = "cd"; String str3 = str1 + str2; Copy the code
Analysis: if the string constant pool the string object
- String constant pool :(2 objects) “ab”, “CD”, “abcd”;
- Heap: no
- Stack: (3 references) STR1, STR2, STR3 Total: 2 objects +3 references
String objects are specified using the java.lang.string.intern () method
code
String str1 = "123";
String str2 = new String("123");
String str3 = str2;
System.out.println(Str1 == str2: + (str1 == str2));
System.out.println("str1 == str3:" + (str1 == str3));
// Specify a String object with the java.lang.string.intern () method
String str4 = str2.intern();
System.out.println("str1 == str4:" + (str1 == str4));
Copy the code
Results:
Str1 = = str2:falseStr1 = = str3:falseStr1 = = str4:true
Copy the code
The length of the String
The maximum length of a Java String is divided into two phases, the compile phase and the runtime phase
Compilation stage:
When we define strings directly using String literals, we store a copy of the String in the constant pool. Each constant in the constant pool is a table with its own type. For the index, u2 is defined, which is 2 bytes unsigned. A CONSTANT_String_info table of fixed length is used to store literal String values. Note that this table stores only literal String values, not symbolic references.
The JVM’s constant pool can hold up to 65535 entries. The 0th term doesn’t have to. The last item can only be 65534(subscript value) at most. The maximum length of a utF-8 constant string in each entry is 65535 bytes (not characters).
Runtime phase:
A String is stored internally as a char array whose length is int. The maximum length allowed for a String is integer. MAX_VALUE, which is 2147483647. And since characters in Java are stored in 16 bits, it takes about 4GB of memory to store the maximum length of a string.
String Often meet test questions
1. How to compare two strings? Equals or equals
In simple terms, “==” checks whether two references refer to the same object in memory, and equals() checks whether the values of two objects are equal. Whenever you want to check whether two strings are equal, you have to use equals().
2. Why is char[] better for security-sensitive String information than String?
Strings are immutable, which means they won’t change until the garbage collector comes along to clean them up. With arrays, you can explicitly modify character elements anywhere in it. That way, security-sensitive information such as passwords cannot appear anywhere on the system.
3. Can string objects be used in switch expressions?
As of JDK7, we can use strings in switch conditional expressions, which is not possible prior to version 7.
// java 7 only!
switch (str.toLowerCase()) {
case "a":
value = 1;
break;
case "b":
value = 2;
break;
}
Copy the code
4. How to convert a string to an integer value?
int n = Integer.parseInt(“10”);
It is so simple that it is often used and occasionally forgotten.
5. How do I separate strings with Spaces?
We can easily use regular expressions to separate them. “\s” means space, as well as “, “\t “,” \r “, “\n”.
String[] strArray = aString.split(“\s+”);
6. What exactly does the subString() method do?
In JDK6, this method only gives a window to represent the resulting string on the character array that identifies the existing string, but does not create a new string object. If you need to create a new string object, you can add an empty string to the result like this:
str.subString(m, n) + “”
This creates a new character array to represent the resulting string. Also, there is a chance that your code will run faster because the garbage collector will recycle large strings that are not in use and leave behind substrings.
The subString() method in Oracle JDK7 creates a new character array instead of the existing one. Take a look at this figure to see the difference between the subString() method in JDK6 and JDK7.
7.String&StringBuilder&StringBuffer
String vs StringBuilder: StringBuilder is variable, and this means that you can also go to modify it after creating objects of value. StringBuilder vs StringBuffer: StringBuffer is synchronous, means it is thread-safe, but some will be slower than the StringBuilder.
8. How to quickly repeat a string?
In Python, you can just multiply a string by a number. In Java, you can use the repeat() method from the StringUtils class in the Apache Commons Lang package.
String str = “abcd”; String repeated = StringUtils.repeat(str,3); //abcdabcdabcd
9. How to convert a time-formatted string into a date object?
String str = “Sep 17, 2013”; Date date = new SimpleDateFormat(“MMMM d, yy”, Locale.ENGLISH).parse(str); System.out.println(date); //Tue Sep 17 00:00:00 EDT 2013
10. How do I count the number of occurrences of a character in a string?
You can do this using the StringUtils class in the Apache Commons Lang package.
int n = StringUtils.countMatches(“11112222”, “1”); System.out.println(n);