Mastering Strings: More Than Just Text
In Java, a String is not just a primitive data type like an int or a boolean. It is actually an Object. This means every String comes with a built-in "Swiss Army Knife" of methods that allow you to manipulate, search, and change text easily.
1. What makes Strings special?
Strings are immutable. This is a fancy way of saying that once a String is created, it cannot be changed. When you "change" a String, Java is actually creating a brand-new String in the background and throwing the old one away.
2. Essential String Methods
Here are the tools you will use most often:
| Method | What it does | Example (String s = "Java") |
Result |
|---|---|---|---|
length() |
Returns the number of characters | s.length() |
4 |
toUpperCase() |
Converts to all caps | s.toUpperCase() |
"JAVA" |
toLowerCase() |
Converts to all lowercase | s.toLowerCase() |
"java" |
charAt(index) |
Gets the character at a position | s.charAt(0) |
'J' |
indexOf(char) |
Finds the position of a character | s.indexOf('v') |
2 |
isEmpty() |
Checks if the string is empty | s.isEmpty() |
false |
trim() |
Removes whitespace from ends | " hi ".trim() |
"hi" |
3. Comparison: The .equals() Rule
As we mentioned before, never use == to compare Strings. * == checks if the "boxes" are the same.
.equals()checks if the "text inside the boxes" is the same.
String name1 = "YourName";
String name2 = new String("YourName");
System.out.println(name1 == name2); // false (Different boxes)
System.out.println(name1.equals(name2)); // true (Same text)
4. Extracting Parts: substring()
If you want to grab a specific part of a String, use substring(start, end).
- The
startindex is included. - The
endindex is excluded.
String blog = "JavaTutorial";
String part = blog.substring(0, 4); // Grabs index 0, 1, 2, 3
System.out.println(part); // Output: Java
💻 Full Practical Example: The Email Formatter
Copy this code to see how multiple String methods can work together to clean up user data:
import java.util.Scanner;
public class StringMaster {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your full name: ");
String fullName = input.nextLine();
// 1. Clean up spaces and convert to uppercase
String cleanName = fullName.trim().toUpperCase();
// 2. Get the first initial
char initial = cleanName.charAt(0);
// 3. Check if the name contains a specific word
boolean isCoder = cleanName.contains("CODER");
System.out.println("Formatted Name: " + cleanName);
System.out.println("Your Initial: " + initial);
System.out.println("Is a c0der? " + isCoder);
input.close();
}
}
💡 Challenge: The Word Shuffler
Write a program that asks the user for a single word.
- Print the length of the word.
- Print the first and last character of the word.
- Print the word entirely in lowercase.
- Bonus: Try to use
substring()to print only the middle part of the word (excluding the first and last letters)!