1. A String is a sequence of characters
Like an array of char, a String has positions starting at 0:
text: J A V A 2 1 index: 0 1 2 3 4 5 6public class Main { public static void main(String[] args) { String s = "JAVA 21"; System.out.println(s.length()); // 7 (method, so brackets!) System.out.println(s.charAt(0)); // J System.out.println(s.charAt(s.length() - 1)); // 1 for (int i = 0; i < s.length(); i++) { System.out.print(s.charAt(i) + "-"); } }}2. The essential String methods
|
Method |
Returns |
Example with |
Result |
|---|---|---|---|
|
|
int |
|
11 |
|
|
char |
|
|
|
|
String from index a up to (not including) b |
|
|
|
|
String from a to the end |
|
|
|
|
first position of x, or -1 |
|
4 |
|
|
last position, or -1 |
|
7 |
|
|
boolean |
|
true |
|
|
boolean |
|
true |
|
|
String |
|
|
|
|
String without leading/trailing spaces |
|
|
|
|
String with every a replaced by b |
|
|
|
|
String array |
|
|
|
|
boolean |
|
true |
|
|
boolean |
|
false |
|
|
int: negative, 0 or positive (dictionary order) |
|
negative |
|
|
String |
|
|
Also useful: String.join("-", "a", "b", "c") gives "a-b-c", and String.valueOf(42) turns any value into text.
For individual characters, the Character tools help: Character.isDigit(c), Character.isLetter(c), Character.isUpperCase(c), Character.toUpperCase(c), Character.isWhitespace(c).
3. Immutability: Strings never change
A String object can never be modified after it's created. Every method that seems to change a String actually creates a new String.
public class Main { public static void main(String[] args) { String name = "riya"; name.toUpperCase(); // creates "RIYA", then throws it away System.out.println(name); // riya: unchanged! name = name.toUpperCase(); // store the new String back in the variable System.out.println(name); // RIYA }}4. The String pool, and why == fails
Because Strings never change, Java can safely share identical text. String literals (text written in quotes in code) are stored once in a special area called the String pool:
import java.util.Scanner;public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String a = "java"; String b = "java"; // reuses the same pooled object String c = new String("java"); // forces a brand-new object System.out.print("Type java: "); String d = sc.nextLine(); // text built at runtime: a new object System.out.println(a == b); // true: same object System.out.println(a == c); // false: different objects System.out.println(a == d); // false System.out.println(a.equals(c)); // true: same characters System.out.println(a.equals(d)); // true }}
== asks "are these the same object?" (do both arrows point to the same place?). .equals() asks "do these contain the same characters?" For text, you almost always want the second question.
5. StringBuilder: building text efficiently
Because Strings are immutable, this loop creates a new String object every round (10,000 of them):
String result = "";for (int i = 0; i < 10000; i++) { result = result + i; // each + makes a new String and copies all the old text}StringBuilder is a changeable text container built for this job:
public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); for (int i = 1; i <= 5; i++) { sb.append(i).append(", "); } sb.setLength(sb.length() - 2); // remove the last ", " System.out.println(sb); // 1, 2, 3, 4, 5 StringBuilder word = new StringBuilder("level"); System.out.println(word.reverse()); // level String finalText = sb.toString(); // convert back when needed }}Useful StringBuilder methods: append, insert(index, x), deleteCharAt(index), reverse(), setCharAt(index, c), toString().
Rule of thumb: a few + joins are fine. Joining inside a loop? Use StringBuilder.
6. Text blocks
For multi-line text, use triple quotes:
String menu = """ 1. Add student 2. List students 0. Exit """;System.out.print(menu);7. Worked problems
Reverse a String
static String reverse(String s) { StringBuilder sb = new StringBuilder(); for (int i = s.length() - 1; i >= 0; i--) { sb.append(s.charAt(i)); } return sb.toString(); // Shortcut: return new StringBuilder(s).reverse().toString();}Count vowels and consonants
static void countLetters(String s) { int vowels = 0, consonants = 0; for (char c : s.toLowerCase().toCharArray()) { if (Character.isLetter(c)) { if ("aeiou".indexOf(c) >= 0) vowels++; else consonants++; } } System.out.println("Vowels: " + vowels + ", consonants: " + consonants);}toCharArray() turns the String into a char[] so we can use for-each. "aeiou".indexOf(c) >= 0 is a neat way to check membership.
Anagram check ("listen" and "silent")
static boolean isAnagram(String a, String b) { char[] x = a.replace(" ", "").toLowerCase().toCharArray(); char[] y = b.replace(" ", "").toLowerCase().toCharArray(); Arrays.sort(x); Arrays.sort(y); return Arrays.equals(x, y);}Common mistakes
-
s.lengthinstead ofs.length()(and the opposite for arrays). -
Calling
toUpperCase(),replace()orstrip()without storing the result. -
Comparing text with
==. -
substring(2, 5)gives 3 characters (indexes 2, 3, 4), not 5. The end index is excluded. -
Calling methods on a String that is
null: this crashes withNullPointerException.
Interview questions
Why are Strings immutable in Java?
For security (values like file paths and credentials can't be changed after validation), thread safety, and to allow the String pool to share instances safely. It also allows caching the hash code, which makes Strings efficient as keys in hash-based collections.
What is the String pool?
A special area in the heap where string literals are stored once and shared. Two identical literals refer to the same pooled object. new String("x") always creates a new object outside the pool; intern() returns the pooled version.
What is the difference between String, StringBuilder and StringBuffer?
String is immutable. StringBuilder is mutable and fast but not thread-safe. StringBuffer is mutable and thread-safe (synchronised) but slower. Use StringBuilder unless several threads modify the same buffer.
How many objects does String s = new String("hello"); create?
Up to two: the literal "hello" in the pool (if it isn't already there) and a new String object on the heap that s refers to.
Practice
-
easy Check whether a word is a palindrome, ignoring case ("Madam").
-
easy Count the words in a sentence (watch out for multiple spaces:
split("\\s+")splits on one or more whitespace characters). -
easy Capitalise the first letter of every word: "java is fun" → "Java Is Fun".
-
medium Print the frequency of each character in a word (use an
int[26]array for lowercase letters). -
medium Remove duplicate characters, keeping the first occurrence: "programming" → "progamin".
-
medium Check whether one string is a rotation of another ("abcd" and "cdab"). Hint: look inside
a + a. -
hard Compress a string: "aaabbcccc" → "a3b2c4". Return the original if the compressed version isn't shorter.



Discussion