Java String Methods You'll Actually Use (With Examples)
backend
7 min read
The Java String methods you'll reach for every single day, grouped by what they do and shown with real examples. No fluff, just the stuff you'll actually type.

Published By: Nelson Djalo | Date: April 7, 2026
If you write Java, you write Strings. They show up in every API response, every log line, every form field, every database row. The good news is the String class gives you a fat toolbox. The bad news is most tutorials dump 80 methods on you and call it a day. This post does the opposite - it walks through the String methods you'll actually reach for, grouped by what they do, with code you can paste into a main method right now.
These are the methods you use to ask basic questions about a String - how big is it, what's at position X, is it empty.
String name = "Amigoscode";
name.length(); // 10
name.charAt(0); // 'A'
name.charAt(9); // 'e'
name.isEmpty(); // false - length is not zero
"".isEmpty(); // true
" ".isEmpty(); // false - it has a space
" ".isBlank(); // true - isBlank treats whitespace as empty (Java 11+)
isBlank() is the one most people miss. If you're validating a form field, isEmpty() will let " " through. isBlank() will not. Use isBlank() for user input.
This is where new Java devs get burned. You do not compare Strings with ==. You use equals().
String a = "java";
String b = "java";
String c = new String("java");
a == b; // true (string pool trick - do not rely on it)
a == c; // false (different objects)
a.equals(c); // true (same content - this is what you want)
"Java".equalsIgnoreCase("JAVA"); // true
"apple".compareTo("banana"); // negative (apple comes first)
"banana".compareTo("apple"); // positive
"Amigoscode".startsWith("Amigo"); // true
"report.pdf".endsWith(".pdf"); // true
"hello world".contains("world"); // true
compareTo returns a negative number, zero, or a positive number depending on alphabetical order. It's what Collections.sort uses behind the scenes when you sort a List<String>.
When you need to find where something lives inside a String, indexOf and lastIndexOf are your friends.
String email = "nelson@amigoscode.com";
email.indexOf('@'); // 6
email.indexOf("amigo"); // 7
email.indexOf("xyz"); // -1 (not found)
email.lastIndexOf('.'); // 17 (the dot before "com")
A -1 return means "not in there". You'll see code like if (str.indexOf("foo") != -1) everywhere, but str.contains("foo") reads better - use that unless you need the actual position.
Heads up - Strings in Java are immutable. Every "modification" method returns a brand new String. The original is untouched.
String greeting = " Hello, World! ";
greeting.trim(); // "Hello, World!"
greeting.strip(); // "Hello, World!" (Java 11+, Unicode-aware)
greeting.toLowerCase(); // " hello, world! "
greeting.toUpperCase(); // " HELLO, WORLD! "
"Hello, World!".substring(7); // "World!"
"Hello, World!".substring(7, 12); // "World"
"banana".replace('a', 'o'); // "bonono"
"banana".replace("an", "X"); // "bXX"
strip() is the modern trim(). Use it. trim() only removes ASCII whitespace, while strip() understands all Unicode whitespace characters - which matters more than you'd think when users paste data from Word.
substring(start, end) is end-exclusive. So "Hello".substring(0, 3) gives you "Hel", not "Hell". Burn that into your brain.
These two are the workhorses for parsing CSVs, building queries, and formatting log lines.
String csv = "java,kotlin,scala,groovy";
String[] langs = csv.split(",");
// ["java", "kotlin", "scala", "groovy"]
String joined = String.join(" - ", langs);
// "java - kotlin - scala - groovy"
String formatted = String.format("Hello %s, you are %d years old", "Nelson", 33);
// "Hello Nelson, you are 33 years old"
split() takes a regex, not a plain string. So "1.2.3".split(".") gives you an empty array because . is the regex "any character". Use "1.2.3".split("\\.") instead. This trips up everyone exactly once.
If you're new to all this and want a structured walkthrough, the Java for Beginners course covers it from zero.
Sometimes you need to bounce between Strings and other types.
String number = "42";
int n = Integer.parseInt(number); // 42 as int
double d = Double.parseDouble("3.14"); // 3.14 as double
String back = String.valueOf(n); // "42"
String fromBool = String.valueOf(true);// "true"
char[] chars = "hello".toCharArray();
// ['h', 'e', 'l', 'l', 'o']
String.valueOf() is null-safe in a way that toString() is not. String.valueOf(null) returns "null", while someObject.toString() throws a NullPointerException if someObject is null. Small thing, saves real bugs.
Java 11 dropped a bunch of String methods that should have existed since day one.
"abc".repeat(3); // "abcabcabc"
"".isBlank(); // true
" ".isBlank(); // true
"hi".isBlank(); // false
"line1\nline2\nline3".lines().forEach(System.out::println);
// line1
// line2
// line3
repeat() is great for building separator lines in CLI tools or test fixtures. lines() returns a Stream<String> which plays nicely with everything in Java Streams Essentials.
Text blocks landed in Java 15. They make multiline Strings actually pleasant. The formatted() method on a text block is the cleanest way to template HTML, JSON, or SQL.
String json = """
{
"name": "%s",
"age": %d
}
""".formatted("Nelson", 33);
That's it. No more + "\n" + chains. If you're still on Java 8, this is one of many reasons to upgrade.
Three things bite Java devs over and over with Strings.
1. Using == instead of equals(). == compares object references. equals() compares content. With the string pool, == sometimes happens to work, which is worse than it never working - because then you ship a bug that only fails in production.
2. Forgetting Strings are immutable. This code does nothing useful:
String s = "hello";
s.toUpperCase(); // result is thrown away
System.out.println(s); // still "hello"
s = s.toUpperCase(); // this is what you wanted
System.out.println(s); // "HELLO"
3. Concatenating in a loop with +. Each + creates a new String object. In a tight loop this gets ugly fast. Use StringBuilder instead:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append("row ").append(i).append("\n");
}
String result = sb.toString();
For more on how Java treats objects under the hood, the 'this' Keyword in Java post is a quick read that connects nicely.
String methods are the kind of thing you stop thinking about once they're in your fingers. The same way you stop thinking about List.add() or Map.get(). They become reflex. The fastest path to that is writing real code - not memorizing the JavaDoc. If you want a structured path that takes you from these basics through to building APIs, check the Spring Boot Roadmap or jump straight into the Java Master Class.
Why are Java Strings immutable?
Mostly for safety and performance. Immutable Strings can be cached in the string pool, shared across threads without locks, and used as keys in HashMap without surprises. The tradeoff is that "modifying" a String always allocates a new one.
What's the difference between trim() and strip()?
trim() only removes characters with code point less than or equal to U+0020 (space). strip() uses Character.isWhitespace(), which understands all Unicode whitespace including non-breaking spaces. Use strip() on Java 11+.
When should I use StringBuilder instead of String?
When you're appending in a loop or building a String piece by piece. For one-off concatenation like "Hello, " + name, the compiler already turns it into a StringBuilder for you, so you do not need to optimize it.
Is String.format() slow?
It's slower than plain concatenation because it parses the format String at runtime. For a few calls a second it does not matter at all. For hot loops processing millions of records, prefer StringBuilder or pre-compiled MessageFormat.
How do I check if a String is null or empty in one shot?
Use str == null || str.isBlank(). Order matters - the null check has to come first or you'll NPE. Many projects also pull in Apache Commons Lang and use StringUtils.isBlank(str) which handles null for you.
Master these methods and you'll handle 95% of String work in Java without ever opening the docs. The rest you can look up when you need them. Want to build the muscle memory for real? Start with Java for Beginners and write code every day until this stuff feels boring.

Skip the generic recommendations. These 9 books changed how I write code, lead teams, and think about systems - from Clean Code to books most devs haven't heard of.

The exact skills, tools, and learning order to go from zero to hired as a Java full stack developer. Covers Spring Boot, React, databases, Docker, and what employers actually look for.

Abstract class or interface? Most Java devs get this wrong. Here's a clear breakdown with a side-by-side comparison table, code examples, and a simple decision rule.
Join thousands of developers mastering in-demand skills with Amigoscode. Try it free today.