Preface
In Java, the String class is a very important built-in class for processing string data. A string is immutable, which means that once created, the contents of the string cannot be modified. As one of the most basic and commonly used classes in Java, the String class has unique design and implementation in memory management, thread safety, performance optimization, etc. This article will introduce in detail the characteristics, uses, main methods and common uses of String classes in Java, and will show how to create, manipulate and use String classes in Java through code examples.
1. Features of String
1.1 Immutability
Once a String object is created, its content cannot be changed. This immutability is achieved by modifying the character array value by final keyword. There is no method to modify the character array in the String class. Any modification operation to a string (such as splicing, substitution, etc.) will create a new String object.
String str1 = "Hello"; String str2 = (" World"); // Create a new string object "Hello World"(str1); // Output: Hello(str2); // Output: Hello World
Immutability brings several benefits:
- Security: In a multi-threaded environment, multiple threads can safely share the same string object without worrying about data being modified.
- Memory efficiency: Immutable strings can be shared. When creating a string literal in a constant pool, subsequent references to the same content will point directly to objects in the constant pool instead of creating new objects, thus reducing memory consumption.
- Hash code cache: Since strings are immutable, their hash codes are only calculated once and can be cached. This makes strings more efficient when they are keys to the hash table, because there is no need to recalculate the hash value every time you look up.
1.2 String constant pool
String constant pool is a special memory area in Java that stores string literals and some constant strings. When creating a String object using literal method, the JVM first checks whether the string object with the same content already exists in the string constant pool. If it exists, it directly returns the reference to the string object in the constant pool; if it does not exist, a new string object is created in the constant pool and its reference is returned.
String str1 = "Hello"; String str2 = "Hello"; (str1 == str2); // Output: true,str1andstr2Reference is the same string object
Through the intern() method, you can manually place a String object into a string constant pool.
String str1 = new String("Hello"); String str2 = (); String str3 = "Hello"; (str2 == str3); // Output: true,str2andstr3Reference is the same string object
1.3 Memory structure
The memory structure of String objects in memory mainly includes character array value, hash code hash and offset offset (in JDK 9 and later versions, if the string content is in the Latin-1 character set, it is stored using the byte array and distinguished with encoding identifier).
- Character array value: A sequence of characters used to store strings. Before JDK 9, UTF-16-encoded character arrays were used; in JDK 9 and later, if the string contents are all in the Latin-1 character set, the byte array is stored.
- hash code hash: Hashcode used to cache strings to avoid recalculating each time the hashCode() method is called.
- Offset(In JDK 9 and later): Used to identify the starting position of a string in a byte array (if the string is stored using a byte array).
1.4 The impact of JDK version update on String class
With the update of the JDK version, the underlying design and optimization of the String class are also constantly developing.
- JDK 6: The string constant pool is located in the permanent generation (method area), and it stores the object itself.
- JDK 7: Move the constant pool from the permanent generation to the heap memory, storing the reference to the object.
- JDK 8: Metaspace is introduced to replace the permanent generation, and the creation of strings and the behavior of the intern() method are optimized.
- JDK 9: A major underlying optimization was carried out on the String class. Instead, a byte array was used to store string data (if the string contents were all in the Latin-1 character set), and a coder field and COMPACT_STRINGS attribute were introduced to control the compact storage function of strings.
2. Use of String
2.1 Represents text data
Strings are the standard way to represent textual data in computer science. In Java, strings are often used to represent personal information such as the user's name and address, as well as various text information in the program.
2.2 Processing text data
Java provides a wealth of built-in functions and methods, allowing developers to easily process text data. For example, various methods of the String class can be used to find substrings, replace characters, split strings, etc.
2.3 Memory management and performance optimization
Through string constant pooling and immutability design, the String class excels in memory management and performance optimization. It reduces duplicate string storage in memory, improves memory utilization and access efficiency, and allows the JVM to cache and reuse strings, reducing the overhead of creating new objects.
3. Main methods of String class
3.1 Creating a String
3.1.1 Direct assignment
String str = "Hello, World!";
String objects created in this way will be placed in the string constant pool.
3.1.2 Using the new keyword
String str = new String("Hello, World!");
This way creates a new String object in heap memory and is not put into the string constant pool (unless manually put in via the intern() method).
3.1.3 Character array to String
char[] array = {'a', 'b', 'c'}; String str = new String(array);
3.2 String comparison
3.2.1 == Comparison
String str1 = "Hello"; String str2 = "Hello"; String str3 = new String("Hello"); (str1 == str2); // Output: true, str1 and str2 refer to the same string object(str1 == str3); // Output: false,str1andstr3References are different string objects
== Compare whether the references of the string object are the same.
3.2.2 equals method
((str3)); // Output: true,str1andstr3The same content
The equals method compares whether the contents of the string object are the same.
3.2.3 compareTo method
String str4 = "World"; ((str4)); // Output: -11,In dictionary order,"Hello"Less than"World"
The compareTo method compares the size relationship of two strings in dictionary order, and the return value is of type int.
3.2.4 compareToIgnoreCase method
((str4)); // Output: -11,Ignore case comparison
The compareToIgnoreCase method is similar to the compareTo method, but the letter case is ignored when comparing.
3.3 Get length
String str = "Hello, World!"; int length = (); // Return the length of the string(length); // Output: 13
3.4 String search
3.4.1 charAt method
char ch = (7); // Returns the character at the specified index position(ch); // Output: W
The charAt method returns the characters at the specified index position, and the index range starts from 0.
3.4.2 indexOf method
int index = ("World"); // Returns the first occurrence of the specified substring(index); // Output: 7index = ("Java", 8); // Start searching from the specified index(index); // Output: -1,not found
The indexOf method returns the first occurrence of the specified substring, and -1 if not found.
3.4.3 lastIndexOf method
int lastIndex = ("o"); // Returns the last occurrence of the specified character(lastIndex); // Output: 8lastIndex = ("o", 7); // Start reverse search from the specified index(lastIndex); // Output: 4
The lastIndexOf method returns the last occurrence of the specified character or substring, and -1 if not found.
3.4.4 contains method
boolean containsHello = ("Hello"); // Determine whether the string contains the specified character sequence(containsHello); // Output: true
The contains method is used to determine whether a string contains the specified character sequence.
3.5 Substring
3.5.1 Substring method
String subStr = (7, 12); // Return the substring from beginIndex to endIndex-1(subStr); // Output: World
The substring method returns a substring from beginIndex to endIndex-1.
3.6 String replacement
3.6.1 replace method
String replacedStr = ("World", "Java"); // Replace characters in string(replacedStr); // Output: Hello, Java!
The replace method is used to replace characters or substrings in a string.
3.6.2 replaceAll method
String replacedAllStr = ("o", "0"); // Replace content in a string with regular expression(replacedAllStr); // Output: Hell0, W0rld!
The replaceAll method replaces all matches in the string with a regular expression.
3.6.3 replaceFirst method
String replacedFirstStr = ("o", "0"); // Replace the first match in the string(replacedFirstStr); // Output: Hello, W0rld!
The replaceFirst method replaces the first match in the string.
3.7 Case conversion
3.7.1 toLowerCase method
String lowerStr = (); // Convert string to lowercase(lowerStr); // Output: hello, world!
The toLowerCase method converts a string to lowercase.
3.7.2 toUpperCase method
String upperStr = (); // Convert string to uppercase(upperStr); // Output: HELLO, WORLD!
toUpperCase method converts the string to uppercase.
3.8 Remove the beginning and end spaces of strings
String trimmedStr = (); // Remove whitespace characters at both ends of the string(trimmedStr); // Output: Hello, World!(Assume there are no spaces at both ends of the original string)
The trim method is used to remove whitespace characters (including spaces, tabs, line breaks, etc.) at both ends of a string.
3.9 String Splitting
String[] splitStrs = (", "); // Splitting string according to regular expressionfor (String s : splitStrs) { (s); } // Output:// Hello // World!
The split method splits the string according to the given regular expression and returns an array of strings.
3.10 String connection
3.10.1 Using the + operator
String concatenatedStr = "Hello" + " " + "World!"; // Use the + operator to connect the string(concatenatedStr); // Output: Hello World!
At compile time, Java will optimize the splicing of multiple string literals into a StringBuilder append operation.
3.10.2 Using StringBuilder or StringBuffer
StringBuilder sb = new StringBuilder(); ("Hello").append(" ").append("World!"); String concatenatedStr = (); (concatenatedStr); // Output: Hello World!
Both StringBuilder and StringBuffer provide operations for mutable strings, but StringBuilder is non-thread-safe, while StringBuffer is thread-safe. In a single threaded environment, it is recommended to use StringBuilder for performance improvement.
3.11 Other common methods
3.11.1 startsWith method
boolean startsWithHello = ("Hello"); // Determine whether the string starts with the specified prefix(startsWithHello); // Output: true
The startsWith method is used to determine whether the string starts with the specified prefix.
3.11.2 endsWith method
boolean endsWithExclamation = ("!"); // Determine whether the string ends with the specified suffix(endsWithExclamation); // Output: true
The endsWith method is used to determine whether the string ends with the specified suffix.
3.11.3 toCharArray method
char[] charArray = (); // Convert string to character arrayfor (char c : charArray) { (c); } // Output: Hello, World!
The toCharArray method converts a string to a character array.
3.11.4 split(String regex, int limit) method
String[] splitStrsWithLimit = (", ", 2); // Split the string according to regular expression and limit the number of splitsfor (String s : splitStrsWithLimit) { (s); } // Output:// Hello // World!
The split(String regex, int limit) method splits the string according to the given regular expression and limits the number of splits.
4. Common usage of String class
4.1 String stitching
In Java, string stitching is a common operation. Due to String immutability, using the + operator to do string stitching can cause performance issues (especially when strings are spliced multiple times in a loop). Therefore, it is recommended to use StringBuilder or StringBuffer for string splicing.
// Use the + operator for string splicing (not recommended in loops)String result = ""; for (int i = 0; i < 1000; i++) { result += "Hello "; } (result); // Use StringBuilder for string splicing (recommended)StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) { ("Hello "); } String resultWithStringBuilder = (); (resultWithStringBuilder);
4.2 String comparison
In Java, string comparisons usually use the equals method instead of==
Operator. because==
The operator compares whether the references of the string object are the same, while the equals method compares whether the contents of the string object are the same.
String str1 = "Hello"; String str2 = new String("Hello"); (str1 == str2); // Output: false, str1 and str2 refer to different string objects((str2)); // Output: true,str1andstr2The same content
4.3 String search and replacement
In text processing, it is often necessary to look up substrings or replace certain characters in strings. The String class provides a wealth of methods to support these operations.
String text = "Hello, welcome to the world of Java!"; // Find substringsint index = ("welcome"); ("Index of 'welcome': " + index); // Output: 7// Replace characters in stringString replacedText = ("Java", "Programming"); (replacedText); // Output: Hello, welcome to the world of Programming!
4.4 String splitting
When working with CSV files or parsing complex strings, it is often necessary to split the string into multiple parts. The split method of the String class provides a convenient way to achieve this.
String csvLine = "name,age,city"; String[] fields = (","); for (String field : fields) { (field); } // Output:// name // age // city
4.5 String formatting
When outputting a formatted string, you can use a method or a Formatter class.
String name = "Alice"; int age = 30; String formattedString = ("Name: %s, Age: %d", name, age); (formattedString); // Output: Name: Alice, Age: 30
Summarize
The String class in Java is an important built-in class for processing string data. Its features include immutability, string constant pool, specific memory structures, and optimizations updated with JDK version. The String class is widely used to represent and process text data and performs excellently in memory management and performance optimization. The main methods include creating strings, string comparisons, getting lengths, string searches, substring operations, string replacement, case conversion, removing beginning and end spaces, string splitting and concatenation, etc. Common usages involve string stitching, comparison, search and replacement, splitting, and formatting. By using the String class reasonably, text data can be effectively processed and program performance can be optimized.
This is all about this article about in-depth understanding of String in Java. For more related String content in Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!