Java Strings - Complete Guide
Introduction to Java Strings
Strings in Java are objects used to represent sequences of characters. Unlike primitive data types, String is a reference type with many built-in methods for manipulation.
Strings are immutable, meaning once created, their content cannot be changed. Operations that seem to modify a string actually return a new String object.
Creating Strings
Strings can be created in several ways, such as using literals, the `new` keyword, or from arrays of characters and bytes.
public class StringCreation {
public static void main(String[] args) {
// Method 1: Using string literals
String str1 = "Hello World";
// Method 2: Using new keyword
String str2 = new String("Hello World");
// Method 3: From character array
char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str3 = new String(charArray);
// Method 4: From byte array
byte[] byteArray = {72, 101, 108, 108, 111};
String str4 = new String(byteArray);
System.out.println("str1: " + str1);
System.out.println("str2: " + str2);
System.out.println("str3: " + str3);
System.out.println("str4: " + str4);
// String comparison
String literal1 = "Java";
String literal2 = "Java";
String newString1 = new String("Java");
String newString2 = new String("Java");
System.out.println("literal1 == literal2: " + (literal1 == literal2)); // true
System.out.println("newString1 == newString2: " + (newString1 == newString2)); // false
System.out.println("literal1.equals(newString1): " + literal1.equals(newString1)); // true
}
}
str1: Hello World str2: Hello World str3: Hello str4: Hello literal1 == literal2: true newString1 == newString2: false literal1.equals(newString1): true
Common String Methods
The `String` class includes many built-in methods for text manipulation. Below are examples of frequently used ones:
public class StringMethods {
public static void main(String[] args) {
String text = " Hello Java World ";
System.out.println("Length: " + text.length());
System.out.println("Uppercase: " + text.toUpperCase());
System.out.println("Lowercase: " + text.toLowerCase());
System.out.println("Trimmed: '" + text.trim() + "'");
System.out.println("Contains 'Java': " + text.contains("Java"));
System.out.println("Char at 7: " + text.charAt(7));
System.out.println("Substring (7-11): " + text.substring(7, 11));
System.out.println("Replace 'a' with 'o': " + text.replace('a', 'o'));
String[] words = text.trim().split(" ");
System.out.println("Split words:");
for (String word : words) {
System.out.println(" - " + word);
}
System.out.println("Starts with 'Hello': " + text.trim().startsWith("Hello"));
System.out.println("Ends with 'World': " + text.trim().endsWith("World"));
}
}
Length: 19 Uppercase: HELLO JAVA WORLD Lowercase: hello java world Trimmed: 'Hello Java World' Contains 'Java': true Char at 7: J Substring (7-11): Java Replace 'a' with 'o': Hello Jovo World Split words: - Hello - Java - World Starts with 'Hello': true Ends with 'World': true
String Immutability
Because strings are immutable, operations like concatenation or replacement generate new string objects rather than altering the original. This behavior improves security and efficiency with the string pool.
public class StringImmutability {
public static void main(String[] args) {
String original = "Hello";
String modified = original.concat(" World");
System.out.println("Original: " + original);
System.out.println("Modified: " + modified);
System.out.println("Are they the same object? " + (original == modified));
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");
System.out.println("s1 == s2: " + (s1 == s2));
System.out.println("s1 == s3: " + (s1 == s3));
System.out.println("s1.equals(s3): " + s1.equals(s3));
String s4 = s3.intern();
System.out.println("s1 == s4: " + (s1 == s4));
}
}
Original: Hello Modified: Hello World Are they the same object? false s1 == s2: true s1 == s3: false s1.equals(s3): true s1 == s4: true
Best Practices for Working with Strings
- ✅ Prefer string literals to leverage string pooling
- ✅ Use `StringBuilder` or `StringBuffer` when modifying strings repeatedly
- ✅ Always use `equals()` to compare string contents instead of `==`
- ✅ Use `isEmpty()` for checking empty strings instead of `length() == 0`
- ✅ Avoid concatenating strings in loops; use `StringBuilder` for efficiency
- ✅ Apply `trim()` to handle unwanted whitespace in user input
- ✅ Use `String.format()` for complex formatting instead of manual concatenation
- ✅ Explore built-in methods before writing custom string logic