Strings, formatting and text blocks
Course contents (20 lessons)
- Getting started
- Installing JDK 21 and running Java code
- Your first program: how a Java file is built
- Language basics
- Variables and data types
- Strings, formatting and text blocks
- Control flow: if, switch expressions and loops
- Data and methods
- Arrays and the collections framework
- Methods, overloading and varargs
- Object-oriented Java
- Classes, objects and encapsulation
- Inheritance, abstract classes and interfaces
- Records, enums and sealed types
- Writing robust code
- Exceptions: checked, unchecked and try-with-resources
- Generics, bounded types and wildcards
- Files and the NIO.2 API
- Modern Java
- Lambdas and the Stream API
- Optional: handling missing values
- Concurrency: executors, CompletableFuture and virtual threads
- Tools, services and the final project
- Maven and Gradle basics
- Testing with JUnit 5
- A small REST service with the JDK HTTP server
- Final project: a library manager
Strings are objects
String is a class, not a primitive. A string literal is written between double quotes, and Java creates a String object for it. The most important property is that strings are immutable. Once created, a string never changes. Methods like toUpperCase return a new string and leave the original alone.
import java.util.List;
public class Main {
public static void main(String[] args) {
String raw = " Java Is Fun ";
// Methods return new strings
System.out.println(raw.trim()); // old way
System.out.println(raw.strip().toLowerCase());
System.out.println(raw.length());
System.out.println(raw.isBlank());
System.out.println("ab".repeat(3));
String email = "sara.khan@example.com";
int at = email.indexOf('@');
System.out.println(email.substring(0, at)); // sara.khan
System.out.println(email.substring(at + 1)); // example.com
System.out.println(email.contains("example"));
System.out.println(email.endsWith(".com"));
System.out.println(email.replace(".", "_"));
System.out.println(email.charAt(0));
// Splitting and joining
String[] parts = "red,green,blue".split(",");
System.out.println(parts.length);
System.out.println(String.join(" | ", parts));
System.out.println(String.join("-", List.of("a", "b", "c")));
// equals, not ==
String a = "java";
String b = new String("java");
System.out.println(a == b); // false: different objects
System.out.println(a.equals(b)); // true: same text
System.out.println("JAVA".equalsIgnoreCase(a));
// Building a string in a loop
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i);
if (i < 5) sb.append(", ");
}
System.out.println(sb);
System.out.println(sb.reverse());
// Formatting
String name = "Ayesha";
double price = 1234.5;
System.out.println(String.format("%s paid %,.2f rupees", name, price));
System.out.println("%-8s|%6d|%8.1f".formatted("item", 42, 3.14159));
// Text blocks (Java 15+)
String json = """
{
"name": "%s",
"active": true
}
""".formatted(name);
System.out.print(json);
}
}
Walking through it
The first block shows common methods. strip removes whitespace from both ends and understands all Unicode spaces, so prefer it over the older trim. isBlank is true for empty strings and strings made only of whitespace, which is a better check than isEmpty when you validate user input. repeat repeats a string.
The email example shows the standard way to take a string apart. indexOf returns the position of the first match, or -1 if there is none. substring(start, end) includes the start position and excludes the end. Positions start at zero. If the position is out of range, you get a StringIndexOutOfBoundsException, so check for -1 before you use the result.
split takes a regular expression, not just a plain character. That is fine for a comma, but for a character that has special meaning in regular expressions, such as a dot or a pipe, you must escape it: split("\\.").
equals versus ==
This is the first Java trap almost everyone falls into. For objects, == asks whether two variables point to the same object. equals asks whether they have the same content. In the example, new String("java") makes a separate object, so a == b is false although both hold the same text. Sometimes == on strings appears to work, because Java reuses identical literals, and that makes the bug hard to notice. Always compare strings with equals. If one side may be null, put the literal first, as in "yes".equals(answer), so that a null value does not cause an exception.
StringBuilder
Because strings are immutable, s = s + x in a loop creates a new string on every pass. For a few joins this is fine, and the compiler handles simple cases well. For loops with many iterations, use StringBuilder. You call append as often as you like, and toString at the end, which println does for you.
Formatting and text blocks
String.format and the instance method formatted use the same format codes as printf. %s is a string, %d a whole number, %f a decimal. Flags and widths refine them: %,.2f adds thousands separators and two decimals, %-8s pads a string to eight characters on the left side, %6d right-aligns a number in six characters. Be aware that decimal separators depend on the default locale of the machine. If you need a fixed output, pass Locale.ROOT or Locale.US as the first argument to String.format.
A text block starts and ends with three double quotes. The content begins on the line after the opening quotes. Java removes the common indentation, so you can indent the block to match your code and the output is not affected. You can use quotes inside without escaping them. Text blocks are ideal for JSON, SQL and HTML snippets.
Common mistakes
- Using
==to compare strings. - Ignoring the return value.
name.toUpperCase();on its own line does nothing useful. - Calling a method on null. A null string gives
NullPointerException. - Concatenating inside big loops instead of using
StringBuilder. - Splitting on a special character without escaping.
Try it yourself
- Write a method that checks whether a word is a palindrome, ignoring case.
- Given the string
"2026-03-15", print the year, month and day separately. - Print a three-row table of names and prices with aligned columns using
printf. - Write a small HTML snippet in a text block and print it.
import java.util.List;
public class Main {
public static void main(String[] args) {
String raw = " Java Is Fun ";
// Methods return new strings
System.out.println(raw.trim()); // old way
System.out.println(raw.strip().toLowerCase());
System.out.println(raw.length());
System.out.println(raw.isBlank());
System.out.println("ab".repeat(3));
String email = "sara.khan@example.com";
int at = email.indexOf('@');
System.out.println(email.substring(0, at)); // sara.khan
System.out.println(email.substring(at + 1)); // example.com
System.out.println(email.contains("example"));
System.out.println(email.endsWith(".com"));
System.out.println(email.replace(".", "_"));
System.out.println(email.charAt(0));
// Splitting and joining
String[] parts = "red,green,blue".split(",");
System.out.println(parts.length);
System.out.println(String.join(" | ", parts));
System.out.println(String.join("-", List.of("a", "b", "c")));
// equals, not ==
String a = "java";
String b = new String("java");
System.out.println(a == b); // false: different objects
System.out.println(a.equals(b)); // true: same text
System.out.println("JAVA".equalsIgnoreCase(a));
// Building a string in a loop
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i);
if (i < 5) sb.append(", ");
}
System.out.println(sb);
System.out.println(sb.reverse());
// Formatting
String name = "Ayesha";
double price = 1234.5;
System.out.println(String.format("%s paid %,.2f rupees", name, price));
System.out.println("%-8s|%6d|%8.1f".formatted("item", 42, 3.14159));
// Text blocks (Java 15+)
String json = """
{
"name": "%s",
"active": true
}
""".formatted(name);
System.out.print(json);
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account