Strings
Overview
A String is how Java handles text. Whether it's a user's password, a tweet, or a whole essay, it's stored as a String.
But Strings in Java have a very unique superpower (and a catch): They are Immutable. This means once a String is created in memory, its text can NEVER be changed. If you try to change 'hello' to 'HELLO', Java actually creates a brand new String in the background and throws the old one away. This makes Strings incredibly secure and safe to share across your app.
1. The String Pool
Because Strings are used so much, Java tries to save memory. If you create a String `String a = "Hi"` and later write `String b = "Hi"`, Java realizes they are the exact same text. Instead of making a new object, it just points `b` to `a`. This special memory area is called the String Pool.
2. Useful Built-in Methods
The String class comes with dozens of built-in tools to manipulate text. You can find the length, make it uppercase, search for a specific word, or replace letters instantly.
3. Comparing Strings
We said this before, but it's vital: NEVER use `==` to compare Strings. `==` checks if two variables are pointing to the exact same memory address. `.equals()` checks if the actual English text inside them is the same.
Syntax
Notice how calling methods on 'text' doesn't alter the original 'text' variable. It returns a brand new String.
String text = " Java is Fun ";
int len = text.length(); // 15 (includes spaces!)
String cleanText = text.trim(); // "Java is Fun" (removes outer spaces)
String loudText = cleanText.toUpperCase(); // "JAVA IS FUN"
boolean hasJava = cleanText.contains("Java"); // true
String sub = cleanText.substring(0, 4); // "Java" (grabs first 4 letters)Common Pitfalls
- Using `==` to compare text instead of `.equals()`. This creates massive, hard-to-find logical bugs.
- Calling a method on a String that is currently `null`. This will immediately crash your app with a `NullPointerException`.
Interview Tips
- The most common Java interview question: 'Why are Strings immutable?' Answer: For security (no one can alter a password reference), Thread-Safety, and Memory Efficiency (via the String Pool).
Real-World Example
Strings are used for validating inputs, like checking if an email is formatted correctly.
public class InputValidator {
public static void main(String[] args) {
String userEmail = " Kartik@Google.com ";
// Clean up user typos instantly
String normalizedEmail = userEmail.trim().toLowerCase();
if (normalizedEmail.contains("@") && normalizedEmail.endsWith(".com")) {
System.out.println("Valid Email: " + normalizedEmail);
} else {
System.out.println("Invalid Email format.");
}
}
}