Java Notes
Complete reference of all Java String methods with syntax, parameters, return types, examples, and output for each method including charAt, substring, indexOf, replace, split, trim, and more.
Overview
The Java String class provides a rich set of methods for manipulating text. Since Strings are immutable, every method that appears to modify a String actually returns a NEW String object — the original remains unchanged.
This chapter covers every important String method organized by category with complete examples and output.
Length and Character Access
length()
Returns the number of characters in the string.
public class LengthDemo {
public static void main(String[] args) {
String s = "Hello World";
System.out.println("String: \"" + s + "\"");
System.out.println("Length: " + s.length());
System.out.println("Empty string length: " + "".length());
System.out.println("Space length: " + " ".length());
}
}String: "Hello World" Length: 11 Empty string length: 0 Space length: 1
charAt(int index)
Returns the character at the specified index (0-based).
String: Programming charAt(0): P charAt(3): g Last char: g Characters: P r o g r a m m i n g
toCharArray()
Converts the string to a character array.
String: Java Char array: [J, a, v, a] After modifying array: Lava Original string: Java
Searching Methods
indexOf(String str) / indexOf(char ch)
Returns the index of the first occurrence, or -1 if not found.
public class IndexOfDemo {
public static void main(String[] args) {
String s = "Hello World Hello Java";
System.out.println("String: \"" + s + "\"");
System.out.println("indexOf(\'o\'): " + s.indexOf('o'));
System.out.println("indexOf(\"Hello\"): " + s.indexOf("Hello"));
System.out.println("indexOf(\"Hello\", 5): " + s.indexOf("Hello", 5)); // Start from index 5
System.out.println("indexOf(\"Python\"): " + s.indexOf("Python")); // Not found
}
}String: "Hello World Hello Java"
indexOf('o'): 4
indexOf("Hello"): 0
indexOf("Hello", 5): 12
indexOf("Python"): -1lastIndexOf(String str)
Returns the index of the last occurrence.
public class LastIndexOfDemo {
public static void main(String[] args) {
String path = "C:/Users/Admin/Documents/file.txt";
System.out.println("Path: " + path);
System.out.println("lastIndexOf('/'): " + path.lastIndexOf('/'));
System.out.println("lastIndexOf('.'): " + path.lastIndexOf('.'));
// Extract filename
String filename = path.substring(path.lastIndexOf('/') + 1);
System.out.println("Filename: " + filename);
// Extract extension
String ext = path.substring(path.lastIndexOf('.') + 1);
System.out.println("Extension: " + ext);
}
}Path: C:/Users/Admin/Documents/file.txt
lastIndexOf('/'): 24
lastIndexOf('.'): 29
Filename: file.txt
Extension: txtcontains(CharSequence s)
Returns true if the string contains the specified sequence.
public class ContainsDemo {
public static void main(String[] args) {
String email = "user@example.com";
System.out.println("Email: " + email);
System.out.println("Contains @: " + email.contains("@"));
System.out.println("Contains .com: " + email.contains(".com"));
System.out.println("Contains .org: " + email.contains(".org"));
}
}Email: user@example.com Contains @: true Contains .com: true Contains .org: false
Substring Methods
substring(int beginIndex) / substring(int beginIndex, int endIndex)
Extracts a portion of the string. endIndex is exclusive.
public class SubstringDemo {
public static void main(String[] args) {
String s = "Hello World";
// 0123456789...
System.out.println("String: \"" + s + "\"");
System.out.println("substring(6): \"" + s.substring(6) + "\""); // From index 6 to end
System.out.println("substring(0,5): \"" + s.substring(0, 5) + "\""); // From 0 to 4 (5 excluded)
System.out.println("substring(3,8): \"" + s.substring(3, 8) + "\""); // From 3 to 7
// Common use: extract parts of data
String date = "2024-06-15";
String year = date.substring(0, 4);
String month = date.substring(5, 7);
String day = date.substring(8);
System.out.println("\nDate: " + date);
System.out.println("Year: " + year + ", Month: " + month + ", Day: " + day);
}
}String: "Hello World" substring(6): "World" substring(0,5): "Hello" substring(3,8): "lo Wo" Date: 2024-06-15 Year: 2024, Month: 06, Day: 15
Modification Methods (Return New String)
replace(char old, char new) / replace(CharSequence old, CharSequence new)
public class ReplaceDemo {
public static void main(String[] args) {
String s = "Java is fun. Java is powerful.";
System.out.println("Original: " + s);
System.out.println("replace('a', '@'): " + s.replace('a', '@'));
System.out.println("replace(\"Java\", \"Python\"): " + s.replace("Java", "Python"));
// Remove characters by replacing with empty string
String phone = "+1-800-555-1234";
String digits = phone.replace("-", "").replace("+", "");
System.out.println("\nPhone: " + phone);
System.out.println("Digits only: " + digits);
}
}Original: Java is fun. Java is powerful.
replace('a', '@'): J@v@ is fun. J@v@ is powerful.
replace("Java", "Python"): Python is fun. Python is powerful.
Phone: +1-800-555-1234
Digits only: 18005551234replaceAll(String regex, String replacement)
Uses regular expressions for pattern-based replacement.
Original: "Hello World Java 2024" Cleaned: "Hello World Java 2024" Original: Order #12345 placed on 2024-01-15 No digits: Order # placed on -- Alpha only: Order placed on
toUpperCase() and toLowerCase()
public class CaseDemo {
public static void main(String[] args) {
String mixed = "Hello World 123!";
System.out.println("Original: " + mixed);
System.out.println("Upper: " + mixed.toUpperCase());
System.out.println("Lower: " + mixed.toLowerCase());
// Case-insensitive comparison
String a = "Java";
String b = "JAVA";
System.out.println("\n\"" + a + "\".equalsIgnoreCase(\"" + b + "\"): " + a.equalsIgnoreCase(b));
}
}Original: Hello World 123!
Upper: HELLO WORLD 123!
Lower: hello world 123!
"Java".equalsIgnoreCase("JAVA"): truetrim(), strip(), stripLeading(), stripTrailing()
public class TrimDemo {
public static void main(String[] args) {
String s = " Hello World ";
System.out.println("Original: \"" + s + "\"");
System.out.println("trim(): \"" + s.trim() + "\"");
System.out.println("strip(): \"" + s.strip() + "\"");
System.out.println("stripLeading(): \"" + s.stripLeading() + "\"");
System.out.println("stripTrailing(): \"" + s.stripTrailing() + "\"");
// Difference: strip() handles Unicode whitespace, trim() only ASCII <=32
}
}Original: " Hello World " trim(): "Hello World" strip(): "Hello World" stripLeading(): "Hello World " stripTrailing(): " Hello World"
Splitting and Joining
split(String regex)
Splits the string into an array based on a delimiter pattern.
CSV: Apple,Banana,Cherry,Date Parts: [Apple, Banana, Cherry, Date] Count: 4 Limited split: [one, two, three:four:five] Multi-delimiter: [Hello, World, Java, Programming] IP octets: [192, 168, 1, 100]
String.join(delimiter, elements)
Joins multiple strings with a delimiter (Java 8+).
public class JoinDemo {
public static void main(String[] args) {
// Join strings
String result = String.join(", ", "Apple", "Banana", "Cherry");
System.out.println("Joined: " + result);
// Join array
String[] words = {"Java", "is", "awesome"};
String sentence = String.join(" ", words);
System.out.println("Sentence: " + sentence);
// Build CSV
String csv = String.join(",", "Name", "Age", "City");
System.out.println("CSV header: " + csv);
// Join with complex delimiter
String path = String.join("/", "home", "user", "documents");
System.out.println("Path: " + path);
}
}Joined: Apple, Banana, Cherry Sentence: Java is awesome CSV header: Name,Age,City Path: home/user/documents
Checking Methods
isEmpty() and isBlank()
public class EmptyBlankDemo {
public static void main(String[] args) {
String empty = "";
String blank = " ";
String text = "Hello";
System.out.println("String\t\tisEmpty()\tisBlank()");
System.out.println("\"\"\t\t" + empty.isEmpty() + "\t\t" + empty.isBlank());
System.out.println("\" \"\t\t" + blank.isEmpty() + "\t\t" + blank.isBlank());
System.out.println("\"Hello\"\t\t" + text.isEmpty() + "\t\t" + text.isBlank());
}
}String isEmpty() isBlank() "" true true " " false true "Hello" false false
Difference: isEmpty() returns true only for "" (length 0). isBlank() returns true for "" and strings containing only whitespace.
startsWith() and endsWith()
public class StartsEndsDemo {
public static void main(String[] args) {
String filename = "report_2024.pdf";
System.out.println("File: " + filename);
System.out.println("startsWith(\"report\"): " + filename.startsWith("report"));
System.out.println("endsWith(\".pdf\"): " + filename.endsWith(".pdf"));
System.out.println("endsWith(\".txt\"): " + filename.endsWith(".txt"));
// startsWith with offset
System.out.println("startsWith(\"2024\", 7): " + filename.startsWith("2024", 7));
}
}File: report_2024.pdf
startsWith("report"): true
endsWith(".pdf"): true
endsWith(".txt"): false
startsWith("2024", 7): trueFormatting
String.format()
public class FormatDemo {
public static void main(String[] args) {
// Basic formatting
String name = "Alice";
int age = 25;
double gpa = 3.85;
String formatted = String.format("Name: %s, Age: %d, GPA: %.2f", name, age, gpa);
System.out.println(formatted);
// Padding and alignment
System.out.println(String.format("|%-15s|", "left")); // Left-aligned
System.out.println(String.format("|%15s|", "right")); // Right-aligned
System.out.println(String.format("|%015d|", 42)); // Zero-padded
// Multiple formats
System.out.println(String.format("Hex: %x, Oct: %o, Sci: %e", 255, 255, 123456.789));
}
}Name: Alice, Age: 25, GPA: 3.85 |left | | right| |000000000000042| Hex: ff, Oct: 377, Sci: 1.234568e+05
Java 11+ Methods
repeat(int count)
public class RepeatDemo {
public static void main(String[] args) {
System.out.println("Ha".repeat(5));
System.out.println("-".repeat(30));
System.out.println("ABC ".repeat(3).trim());
}
}HaHaHaHaHa ------------------------------ ABC ABC ABC
concat() vs + Operator
public class ConcatDemo {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = " World";
// Using concat()
String r1 = s1.concat(s2);
System.out.println("concat: " + r1);
// Using + operator
String r2 = s1 + s2;
System.out.println("+ operator: " + r2);
// Difference: concat() throws NPE on null, + converts to "null"
String nullStr = null;
System.out.println("+ with null: " + s1 + nullStr); // "Hellonull"
// s1.concat(nullStr); // NullPointerException!
}
}concat: Hello World + operator: Hello World + with null: Hellonull
Common Mistakes
- Forgetting that methods return NEW strings — must assign the result
- Using split(".") without escaping — dot is regex, matches everything
- Off-by-one in substring — endIndex is exclusive
- NullPointerException — calling methods on null String
- Confusing replaceAll with replace — replaceAll uses regex
Best Practices
- Use isEmpty()/isBlank() instead of comparing with "" or checking length
- Use strip() over trim() for Unicode whitespace handling (Java 11+)
- Escape regex special characters in split/replaceAll:
.,|,\\, etc. - Use String.join() instead of manual loop concatenation
- Use StringBuilder for multiple concatenations in a loop
- Prefer equalsIgnoreCase() when case doesn't matter
- Use format() for complex string building with mixed types
- Check contains() before indexOf() for readability when you just need boolean
Interview Questions
Q1: What is the difference between replace() and replaceAll()? replace() takes literal CharSequence parameters. replaceAll() takes regex pattern as first argument.
Q2: What does split() return for an empty string? "".split(",") returns an array with one element: [""].
Q3: Is trim() and strip() the same? Both remove leading/trailing whitespace, but strip() (Java 11) handles Unicode whitespace characters that trim() misses.
Q4: What does charAt() throw for invalid index? StringIndexOutOfBoundsException.
Q5: How does substring() work internally? Since Java 7u6, substring creates a new char array (independent copy). Before that, it shared the original array with offset.
Q6: What is the return type of split()? String[] (array of Strings).
Q7: Can you chain String methods? Yes! Since each method returns a String: s.trim().toLowerCase().replace(" ", "_")
Q8: What does compareTo() return? Negative if first string is lexicographically less, 0 if equal, positive if greater. The value is the difference in char values at the first differing position.
Q9: What is String.valueOf()? Static method that converts any type to String: String.valueOf(42) → "42", String.valueOf(null) → "null".
Q10: How to check if a String contains only digits? Use str.matches("[0-9]+") or str.chars().allMatch(Character::isDigit).
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for String Methods.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, strings, string
Related Java Master Course Topics