In Java, strings are fundamental for handling text information, and the String class is one of the most commonly used classes in Java for representing and manipulating text data. A string is essentially a sequence of characters, and the String class provides a rich set of methods to facilitate various text operations such as obtaining length, concatenation, comparison, splitting, and more.
一、Basic Characteristics of the String Class¶
First, it is crucial to understand a key characteristic of String: immutability. This means that once a String object is created, its content cannot be modified. If modifications are needed, a new String object is effectively created.
Example:
String original = "Hello";
original = original + " World"; // A new String object is created here
二、Common Methods and Examples¶
Next, we will introduce the most commonly used methods of the String class, each accompanied by code examples and explanations.
1. Get String Length: length()¶
The length() method returns the length of the string (i.e., the number of characters).
Example:
String str = "Java Programming";
int len = str.length();
System.out.println("String length: " + len); // Output: 18
2. Get Character at a Specific Position: charAt(int index)¶
The charAt(index) method returns the character at the specified index position in the string (indexes start from 0).
Example:
String str = "Hello";
char firstChar = str.charAt(0); // Get the 0th character (first character)
char lastChar = str.charAt(str.length() - 1); // Get the last character
System.out.println("First character: " + firstChar); // Output: H
System.out.println("Last character: " + lastChar); // Output: o
3. String Concatenation: concat(String str) or + Operator¶
The concat() method concatenates the current string with another string. Additionally, Java supports the + operator for string concatenation.
Example:
String a = "Hello";
String b = "World";
// Using concat()
String c = a.concat(b);
System.out.println(c); // Output: HelloWorld
// Using the + operator
String d = a + " " + b;
System.out.println(d); // Output: Hello World
4. Compare String Content: equals(String str)¶
The equals() method is used to compare whether the contents of two strings are equal. Note: Do not use the == operator to compare string content, as == compares the memory addresses of the objects (unless the string is a constant in the constant pool).
Example:
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc"); // New object with a different address than s1
System.out.println(s1 == s2); // true (constant pool reuse, may be the same)
System.out.println(s1 == s3); // false (s3 is a new object with a different address)
System.out.println(s1.equals(s2)); // true (content is the same)
System.out.println(s1.equals(s3)); // true (content is the same)
Important Conclusion: Always use equals() to compare string content, not ==.
5. Substring Extraction: substring(int beginIndex) or substring(int beginIndex, int endIndex)¶
substring(beginIndex): Extracts frombeginIndexto the end of the string.substring(beginIndex, endIndex): Extracts the substring frombeginIndextoendIndex-1(left-closed, right-open).
Example:
String s = "HelloWorld";
// Extract from index 2 to the end
String part1 = s.substring(2);
System.out.println(part1); // Output: lloWorld
// Extract from index 2 to 5 (excluding 5)
String part2 = s.substring(2, 5);
System.out.println(part2); // Output: llo
6. Replace Characters/Substrings: replace(char oldChar, char newChar) or replace(CharSequence target, CharSequence replacement)¶
The replace() method can replace individual characters or entire substrings:
- Replace a single character: replace(oldChar, newChar)
- Replace a substring: replace(target, replacement)
Example:
String s = "Hello Java";
// Replace the single character 'H' with 'h'
String newS1 = s.replace('H', 'h');
System.out.println(newS1); // Output: hllo Java
// Replace the substring "Java" with "Python"
String newS2 = s.replace("Java", "Python");
System.out.println(newS2); // Output: Hello Python
7. Trim Leading and Trailing Whitespace: trim()¶
The trim() method removes leading and trailing whitespace characters (spaces, tabs, newlines, etc.).
Example:
String s = " Java String ";
String trimmed = s.trim();
System.out.println(trimmed); // Output: Java String
8. Split String: split(String regex)¶
The split() method splits a string into multiple substrings based on a specified delimiter (regular expression) and returns an array of strings.
Example:
String csv = "apple,banana,orange,grape";
String[] fruits = csv.split(","); // Split by commas
for (String fruit : fruits) {
System.out.println(fruit); // Output each fruit in sequence
}
// Output:
// apple
// banana
// orange
// grape
9. Case Conversion: toLowerCase() and toUpperCase()¶
toLowerCase(): Converts all characters in the string to lowercase.toUpperCase(): Converts all characters in the string to uppercase.
Example:
String s = "Hello World";
String lower = s.toLowerCase();
String upper = s.toUpperCase();
System.out.println(lower); // Output: hello world
System.out.println(upper); // Output: HELLO WORLD
10. Check for Empty/Blank Strings: isEmpty() and isBlank()¶
isEmpty(): Checks if the string length is 0 (returnstrueonly if length is 0).isBlank()(Java 11+): Checks if the string is blank (length 0 or contains only whitespace characters like spaces, tabs).
Example:
String emptyStr = "";
String blankStr = " ";
String normalStr = "Java";
System.out.println(emptyStr.isEmpty()); // true
System.out.println(emptyStr.isBlank()); // true
System.out.println(blankStr.isEmpty()); // false (length is 3)
System.out.println(blankStr.isBlank()); // true (contains whitespace)
System.out.println(normalStr.isEmpty()); // false
System.out.println(normalStr.isBlank()); // false
三、Notes¶
- Immutability: Modifying a string creates a new object, which can cause performance issues (e.g., string concatenation in loops). In such cases,
StringBuilderorStringBuffer(thread-safe) is recommended. - Avoid Using
==for Content Comparison: Useequals()instead, unless you are certain the strings refer to the same object in the constant pool. - Special Character Handling: When using
split()with special regex characters (e.g.,.,*), escape them (e.g.,split("\\.")to split on.).
四、Summary¶
Mastering the common methods of the String class is fundamental for Java text operations. Using methods like length(), charAt(), equals(), and substring(), you can easily handle most text processing tasks such as extracting information, concatenating content, converting formats, and splitting data. As Java evolves (e.g., adding isBlank()), more practical methods are introduced, and continuous learning and practice will enhance your efficiency in string manipulation.