Text in Java is stored in String objects. Strings are immutable: once created, a string’s characters cannot change, so a call such as toUpperCase() hands back a separate string. Java gives you dozens of methods for searching, cutting, comparing and transforming text, plus StringBuilder for building text efficiently. This lesson covers the ones you will use every day.
In this lesson you will learn
- The most useful
Stringmethods - How to compare strings correctly
- Why strings are immutable
- How to build text with
StringBuilder - Formatting with
String.format()and text blocks
Everyday String Methods
public class Main {
public static void main(String[] args) {
String s = " Core Tech ED ";
String t = s.trim();
System.out.println("[" + t + "] length " + t.length());
System.out.println(t.toUpperCase() + " | " + t.toLowerCase());
System.out.println(t.charAt(0) + " " + t.indexOf("Tech") + " " + t.substring(5, 9));
System.out.println(t.contains("ED") + " " + t.startsWith("Core"));
System.out.println(t.replace("ED", "Education"));
System.out.println(String.join("-", t.split(" ")));
System.out.println("java".equals("Java") + " " + "java".equalsIgnoreCase("Java"));
}
}
Output
[Core Tech ED] length 12
CORE TECH ED | core tech ed
C 5 Tech
true true
Core Tech Education
Core-Tech-ED
false true
trim()removes spaces at both ends;length()counts characters.charAt(0)reads one character;indexOf("Tech")finds a position (or -1 if missing).substring(5, 9)takes characters 5 to 8. The end index is not included.split(" ")breaks text into an array;String.join("-", parts)glues it back with a separator.equals()is case-sensitive;equalsIgnoreCase()is not.
Strings are immutable
t.toUpperCase() did not change t; it returned a new string. To keep a result, assign it: t = t.toUpperCase();
StringBuilder, format() and Text Blocks
public class Main {
public static void main(String[] args) {
String word = "level";
String reversed = new StringBuilder(word).reverse().toString();
System.out.println(word + " palindrome? " + word.equals(reversed));
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i);
if (i < 5) sb.append(",");
}
System.out.println(sb);
String report = String.format("%-8s|%6.2f|%03d", "Rafi", 92.456, 7);
System.out.println(report);
String text = """
Line one
Line two"""; // text block (Java 15+)
System.out.println(text.lines().count() + " lines");
}
}
Output
level palindrome? true
1,2,3,4,5
Rafi | 92.46|007
2 lines
StringBuilderis a mutable string. Useappend()in loops instead of+=, which would create a new string on every pass. It also hasreverse(), used here to check for a palindrome.String.format()uses format codes:%-8sleft-aligns a string in 8 characters,%6.2fprints a decimal with 2 places in 6 characters, and%03dpads an integer with zeros.- Text blocks (
""", Java 15+) write multi-line strings without\nescapes.
String Methods Reference
| Method | Returns |
|---|---|
length() | Number of characters |
charAt(i) | Character at index i |
indexOf(s) / lastIndexOf(s) | First / last position of s, or -1 |
substring(a, b) | Characters from a up to (not including) b |
contains(s), startsWith(s), endsWith(s) | boolean |
replace(a, b) | New string with every a replaced |
split(regex) | String[] |
isEmpty() / isBlank() | Empty / only whitespace |
compareTo(s) | Negative, 0 or positive for alphabetical order |
Common Mistakes
- Comparing with
==. It checks whether two variables point to the same object, not the same text. Useequals(). - Ignoring the return value of
trim(),replace()and similar methods. - Calling a method on
null, which throwsNullPointerException."yes".equals(input)is safe even ifinputis null. - Building long strings with
+in a loop. UseStringBuilder.
Practice Exercises
Exercise 1. Count the vowels in “Programming in Java”.
Show answer
String s = "Programming in Java".toLowerCase();
int count = 0;
for (char c : s.toCharArray()) {
if ("aeiou".indexOf(c) >= 0) count++;
}
System.out.println(count); // 6
Exercise 2. Turn “core tech ed” into “Core Tech Ed”.
Show answer
StringBuilder out = new StringBuilder();
for (String w : "core tech ed".split(" ")) {
out.append(Character.toUpperCase(w.charAt(0))).append(w.substring(1)).append(" ");
}
System.out.println(out.toString().trim());
Frequently Asked Questions
What is the difference between StringBuilder and StringBuffer?
They have the same methods. StringBuffer is synchronised for use by several threads, which makes it slower. Use StringBuilder unless you need thread safety.
Why are Java strings immutable?
Immutability makes strings safe to share between threads, lets Java reuse identical string literals from a pool, and makes them reliable keys in hash maps.
Summary
- Strings are immutable; methods return new strings.
- Compare text with
equals()orequalsIgnoreCase(). StringBuilderbuilds text efficiently in loops.String.format()and text blocks handle formatting and multi-line text.
Next: Java Methods.
