Strings & Text Blocks
Names, addresses, messages, file contents and web pages are all text, so you will use strings in almost every Java program. A String is a sequence of characters, written between double quotes: "Lucknow".
In this lesson you will learn the most useful String methods, the right way to compare strings (a classic interview question), how to format numbers neatly, how to build long strings efficiently with StringBuilder, and how to write multi-line text with text blocks.
Creating strings and calling methods
A String is an object, so it has methods: actions you call with a dot, such as name.length(). Characters are numbered from 0, so the first character is at index 0 and the last is at index length() - 1.
public class StringBasics {
public static void main(String[] args) {
String station = " Lucknow Charbagh ";
String name = station.strip();
System.out.println("[" + name + "]");
System.out.println(name.length());
System.out.println(name.toUpperCase());
System.out.println(name.charAt(0));
System.out.println(name.indexOf("Char"));
System.out.println(name.substring(8));
System.out.println(name.substring(0, 7));
System.out.println(name.contains("bagh"));
System.out.println(name.startsWith("Luck"));
System.out.println(name.replace("Charbagh", "Junction"));
System.out.println("-".repeat(20));
System.out.println(" ".isBlank());
}
}[Lucknow Charbagh] 16 LUCKNOW CHARBAGH L 8 Charbagh Lucknow true true Lucknow Junction -------------------- true
A few details worth remembering:
strip()removes spaces from both ends. (trim()is the older version;strip()also understands Unicode spaces.)indexOfreturns the position of the first match, or-1if there is none.substring(8)takes everything from index 8 to the end.substring(0, 7)takes indexes 0 to 6: the end index is not included.repeat,isBlankandstripwere added in Java 11, so very old tutorials do not mention them.
Strings are immutable
No String method changes the original string. name.toUpperCase() returns a new string and leaves name as it was. A string that cannot be changed is called immutable. If you want to keep the result, store it: name = name.toUpperCase();.
Comparing strings: equals, not ==
This is the most famous Java beginner trap. For objects such as strings, == checks whether two variables point to the same object in memory, not whether the text is the same. To compare the text, use equals.
public class Compare {
public static void main(String[] args) {
String a = "Kochi";
String b = new String("Kochi"); // a different object with the same text
String c = "kochi";
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(a.equals(c));
System.out.println(a.equalsIgnoreCase(c));
System.out.println("Aarav".compareTo("Meera") < 0);
String upper = a.toUpperCase();
System.out.println(a + " " + upper);
}
}false true false true true Kochi KOCHI
Sometimes == seems to work, because Java reuses identical string literals written in your code. But strings that come from user input, files or calculations are separate objects, so == fails exactly when it matters. Always use equals (or equalsIgnoreCase). compareTo compares alphabetically: a negative result means the first string comes earlier, which is how you sort names.
Splitting and joining
split cuts a string into an array of pieces at every separator. String.join does the opposite. You will learn arrays properly in Arrays; for now, parts[0] means "the first piece".
public class SplitJoin {
public static void main(String[] args) {
String line = "Priya,Rohtak,Science,91";
String[] parts = line.split(",");
System.out.println(parts[0] + " from " + parts[1] + " scored " + parts[3]);
String joined = String.join(" > ", "Delhi", "Jaipur", "Ajmer");
System.out.println(joined);
}
}Priya from Rohtak scored 91 Delhi > Jaipur > Ajmer
Formatting text and escape sequences
Joining values with + gets messy, especially with decimals. String.format builds a string from a template with placeholders: %s for any value as text, %d for whole numbers, %.2f for a decimal with two places, %,d for a number with thousands separators and %n for a new line. Since Java 15 you can also call .formatted(...) on the template itself, and System.out.printf formats and prints in one step.
Inside quotes, a backslash starts an escape sequence: \n is a new line, \t a tab, \" a double quote and \\ a backslash.
public class Format {
public static void main(String[] args) {
String item = "Cricket bat";
int qty = 2;
double price = 1499.5;
String line = String.format("%s x %d = Rs %.2f", item, qty, qty * price);
System.out.println(line);
System.out.println("%-12s|%6d|".formatted("Kabir", 87));
System.out.println("%-12s|%6d|".formatted("Ananya", 104));
System.out.printf("Total sales: Rs %,d%n", 1250000);
System.out.println("Line one\nLine two has a \"quoted\" word and a back\\slash.");
}
}Cricket bat x 2 = Rs 2999.00 Kabir | 87| Ananya | 104| Total sales: Rs 1,250,000 Line one Line two has a "quoted" word and a back\slash.
A number between % and the letter sets a minimum width: %6d right-aligns in 6 characters and %-12s left-aligns in 12, which is how you print neat tables. Note that %,d uses international grouping (1,250,000); Indian lakh grouping needs extra work with java.text classes.
Building strings with StringBuilder
Because strings are immutable, result = result + piece inside a loop creates a brand-new string every time. For a few joins that is fine, but in a loop that runs thousands of times it wastes memory and time. A StringBuilder is a mutable buffer: you append to it, then turn it into a string at the end.
public class Builder {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int table = 1; table <= 5; table++) {
sb.append(7 * table);
if (table < 5) {
sb.append(", ");
}
}
System.out.println(sb);
System.out.println(sb.reverse());
System.out.println(new StringBuilder("Isha").insert(0, "Dr. ").append(" Sharma"));
}
}7, 14, 21, 28, 35 53 ,82 ,12 ,41 ,7 Dr. Isha Sharma
The for loop (covered in Loops) appends the 7 times table. Unlike String methods, reverse and insert change the builder itself. You may meet StringBuffer in older code; it does the same job with extra locking for threads, which you almost never need.
Multi-line text with text blocks
Writing a receipt, an SQL query or a piece of JSON with \n and + is ugly. A text block, added in Java 15, starts with three double quotes and a line break, and ends with three double quotes. Everything in between is the text, line breaks included.
public class TextBlock {
public static void main(String[] args) {
String name = "Meera";
String receipt = """
Sharma Sweets, Jaipur
---------------------
Customer: %s
Kaju katli (0.5 kg) Rs 550
Total Rs 550
""".formatted(name);
System.out.print(receipt);
String json = """
{"city": "Pune", "pin": 411001}""";
System.out.println(json);
String oneLine = """
This is a long sentence that we \
split over two lines in the source.""";
System.out.println(oneLine);
}
}Sharma Sweets, Jaipur
---------------------
Customer: Meera
Kaju katli (0.5 kg) Rs 550
Total Rs 550
{"city": "Pune", "pin": 411001}
This is a long sentence that we split over two lines in the source.Java removes the common indentation, so you can indent the block to match your code. If the closing """ is on its own line, the text ends with a line break (that is why the receipt uses print, not println). Double quotes inside need no escaping, and a \ at the end of a line joins it to the next line.
Common mistakes
- Comparing with
==. Usea.equals(b). Put the known string first, as in"yes".equals(answer), so the code also works whenanswerisnull. - Forgetting immutability.
name.toUpperCase();on its own line does nothing useful. Writename = name.toUpperCase();. - Off-by-one in substring. The end index is excluded:
"Jaipur".substring(0, 3)is"Jai". - Index out of range.
"Pune".charAt(4)throwsStringIndexOutOfBoundsException, because the last index is 3. - Concatenating in a big loop. Use
StringBuilder.
Key points
- Strings are immutable objects; methods such as
toUpperCase,stripandreplacereturn new strings. - Indexes start at 0, and
substring(start, end)excludesend. - Compare text with
equalsorequalsIgnoreCase, never==. String.format,.formatted()andprintfuse placeholders such as%s,%d,%.2fand%,d.StringBuilderbuilds long strings efficiently.- Text blocks (
""", Java 15+) hold multi-line text without escapes.
Exercise
A booking system gives you the line " RAJDHANI EXPRESS|12951|Mumbai Central|New Delhi ". Write a program that strips the spaces, splits on the pipe character (use split("\\|"), because | has a special meaning in split patterns), and prints a formatted ticket header using a text block with formatted. The train name should appear in title case: Rajdhani Express.
Show solution
public class TicketHeader {
public static void main(String[] args) {
String raw = " RAJDHANI EXPRESS|12951|Mumbai Central|New Delhi ";
String[] parts = raw.strip().split("\\|");
String[] words = parts[0].toLowerCase().split(" ");
StringBuilder title = new StringBuilder();
for (String w : words) {
title.append(Character.toUpperCase(w.charAt(0)))
.append(w.substring(1))
.append(" ");
}
String header = """
Train : %s (%s)
From : %s
To : %s
""".formatted(title.toString().strip(), parts[1], parts[2], parts[3]);
System.out.print(header);
}
}Train : Rajdhani Express (12951) From : Mumbai Central To : New Delhi
The for (String w : words) loop visits each word; you will study it in the loops lesson. Character.toUpperCase capitalises the first letter and substring(1) keeps the rest.
Quick Quiz
1. What does "Jaipur".substring(1, 4) return?
Index 1 is a; the end index 4 is excluded, so you get indexes 1 to 3.
2. Which is the correct way to check whether city holds the text "Pune"?
equals compares text; == compares object references.
3. What does "%.2f".formatted(3.14159) produce?
%.2f formats a decimal number with exactly two digits after the point.
4. Why use StringBuilder when building a string inside a long loop?
StringBuilder is mutable, so appending does not create a new string every time.
Learn Java with a mentor
Free lessons get you started. Our Java, C & C++ Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
