String Methods

Su Suriya Ravichandran Updated 14 Nov 2026
6 min read ·Lesson 93 of 306

The String class provides more than sixty methods for examining and transforming text. This lesson is a guided tour of the ones used most often, grouped by purpose, with the rules that apply to all of them. Several groups (comparison, searching, replacing, splitting, formatting) have their own detailed lessons; here the goal is to know what exists and when to reach for it.

Two Rules That Apply to Every Method

1. Strings are immutable. No method changes the string it is called on. Methods that transform text return a new string, which you must store or use:

String name = "  ada  ";
name.strip();                      // result thrown away; name is unchanged
name = name.strip();               // correct: keep the result

2. Indexes are zero-based, and end indexes are exclusive. In substring(2, 5), the character at index 2 is included and the one at index 5 is not, so the result has 5 - 2 = 3 characters. Indexes outside 0–length() throw StringIndexOutOfBoundsException.

Because transforming methods return strings, they can be chained:

String cleaned = "  Hello, World!  ".strip().toLowerCase().replace("!", "");   // "hello, world"

Examining Characters and Size

MethodReturnsExampleResult
length()Number of char values"Java".length()4
charAt(i)The char at index i"Java".charAt(2)'v'
isEmpty()length() == 0"".isEmpty()true
isBlank()Empty or only whitespace (Java 11)" ".isBlank()true
toCharArray()A new char[] copy"ab".toCharArray()['a', 'b']
chars()IntStream of the characters"aab".chars().filter(c -> c == 'a').count()2
codePointAt(i), codePointCount(b, e)Unicode code pointsSee String Length

Changing Case

"Java".toUpperCase();      // "JAVA"
"Java".toLowerCase();      // "java"

Case conversion depends on the locale for a few languages. In Turkish, for example, "TITLE".toLowerCase() produces a dotless ı. For identifiers, keys, file extensions, and protocol values that are not shown to users, pass Locale.ROOT so the result is the same on every machine:

String ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase(Locale.ROOT);

There is no built-in "capitalize" method; combine substring with case conversion:

String word = "chennai";
String capitalized = word.substring(0, 1).toUpperCase() + word.substring(1);   // "Chennai"

Removing Whitespace

MethodRemoves
strip()Leading and trailing whitespace (Unicode-aware, Java 11)
stripLeading() / stripTrailing()One side only
trim()Leading and trailing characters with code ≤ U+0020 (older, ASCII-oriented)
String s = "  Hello, Java World  ";
System.out.println("[" + s.strip() + "]");      // [Hello, Java World]

Prefer strip() in new code. trim() does not remove Unicode whitespace such as the non-breaking space (U+00A0) or ideographic space (U+3000), which often arrive in text copied from web pages.

To remove all whitespace, including inside the string, use a regular expression: s.replaceAll("0s+", "").

Extracting Parts

String path = "reports/2026/november/sales.csv";

path.substring(8);                         // "2026/november/sales.csv"
path.substring(0, 7);                      // "reports"
path.substring(path.lastIndexOf('/') + 1); // "sales.csv"

substring combined with indexOf or lastIndexOf is the standard way to pull out a segment around a delimiter. split (its own lesson) breaks a string into all its parts at once.

Searching

MethodReturns
contains(s)true if s appears anywhere
startsWith(prefix), endsWith(suffix)Whether the string begins or ends with the text
indexOf(s) / indexOf(s, from)First position of s (optionally starting at from), or -1
lastIndexOf(s)Last position, or -1
matches(regex)Whether the whole string matches a regular expression
String s = "  Hello, Java World  ";
s.contains("Java");           // true
s.indexOf('o');               // 6
s.lastIndexOf('o');           // 15
s.strip().startsWith("Hello");   // true

All of these are case-sensitive. The String Search lesson covers them in depth.

Comparing

MethodPurpose
equals(other)Same characters, case-sensitive
equalsIgnoreCase(other)Same characters, ignoring case
compareTo(other)Ordering: negative, zero, or positive
compareToIgnoreCase(other)Ordering, ignoring case
contentEquals(CharSequence)Compare with a StringBuilder or other CharSequence
"Java".equalsIgnoreCase("JAVA");    // true
"java".compareTo("Java");           // 32: 'j' (106) minus 'J' (74)

Never compare string content with ==. The String Compare lesson explains why.

Replacing

MethodReplaces
replace(char, char)Every occurrence of a character
replace(CharSequence, CharSequence)Every occurrence of literal text
replaceAll(regex, replacement)Every match of a regular expression
replaceFirst(regex, replacement)The first match only
"banana".replace('a', 'o');             // "bonono"
"2026-11-11".replace("-", "/");         // "2026/11/11"
"a1b22c333".replaceAll("\\d+", "#");    // "a#b#c#"

replace with text is literal; replaceAll treats its first argument as a regular expression, so characters such as ., $, and + have special meanings there.

Splitting and Joining

"red,green,blue".split(",");                  // ["red", "green", "blue"]
"a,b,,c".split(",").length;                   // 4: the empty field between commas is kept
String.join("|", List.of("x", "y"));          // "x|y"
"line1\nline2".lines().count();               // 2

split takes a regular expression. lines() (Java 11) splits on any line terminator (\n, \r\n, or \r) and returns a stream.

Building and Formatting

MethodExampleResult
repeat(n) (Java 11)"ab".repeat(3)"ababab"
String.join(sep, parts)String.join("-", "2026", "11", "11")"2026-11-11"
String.format(fmt, args)String.format("%05.1f", 3.14159)"003.1"
formatted(args) (Java 15)"%d items".formatted(3)"3 items"
concat(s)"Java".concat("21")"Java21"
String.valueOf(x)String.valueOf(3.5)"3.5"

Other Useful Methods

MethodPurpose
indent(n) (Java 12)Add (or remove, if negative) n spaces at the start of each line
stripIndent() (Java 15)Remove common leading indentation from all lines
translateEscapes() (Java 15)Interpret escape sequences such as \n written as text
intern()The pooled instance of the string
getBytes(charset)Encode to bytes in a given character set
regionMatches(...)Compare a region of one string with a region of another

Practical Example: URL Slugs and Initials

Blogs and course platforms turn titles into URL-friendly "slugs," and user interfaces often show a person's initials in an avatar.

import java.text.Normalizer;
import java.util.List;

public class Slug {
    static String slugify(String title) {
        String s = Normalizer.normalize(title.strip(), Normalizer.Form.NFD)
                .replaceAll("\\p{M}", "")           // drop accents: é -> e
                .toLowerCase()
                .replaceAll("[^a-z0-9]+", "-")       // anything else becomes a hyphen
                .replaceAll("^-|-$", "");            // no leading or trailing hyphen
        return s.length() > 40 ? s.substring(0, 40).replaceAll("-$", "") : s;
    }

    static String initials(String fullName) {
        StringBuilder sb = new StringBuilder();
        for (String part : fullName.strip().split("\\s+")) {
            sb.append(Character.toUpperCase(part.charAt(0)));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        List<String> titles = List.of(
            "  Java Strings: The Complete Guide ",
            "Café & Crème — Résumé Tips!",
            "C++ vs. C# in 2026?",
            "Understanding Java's String.format(), String.join() and Text Blocks in Depth"
        );
        for (String t : titles) {
            System.out.println(slugify(t));
        }
        System.out.println(initials("  ada   king lovelace "));
    }
}

Output:

java-strings-the-complete-guide
cafe-creme-resume-tips
c-vs-c-in-2026
understanding-java-s-string-format-strin
AKL

slugify is a chain of string methods, each returning a new string for the next step:

  1. strip() removes outer whitespace.
  2. Normalizer.normalize(..., NFD) splits accented letters into a base letter plus a combining mark, and replaceAll("0p{M}", "") deletes the marks, turning é into e.
  3. toLowerCase() lowercases the text.
  4. replaceAll("[^a-z0-9]+", "-") turns every run of other characters (spaces, punctuation, symbols) into a single hyphen.
  5. A final replaceAll trims hyphens at either end.
  6. Long slugs are cut with substring, and any trailing hyphen left by the cut is removed.

The output also shows the limits of a simple approach. C++ and C# both become c, and the long title is cut mid-word. Real systems often keep a small table of special cases and cut at the last hyphen before the limit. initials uses split("0s+") to break the name on runs of whitespace (so extra spaces do no harm), then charAt(0) and Character.toUpperCase to build the result.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about String Methods and get answers drawn from it.

Signed-in readers only.