The String class is the most commonly used Reference Type in Java. It is used to store sequences of characters (text).
Crucially, Strings in Java are Immutable. This means that once a String object is created in memory, its contents can NEVER be changed. If you try to modify a string (e.g., converting it to uppercase or appending a word), Java doesn't actually change the original string; it creates a brand new string object in the Heap memory and points your variable to the new one.
Java provides a massive suite of built-in methods on the String class to manipulate text, such as .length(), .substring(), and .replace().
Because Strings are objects, you interact with them via methods. Remember that methods like toUpperCase() do NOT alter the original string; they return a newly altered copy.
public class Main {
public static void main(String[] args) {
String greeting = "Hello, World!";
// 1. Length and Case
System.out.println(greeting.length()); // 13
System.out.println(greeting.toUpperCase()); // "HELLO, WORLD!"
// 2. Substrings (Extracting parts)
// Starts at index 0, stops BEFORE index 5
String firstWord = greeting.substring(0, 5); // "Hello"
// 3. Comparison
String a = "java";
String b = "JAVA";
System.out.println(a.equals(b)); // false (Case sensitive)
System.out.println(a.equalsIgnoreCase(b)); // true
// 4. Searching and Replacing
System.out.println(greeting.contains("World")); // true
String newStr = greeting.replace("World", "Java"); // "Hello, Java!"
}
}== to compare text. Because Strings are Objects, == checks if they point to the exact same physical memory address in the String Pool. If one string was created using new String(), == will return false even if the text is identical. ALWAYS use .equals()..equals() on a String variable that is currently null will crash the application. Always put the known literal first: "knownWord".equals(variable) is much safer.str += "a"; inside a massive loop creates a brand new String object in the heap every single iteration, destroying performance. Use StringBuilder for loops.What is the String Pool?
To save memory, the JVM maintains a special area in the Heap called the String Pool. When you create a literal string like String s = "Cat";, the JVM checks the pool. If "Cat" already exists, it doesn't create a new object; it just points s to the existing "Cat". This heavily optimizes memory usage.
Why are Strings designed to be Immutable in Java?
Security and Thread Safety. Strings are used everywhere (network connections, database URLs, passwords). If Strings were mutable, malicious code could change the value of a string after it had passed a security validation check. Immutability guarantees the data is un-tamperable.
Sanitizing user inputs on a backend server. Before saving a user's email to a database, you must aggressively trim whitespace, convert it to lowercase, and validate its format using String methods.
public void register(String rawEmail) {
// Sanitize the input
String cleanEmail = rawEmail.trim().toLowerCase();
if(!cleanEmail.contains("@")) {
throw new Exception("Invalid Email Format");
}
db.save(cleanEmail);
}Test your understanding of Strings with these quick questions.
Question 1
What does it mean that Strings are Immutable?
Question 2
Which method is the ONLY correct way to compare if two Strings contain the exact same text?
Question 3
What will `"Programming".substring(0, 3)` return?
The String class is the most commonly used Reference Type in Java. It is used to store sequences of characters (text).
Crucially, Strings in Java are Immutable. This means that once a String object is created in memory, its contents can NEVER be changed. If you try to modify a string (e.g., converting it to uppercase or appending a word), Java doesn't actually change the original string; it creates a brand new string object in the Heap memory and points your variable to the new one.
Java provides a massive suite of built-in methods on the String class to manipulate text, such as .length(), .substring(), and .replace().
Because Strings are objects, you interact with them via methods. Remember that methods like toUpperCase() do NOT alter the original string; they return a newly altered copy.
public class Main {
public static void main(String[] args) {
String greeting = "Hello, World!";
// 1. Length and Case
System.out.println(greeting.length()); // 13
System.out.println(greeting.toUpperCase()); // "HELLO, WORLD!"
// 2. Substrings (Extracting parts)
// Starts at index 0, stops BEFORE index 5
String firstWord = greeting.substring(0, 5); // "Hello"
// 3. Comparison
String a = "java";
String b = "JAVA";
System.out.println(a.equals(b)); // false (Case sensitive)
System.out.println(a.equalsIgnoreCase(b)); // true
// 4. Searching and Replacing
System.out.println(greeting.contains("World")); // true
String newStr = greeting.replace("World", "Java"); // "Hello, Java!"
}
}== to compare text. Because Strings are Objects, == checks if they point to the exact same physical memory address in the String Pool. If one string was created using new String(), == will return false even if the text is identical. ALWAYS use .equals()..equals() on a String variable that is currently null will crash the application. Always put the known literal first: "knownWord".equals(variable) is much safer.str += "a"; inside a massive loop creates a brand new String object in the heap every single iteration, destroying performance. Use StringBuilder for loops.What is the String Pool?
To save memory, the JVM maintains a special area in the Heap called the String Pool. When you create a literal string like String s = "Cat";, the JVM checks the pool. If "Cat" already exists, it doesn't create a new object; it just points s to the existing "Cat". This heavily optimizes memory usage.
Why are Strings designed to be Immutable in Java?
Security and Thread Safety. Strings are used everywhere (network connections, database URLs, passwords). If Strings were mutable, malicious code could change the value of a string after it had passed a security validation check. Immutability guarantees the data is un-tamperable.
Sanitizing user inputs on a backend server. Before saving a user's email to a database, you must aggressively trim whitespace, convert it to lowercase, and validate its format using String methods.
public void register(String rawEmail) {
// Sanitize the input
String cleanEmail = rawEmail.trim().toLowerCase();
if(!cleanEmail.contains("@")) {
throw new Exception("Invalid Email Format");
}
db.save(cleanEmail);
}Test your understanding of Strings with these quick questions.
Question 1
What does it mean that Strings are Immutable?
Question 2
Which method is the ONLY correct way to compare if two Strings contain the exact same text?
Question 3
What will `"Programming".substring(0, 3)` return?