String ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-10-16

String. Practical Tasks

The call text.replace("a", "o"); compiles and runs without errors, yet text stays the same: strings in Java are immutable, and the new string the method returns is simply thrown away. Slips like this are caught fastest by practice, and that is what the exercises below are for.

This page collects 13 Java string exercises with solutions — practice problems on the methods of the String class, building a string with StringBuilder, formatting with String.format() and printf(), and regular expressions with Pattern and Matcher. The exercises go from simple to combined: String methods first, then StringBuilder and formatting, then regex, and finally the word and palindrome problems that mix several topics. Most have a solution on Patreon, and some have a video walkthrough. If you need a refresher first, read StringBuilder and StringBuffer in Java, String Formatting in Java and Regular Expressions in Java.

String Methods Practice

  1. Write a method that takes any string as a parameter, for example “I like Java!!!”.
  2. Print the last character of the string. Use the String.charAt() method.
  3. Check whether your string ends with the substring “!!!”. Use the String.endsWith() method.
  4. Check whether your string starts with the substring “I like”. Use the String.startsWith() method.
  5. Check whether your string contains the substring “Java”. Use the String.contains() method.
  6. Find the position of the substring “Java” in the string “I like Java!!!” with String.indexOf().
  7. Replace every occurrence of the character a with o.
  8. Convert the string to upper case with String.toUpperCase().
  9. Convert the string to lower case with String.toLowerCase().

A detail that is easy to miss

The search in replace() is case-sensitive: replace("A", "o") finds no match in "I like Java!!!" and returns the string unchanged — with no error. And remember to assign or print the result: the method returns a new string and never changes the original.

Video walkthrough →Solution on Patreon →

Build a String with StringBuilder

  1. Given two numbers, for example 3 and 56, use StringBuilder.append() to build these strings:
    3 + 56 = 59
    3 - 56 = -53
    3 * 56 = 168
  2. Replace the “=” sign with the word “equals” (for example, 3 + 56 equals 59). Use StringBuilder.replace().

Hint

StringBuilder.replace(start, end, str) takes indexes, not the character to replace. Find the position of the sign with indexOf("=") and then call sb.replace(i, i + 1, "equals").

Video walkthrough →Solution on Patreon →

Replace Every Second Occurrence of a Phrase

Write a method that replaces every second occurrence of “object-oriented programming” in a string (ignoring case) with “OOP”. For example, the string

Object-oriented programming is a programming language model organized around objects rather than "actions" and data rather than logic. Object-oriented programming blabla. Object-oriented programming bla.

must be converted to

Object-oriented programming is a programming language model organized around objects rather than "actions" and data rather than logic. OOP blabla. Object-oriented programming bla.

How to approach it

Search for the occurrences in a loop with indexOf(phrase, from) on a lower-case copy of the string, and keep a counter: replace only the occurrences with an even number (the 2nd, 4th and so on). It is convenient to build the result in a StringBuilder, copying the pieces of the original string between the positions you found.

Solution on Patreon →

Find the Two Middle Characters of a String

Given a string of even length, return its two middle characters. For example:

  • "string" → "ri"
  • "code" → "od"
  • "Practice" → "ct"

Hint

For a string of length n, the middle characters are at indexes n / 2 - 1 and n / 2, so a single call s.substring(n / 2 - 1, n / 2 + 1) is enough — the character at the position of the second argument is not included in the result.

Solution on Patreon →

Student List with String.format()

Create a string using formatting: Student [surname] scored [grade] in [subject]. Write the formatting and the console output in a separate method that takes the surname, the grade and the subject name as parameters. Reserve 15 characters for the surname, 3 characters for the grade and 10 for the subject.

Example output:

Student Smith           scored 95  in Math
Student Brown           scored 87  in Physics
Student Johnson         scored 72  in Programming

A formatting detail

The width in %-15s is a minimum: a longer value is not cut off. “Programming” is 11 characters, so with %-10s it sticks out of the column. To cut it to 10 characters, add a precision: %-10.10s.

Video walkthrough →Solution on Patreon →

Employee Salary Report with Formatting

Employee Report · part 1 of 1

  1. Create an Employee class with the fields fullname and salary.
  2. Create an array that contains several objects of this type.
  3. Create a Report class with a static method generateReport(Employee[] employees) that prints the salary information of all employees.
  4. Use string formatting: right-align salary and print it with 2 digits after the decimal point. You can add something of your own.

Hint

The - flag aligns a value to the left, and without it the value is aligned to the right: %-20s%10.2f%n prints the name in a column 20 characters wide and the salary on the right in a column 10 characters wide with two digits after the decimal point.

Solution on Patreon →

Simple Regular Expression: cab, ccab, cccab

Change the regular expression in the example so that it matches the strings cab, ccab and cccab.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexDemo2 {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("a*b");
        Matcher matcher = pattern.matcher("aaab");
        boolean b = matcher.matches();
        System.out.println(b);
    }
}

For the strings cab, ccab and cccab the program must print true, and for ab it must print false.

Hint

The quantifier * means “zero or more”, and + means “one or more”. With c* the pattern would also accept the string ab, which has no c at all. More in the section Quantifiers: ?, *, +, {n,m}.

Video walkthrough →Solution on Patreon →

Regular Expression for a Domain Name

Change the regular expression in the example so that reference1.org is also considered a valid link.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexDemo3 {
    public static void main(String[] args) {
        System.out.println(test("google.com"));
        System.out.println(test("reference1.ua"));
        System.out.println(test("reference1.org"));
    }

    public static boolean test(String testString) {
        Pattern pattern = Pattern.compile(".+\\.(com|ua|ru)");
        Matcher matcher = pattern.matcher(testString);
        return matcher.matches();
    }
}

Right now the program prints true, true, false. Expected output after the change:

true
true
true

Where to look

The allowed domains are listed in a group of alternatives in parentheses, separated by the | character. The matches() method returns true only if the whole string ends with one of them. See Alternation (OR) and groups.

Video walkthrough →Solution on Patreon →

Find All "Java X" Versions with Regex

Given a string:

String text = "Versions: Java  5, Java 6, Java   7, Java 8, Java 12.";

Find all substrings of the form “Java X”, where X is a version number, and print them. There may be several spaces between the word Java and the number.

Expected output:

Java  5
Java 6
Java   7
Java 8
Java 12

Hint

The pattern "Java\\s+\\d+" will do: \s+ is one or more whitespace characters, and \d+ is one or more digits (with a single \d, Java 12 would be cut to Java 1). Loop over the matches with while (matcher.find()) and print matcher.group(). More in the section Character classes: \d, \s, \w and [ ] sets.

Video walkthrough →

Find the Word with the Fewest Distinct Characters

Find the word with the smallest number of distinct characters. A word may contain letters and digits. If there are several such words, find the first one. For example, in the string "fffff ab f 1234 jkjk" the word found must be "fffff".

How to count distinct characters

You can do it without collections: the character at position i appears for the first time if word.indexOf(word.charAt(i)) == i. The number of such positions is the number of distinct characters. To keep the first word when there is a tie, update the minimum only on a strict <.

Count the Words Made of Latin Letters Only

A sentence consists of several words separated by spaces, for example: "One two three one1 two2 123 naïve ". Find the number of words that contain only letters of the Latin alphabet (a–z and A–Z).

Expected result for the example: 3.

Pay attention

The word one1 does not qualify because it contains a digit, and naïve does not qualify because ï is not one of the letters a–z and A–Z. The easiest way to check a whole word is word.matches("[a-zA-Z]+"): matches() requires the whole string to match the pattern.

Find the Palindromes Among Numbers

A sentence consists of several words, for example: "If you have homework left, start with 1 unfinished assignment. 123 324 111 4554". Among the words that consist only of digits, find and print all palindromes — the words that read the same from left to right and from right to left.

Expected result for the example: 1, 111, 4554.

Hint

A word made of digits is checked with word.matches("\\d+"), and a palindrome is checked by comparing the word with its reversed copy: new StringBuilder(word).reverse().toString().equals(word). A one-digit number is also a palindrome. The reverse() method is described in the StringBuilder lesson.

Shopping Receipt with Formatting

Online Store · part 3 of 3 · ← part 2

When a customer makes a purchase, print a report of the purchased products to the console. Use formatting. For example:

Product        Price
--------------------
Jeans        1500.78
Skirt        1000.56
Tie           500.78
--------------------
Total:       3002.12

How to align the columns

Give the header and the rows the same width: "%-10s%10s%n" for the header and "%-10s%10.2f%n" for the products. Calculate the total in a loop over the purchased products instead of typing it in by hand — that way the program checks the arithmetic itself. If your computer uses a locale with a decimal comma, pass Locale.US as the first argument of String.format() to get a dot.

Solution on Patreon →

What to Review Before You Start

These exercises rely on four topics: String methods, StringBuilder, format specifiers and regex basics. The table shows which exercises use each topic and links to the lesson where the method you need is explained with an example.

Topic What you will need Exercises on this page
The String class and its methods charAt(), indexOf(), substring(), replace(), split() String Methods Practice, Two Middle Characters, Every Second Occurrence, Fewest Distinct Characters, Latin Words, Numeric Palindromes
StringBuffer and StringBuilder append(), replace(), reverse() Build a String with StringBuilder, Numeric Palindromes
String formatting Width, precision and the alignment flag: %-15s, %10.2f Student List, Employee Salary Report, Shopping Receipt
Regular expressions Quantifiers + and *, groups (a|b), matches() and find() Simple Regular Expression, Domain Name Regex, Java X Versions, Latin Words

Where String Solutions Usually Go Wrong

Most wrong solutions to string exercises come not from complicated algorithms but from five typical slips: comparing with ==, going past the last index, using matches() instead of find(), an unescaped dot in a regex, and the default locale in String.format(). Check your code against this table before you submit it.

What people write What happens The right way
s1 == s2 false for a string created with new String("Java") or read with scanner.nextLine(), even though the text is the same s1.equals(s2), or equalsIgnoreCase() to ignore case
s.charAt(s.length()) StringIndexOutOfBoundsException: the last index is length() - 1 s.charAt(s.length() - 1)
matcher.matches() to look for substrings false if the pattern does not cover the whole string A while (matcher.find()) loop and matcher.group() (matches() vs find())
Pattern.compile(".+.(com|org)") An unescaped dot means any character, so "googlexcom" also passes the check ".+\\.(com|org)": in a Java string literal the backslash is doubled
String.format("%.2f", 1500.78) On a machine with a German or French default locale you get 1500,78, with a comma String.format(Locale.US, "%.2f", x) always gives 1500.78 (Locale: dot or comma)

Before you submit a solution

Compare the program output with the example in the task and go through the code style checklist: meaningful variable names, a separate method for each action, and no duplicated code.

Frequently Asked Questions

Which of these exercises come up in Java interviews?

Palindrome checks, word counting, finding the middle characters and counting distinct characters are classic warm-up questions in Java interviews. On this page they are Find the Palindromes Among Numbers, Count the Words Made of Latin Letters Only, Find the Two Middle Characters and Find the Word with the Fewest Distinct Characters. Expect a follow-up: check a palindrome without StringBuilder.reverse(), using two indexes that move towards the middle, and explain why the solution runs in O(n).

How do I count the words in a string in Java?

Trim the spaces at the edges with trim() and split the string: text.trim().split("\\s+"). Without trim(), the string " a b" gives the array ["", "a", "b"] with an empty first element, and the empty string "" gives an array of length 1, not 0, so check that case separately with isEmpty().

Can I just concatenate with + in the StringBuilder exercise?

The result is the same, but the exercise trains append() and replace(). In a loop the difference is significant: the + operator creates a new String object on every iteration. More in the section String vs StringBuilder vs StringBuffer.

How do I check my solution if an exercise has no solution link?

Compare the output with the example in the task, then feed the program boundary data: an empty string, a one-character string and a string of spaces only. For example, in the exercise about the two middle characters, "".substring(-1, 1) throws a StringIndexOutOfBoundsException, so decide in advance what the method should return in that case.

How do I search for a substring ignoring case in Java?

Use Pattern.compile(word, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE) and find(): without the second flag, case is ignored only for ASCII letters (example in Pattern flags). Converting both strings with toLowerCase() and calling indexOf() works for most text, but for some Unicode characters the length of the string changes: "İ".toLowerCase() returns two characters, and the indexes in the original string shift.

Comments

Please log in or register to have a possibility to add comment.