Part 02 / Topic 4 of 9
Strings and their methods
A String is text between double quotes. Strings in Java are immutable: no method ever changes a string in place — each one returns a brand-new string.
String dish = "Masala Dosa";
System.out.println(dish.charAt(0)); // M, index starts at 0
System.out.println(dish.substring(7)); // Dosa (from index 7 to the end)
System.out.println(dish.substring(0, 6)); // Masala (end index excluded)
System.out.println(dish.replace("Masala", "Plain")); // a NEW string
Output (examples/04_string_basics.java):
Namaste, Pune!
Asha Kulkarni
ASHA KULKARNI
asha kulkarni
13
M
Dosa
Masala
7
true
Plain Dosa
true
true
true
true
hahaha
ravi
Ravi
true
false
true
| Method | What it does | Example | Result |
|---|---|---|---|
trim() |
removes spaces at both ends | " hi ".trim() |
"hi" |
length() |
number of characters | "chai".length() |
4 |
charAt(i) |
the character at index i |
"chai".charAt(0) |
'c' |
substring(i) / substring(i, j) |
a piece of the string | "chai".substring(1) |
"hai" |
indexOf(x) |
position of x, or -1 |
"chai".indexOf("a") |
1 |
contains(x) |
does it hold x? |
"chai".contains("ha") |
true |
replace(a, b) |
replaces every a with b |
"chai".replace("c", "C") |
"Chai" |
toUpperCase() / toLowerCase() |
changes case | "chai".toUpperCase() |
"CHAI" |
startsWith(x) / endsWith(x) |
does it start/end with x? |
"chai".startsWith("ch") |
true |
equalsIgnoreCase(x) |
equal, ignoring case | "UPI".equalsIgnoreCase("upi") |
true |
isEmpty() / isBlank() |
zero characters / only spaces | " ".isBlank() |
true |
repeat(n) |
repeats the string n times |
"ha".repeat(2) |
"haha" |
+ joins strings together (concatenation):
String greeting = "Namaste, " + "Pune" + "!"; // Namaste, Pune!
== vs. equals(): == on strings compares whether two names point to the same object, not whether the text is equal. Always use equals() (or equalsIgnoreCase()) to compare text.
String a = "chai";
String b = "chai";
String c = new String("chai");
System.out.println(a == b); // true: Java reuses one object for identical literals (the "string pool")
System.out.println(a == c); // false: new String() always makes a separate object
System.out.println(a.equals(c)); // true: equals() compares the characters, which is what you want
🔍 Going deeper: the "string pool" behaviour behind
a == bbeingtrueis a JVM implementation detail for saving memory, not a language rule you should rely on. Stage 2 coversStringBuilderfor building a string piece by piece efficiently; for now,+is fine for a handful of pieces.
Full program: examples/04_string_basics.java.
Done here? The practice set for Part 2 — including the solutions — is on the part page.