1. Introduction
The String class in java.lang provides a rich set of built-in methods for inspecting, comparing, transforming, and splitting text. Mastering these methods is essential for everyday Java programming and is a frequent source of interview and exam questions.
Cricket analogy: Virat Kohli's stats sheet has built-in tools—strike rate, average, boundary count—that every commentator relies on before a series, just as String's method toolkit is the first thing every Java programmer learns.
Since String is immutable, every method that appears to transform a string (like toUpperCase() or trim()) actually returns a brand-new String rather than modifying the original in place.
Cricket analogy: When the scorer changes a scorecard from "50" to "50*" after a not-out, they don't erase the old card—they issue a fresh one, mirroring how toUpperCase() hands back a brand-new String instead of altering the original.
2. Syntax
String s = " Hello World ";
int len = s.length();
char c = s.charAt(2);
String sub = s.substring(2, 7);
int idx = s.indexOf("World");
boolean eq = s.trim().equals("Hello World");
boolean eqIgnore = "JAVA".equalsIgnoreCase("java");
int cmp = "apple".compareTo("banana");
String[] parts = "a,b,c".split(",");
String trimmed = s.trim();
String upper = s.toUpperCase();
String lower = s.toLowerCase();
String cat = "foo".concat("bar");
String plus = "foo" + "bar";
String replaced = s.replace("World", "Java");3. Explanation
length() returns the character count. charAt(index) returns the single character at a zero-based index. substring(begin, end) returns characters from begin up to (but excluding) end; substring(begin) returns from begin to the end of the string. indexOf(str) returns the first index where str occurs, or -1 if not found.
Cricket analogy: Reading a Test scorecard is like these methods: length() is the total overs bowled, charAt(index) is the run scored on a specific ball, substring(begin,end) is extracting overs 10 to 20 of the innings, and indexOf() is finding when the first six was hit.
equals() compares content case-sensitively and returns a boolean; equalsIgnoreCase() does the same ignoring case. compareTo() returns a negative, zero, or positive int based on lexicographic (dictionary) order — useful for sorting. split(regex) breaks a string into an array using a regular expression delimiter. trim() removes leading/trailing whitespace. concat() and the + operator both join strings, but + is more commonly used and also handles non-string operands via implicit toString()/conversion.
Cricket analogy: Comparing MS Dhoni's finishing average to Kohli's chase average is like compareTo() ranking players lexicographically, while split(regex) is like separating an over-by-over commentary feed into individual deliveries.
replace(oldChar/oldString, newChar/newString) replaces ALL occurrences and returns a new String — it does not use regex (unlike replaceAll(), which does).
Exam trap: equals() checks content, while == checks reference. Also, substring(2, 7) is end-exclusive — it returns characters at indices 2,3,4,5,6, NOT including index 7. Off-by-one mistakes here are extremely common.
4. Example
public class StringMethodsDemo {
public static void main(String[] args) {
String s = " Hello World ";
System.out.println("length: " + s.trim().length());
System.out.println("charAt(1): " + s.trim().charAt(1));
System.out.println("substring(2,7): " + s.trim().substring(2, 7));
System.out.println("indexOf(World): " + s.trim().indexOf("World"));
System.out.println("equalsIgnoreCase: " + "JAVA".equalsIgnoreCase("java"));
System.out.println("compareTo: " + "apple".compareTo("banana"));
String[] parts = "a,b,c".split(",");
System.out.println("split length: " + parts.length);
System.out.println("upper: " + s.trim().toUpperCase());
System.out.println("replace: " + s.trim().replace("World", "Java"));
}
}5. Output
length: 11
charAt(1): e
substring(2,7): llo W
indexOf(World): 6
equalsIgnoreCase: true
compareTo: -1
split length: 3
upper: HELLO WORLD
replace: Hello Java6. Key Takeaways
- All String methods return new String objects; none modify the original string.
- substring(begin, end) is end-exclusive; substring(begin) goes to the end of the string.
- Use equals()/equalsIgnoreCase() for content comparison, never == on strings.
- compareTo() returns negative/zero/positive for lexicographic ordering, useful for sorting.
- split(regex) turns a delimited string into a String[]; trim() strips leading/trailing whitespace.
- replace() does simple literal replacement of all matches; replaceAll() uses regex.
Practice what you learned
1. What does "HelloWorld".substring(0, 5) return?
2. What is returned by "apple".compareTo("apple")?
3. Which method should be used to compare two strings while ignoring case differences?
4. What does "a,b,,c".split(",") produce (basic behavior)?
5. What does "foo".indexOf("z") return when the substring is not found?
Was this page helpful?
You May Also Like
Strings in Java
Understand Java's String class, its immutability, the string constant pool, and why == should never be used to compare string content.
StringBuilder and StringBuffer in Java
Compare Java's mutable string alternatives StringBuilder and StringBuffer, their key methods, and when to choose each for performance and thread safety.
Arrays in Java
Learn how Java arrays store fixed-size, homogeneous collections of elements on the heap, including declaration, default values, and common runtime errors.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics