5.2 String Arrays and String Processing
A String array is an array where the type is String — an array that can hold multiple strings. Java's String is the most frequently used special class, and it is commonly used together with arrays.
1. Declaring and Initializing a String Array
// Empty String array (default value: null)
String[] names = new String[3];
System.out.println(names[0]); // null
// Initialize with values
String[] seasons = {"Spring", "Summer", "Autumn", "Winter"};
// Assign one by one using indices
String[] name = new String[3];
name[0] = "Kim";
name[1] = "Lee";
name[2] = "Park";
2. Iterating and Comparing String Arrays
String[] fruits = {"Apple", "Banana", "Orange", "Grape"};
// Iteration
for (String fruit : fruits) {
System.out.println(fruit);
}
// String comparison: use .equals(), NOT ==!
String target = "Banana";
for (int i = 0; i < fruits.length; i++) {
if (fruits[i].equals(target)) {
System.out.println(target + " found at index " + i + ".");
}
}
== vs .equals()
== compares references (addresses), while .equals() compares string content.
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b); // false (different objects)
System.out.println(a.equals(b)); // true (same content)
// String literals may return true with ==, but always use .equals()
String c = "hello";
String d = "hello";
System.out.println(c == d); // true (same object in String pool)
System.out.println(c.equals(d)); // true
3. Why String Is Immutable and Its Benefits
In Java, a String object cannot be changed once created.
String s = "Hello";
s = s + " World"; // creates a new String object; s now points to the new object
// The "Hello" object still exists on the heap (garbage collector will clean it up)
// s now references the new "Hello World" object
Benefits of immutability:
- Thread safety: Multiple threads can safely read the same string simultaneously.
- String Pool: The same literal shares one object, saving memory.
- Hash code caching: Strings can be safely used as keys in
HashMap. - Security: Guarantees that passwords, URLs, etc. are not altered.
// Use StringBuilder when string modification is frequent
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i).append(", ");
}
sb.delete(sb.length() - 2, sb.length()); // remove trailing ", "
System.out.println(sb.toString()); // 1, 2, 3, 4, 5
4. Internal Structure of String: char[] Array
String is internally composed of a char[] array.
String str = "Hello";
// Access a specific character with charAt()
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(i) + " "); // H e l l o
}
// Convert to a char[] array with toCharArray()
char[] chars = str.toCharArray();
System.out.println(chars[0]); // H
// Convert char[] array back to String
String restored = new String(chars);
System.out.println(restored); // Hello
5. Complete Reference of String Methods
Length and Character Access
String s = "Hello, Java!";
// Length
System.out.println(s.length()); // 12
// Character at a position
System.out.println(s.charAt(0)); // H
System.out.println(s.charAt(7)); // J
// Substring
System.out.println(s.substring(7)); // Java!
System.out.println(s.substring(7, 11)); // Java (index 7 inclusive to 11 exclusive)
Searching
String s = "Hello, Java! Hello!";
// Check if contained
System.out.println(s.contains("Java")); // true
// Find position (returns -1 if not found)
System.out.println(s.indexOf("Hello")); // 0 (first occurrence)
System.out.println(s.lastIndexOf("Hello")); // 13 (last occurrence)
System.out.println(s.indexOf("Python")); // -1
// Check start/end
System.out.println(s.startsWith("Hello")); // true
System.out.println(s.endsWith("!")); // true
Transformation and Replacement
String s = " Hello, Java! ";
// Remove whitespace
System.out.println(s.trim()); // "Hello, Java!" (removes leading/trailing whitespace, legacy)
System.out.println(s.strip()); // "Hello, Java!" (includes Unicode whitespace, Java 11+)
// Case conversion
System.out.println(s.trim().toUpperCase()); // HELLO, JAVA!
System.out.println(s.trim().toLowerCase()); // hello, java!
// Replace
String original = "I love Java. Java is great.";
System.out.println(original.replace("Java", "Python"));
// I love Python. Python is great.
Splitting and Joining
// Split
String csv = "Apple,Banana,Orange,Grape";
String[] fruits = csv.split(",");
System.out.println(fruits.length); // 4
for (String f : fruits) {
System.out.print(f + " "); // Apple Banana Orange Grape
}
// Join
String joined = String.join(" - ", fruits);
System.out.println(joined); // Apple - Banana - Orange - Grape
// Or with String.join()
System.out.println(String.join(", ", "A", "B", "C")); // A, B, C
Formatting
// String.format()
String name = "Alice";
int age = 25;
double gpa = 3.85;
String info = String.format("Name: %s, Age: %d, GPA: %.2f", name, age, gpa);
System.out.println(info); // Name: Alice, Age: 25, GPA: 3.85
// Java 15+: formatted()
String info2 = "Name: %s, Age: %d".formatted(name, age);
System.out.println(info2); // Name: Alice, Age: 25
Comparison
String a = "Apple";
String b = "apple";
System.out.println(a.equals(b)); // false (case-sensitive)
System.out.println(a.equalsIgnoreCase(b)); // true (case-insensitive)
System.out.println(a.compareTo(b)); // negative (A < a, lexicographic)
System.out.println(a.compareToIgnoreCase(b)); // 0 (equal)
Other Useful Methods (Java 11+)
String empty = " ";
String blank = "";
System.out.println(empty.isBlank()); // true (true even for whitespace-only)
System.out.println(blank.isEmpty()); // true (length is 0)
System.out.println("hello".repeat(3)); // hellohellohello
// lines() — split by line (returns a Stream)
"line1\nline2\nline3".lines().forEach(System.out::println);
6. Sorting String Arrays
import java.util.Arrays;
import java.util.Comparator;
String[] names = {"Charlie", "Alice", "Bob", "David", "Eve"};
// Lexicographic (ascending) sort
Arrays.sort(names);
System.out.println(Arrays.toString(names));
// [Alice, Bob, Charlie, David, Eve]
// Reverse lexicographic (descending) sort
Arrays.sort(names, Comparator.reverseOrder());
System.out.println(Arrays.toString(names));
// [Eve, David, Charlie, Bob, Alice]
// Sort by length
Arrays.sort(names, Comparator.comparingInt(String::length));
System.out.println(Arrays.toString(names));
// [Bob, Eve, Alice, David, Charlie]
// Sort by length, then lexicographically for equal lengths
Arrays.sort(names, Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()));
System.out.println(Arrays.toString(names));
7. Converting Between char Array and String
// String -> char[]
String str = "Hello";
char[] chars = str.toCharArray();
// Print char[]
System.out.println(chars); // Hello (can print char[] directly)
System.out.println(new String(chars)); // Hello
// Modify char[] then convert back to String
chars[0] = 'J';
String modified = new String(chars);
System.out.println(modified); // Jello
// Inspect each character
for (char c : chars) {
System.out.print(c + "(" + (int) c + ") "); // J(74) e(101) l(108) l(108) o(111)
}
8. Practical Example: Split a Sentence into Words and Process
import java.util.Arrays;
public class WordProcessor {
public static void main(String[] args) {
String sentence = " Java is a powerful and versatile programming language ";
// 1. Trim leading/trailing whitespace, then split on whitespace (regex \\s+: handles multiple spaces)
String[] words = sentence.trim().split("\\s+");
System.out.println("Word count: " + words.length);
System.out.println("Words: " + Arrays.toString(words));
// 2. Length of each word
System.out.println("\nLength of each word:");
for (String word : words) {
System.out.printf("%-15s: %d characters%n", word, word.length());
}
// 3. Find the longest word
String longest = words[0];
for (String word : words) {
if (word.length() > longest.length()) {
longest = word;
}
}
System.out.println("\nLongest word: " + longest + " (" + longest.length() + " characters)");
// 4. Filter words starting with a specific letter
char initial = 'p';
System.out.println("\nWords starting with '" + initial + "':");
for (String word : words) {
if (word.toLowerCase().startsWith(String.valueOf(initial))) {
System.out.println(" " + word);
}
}
// 5. Convert all words to uppercase and rejoin
String[] upperWords = new String[words.length];
for (int i = 0; i < words.length; i++) {
upperWords[i] = words[i].toUpperCase();
}
System.out.println("\nUppercase: " + String.join(" ", upperWords));
// 6. Sort alphabetically
Arrays.sort(words);
System.out.println("\nSorted words: " + Arrays.toString(words));
}
}
Output:
Word count: 8
Words: [Java, is, a, powerful, and, versatile, programming, language]
Length of each word:
Java : 4 characters
is : 2 characters
a : 1 characters
powerful : 8 characters
and : 3 characters
versatile : 9 characters
programming : 11 characters
language : 8 characters
Longest word: programming (11 characters)
Words starting with 'p':
powerful
programming
Uppercase: JAVA IS A POWERFUL AND VERSATILE PROGRAMMING LANGUAGE
Sorted words: [Java, a, and, is, language, powerful, programming, versatile]
Pro Tips
Key String Processing Patterns:
- Null-safe comparison: Use the
"constant".equals(variable)pattern to prevent NullPointerException
String input = null;
// input.equals("hello") -> NullPointerException!
"hello".equals(input) // -> false, safe
- StringBuilder for repeated string concatenation:
// Bad: creates a new String object on every iteration
String result = "";
for (int i = 0; i < 1000; i++) result += i + ", ";
// Good: use StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) sb.append(i).append(", ");
String result = sb.toString();
- Empty string check: Use
str.isEmpty()(length 0) vsstr.isBlank()(whitespace only)