Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud

Write a Java Program to Print All Substrings From a String?

A substring is a contiguous block of characters taken from a string, so to print every substring you walk two nested loops over the input: the outer loop fixes a start index and the inner loop fixes an end index, and you extract the slice with str.substring(i, j + 1). A string of length n produces exactly n*(n+1)/2 non-empty substrings, so the string abc yields six substrings: a, ab, abc, b, bc, and c.

Substring vs Subsequence: Know the Difference

Before writing the program, it helps to be precise about what you are generating, because substrings and subsequences are frequently confused in interviews.

  • Substring: a contiguous run of characters that preserves order with no gaps. For abc, the substrings include ab and bc, but not ac.
  • Subsequence: characters taken in their original order but not necessarily adjacent, so you may skip positions. For abc, ac is a valid subsequence even though it is not a substring.
  • Quick test: if you can lift the characters out as one unbroken slice of the original string, it is a substring; if you had to skip over characters to collect them, it is only a subsequence.

The Logic: Generating Every Substring

Every substring is uniquely identified by a start index and an end index. If you systematically pair each possible start with every valid end, you produce all of them without duplicates or omissions.

  • Read the string length n once, so you do not recompute it inside the loops.
  • Run an outer loop with start index i from 0 to n - 1.
  • Run an inner loop with end index j from i to n - 1, so the inner range never goes before the current start.
  • Extract each substring with str.substring(i, j + 1). The j + 1 is required because Java's substring end index is exclusive.
  • Print or collect the slice, then continue until both loops finish.

Java Program to Print All Substrings

The program below uses a hardcoded string so the output is deterministic and easy to verify. Swap in your own value or read input at runtime, shown further down.

public class AllSubstrings {
    public static void main(String[] args) {
        String str = "abc";
        int n = str.length();

        System.out.println("All substrings of \"" + str + "\":");
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                // substring(i, j + 1): end index is exclusive,
                // so j + 1 includes the character at index j
                System.out.println(str.substring(i, j + 1));
            }
        }

        int total = n * (n + 1) / 2;
        System.out.println("Total substrings: " + total);
    }
}

Running this program prints each substring on its own line, grouped by starting position:

All substrings of "abc":
a
ab
abc
b
bc
c
Total substrings: 6

How Many Substrings Does a String Have?

For a start index i there are n - i possible end positions, and summing that over every start gives n + (n - 1) + ... + 1, which equals n*(n+1)/2. The table below shows how the count grows with string length.

String length (n)CalculationSubstrings
11 * 2 / 21
22 * 3 / 23
33 * 4 / 26
44 * 5 / 210

Reading the String at Runtime

To work on user input instead of a fixed value, read a line with Scanner. The substring logic stays identical.

import java.util.Scanner;

public class AllSubstringsInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = sc.nextLine();
        int n = str.length();

        System.out.println("Substrings of \"" + str + "\" are:");
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                System.out.println(str.substring(i, j + 1));
            }
        }
        sc.close();
    }
}

For the typed input LTB, the program produces:

Enter a string: LTB
Substrings of "LTB" are:
L
LT
LTB
T
TB
B

Time and Space Complexity

  • Pair enumeration: the two nested loops generate O(n^2) start and end index pairs, one per substring.
  • Substring extraction: each substring() call copies up to n characters, and printing each slice also costs up to O(n), so the full program that materializes every substring runs in O(n^3) time.
  • Space: printing on the fly keeps extra space at O(n) for the current substring; storing every substring in a list instead pushes space to O(n^3).

Common Mistakes to Avoid

  • Forgetting the exclusive end index: calling str.substring(i, j) instead of str.substring(i, j + 1) drops the last character of every substring, because Java's end index is exclusive.
  • Confusing substrings with subsequences: if your output includes non-adjacent character groups like ac for abc, you have generated subsequences, which is a different problem.
  • Index out of range: letting the inner loop reach n with an inclusive end, or starting before 0, triggers a StringIndexOutOfBoundsException. Keep both indices within 0 and n.
  • Recomputing length: calling str.length() inside the loops is wasteful. Cache it once in a variable like n.

String utilities like this often sit inside larger applications, and the way they behave can shift across JDK versions and runtime environments. When that logic powers something user facing, you can validate the rendered result across browser and OS combinations using TestMu AI'sSelenium Automation grid so a fix verified on one setup behaves the same everywhere.

Frequently Asked Questions

What is the difference between a substring and a subsequence?

A substring is a contiguous block of characters, so the characters must be adjacent and in order. A subsequence keeps the original order but may skip characters and need not be contiguous. For abc, ab is a substring, while ac is a subsequence but not a substring.

How many substrings does a string of length n have?

A string of length n has n*(n+1)/2 non-empty substrings. A 3-character string like abc has 3*4/2 = 6 substrings, and a 4-character string has 4*5/2 = 10. Counting the empty string adds one more.

Why do you pass j + 1 to substring()?

Java's substring(beginIndex, endIndex) is begin-inclusive and end-exclusive, so it stops before endIndex. When j is the last character you want to keep, you pass j + 1 as the end index so the character at index j is included.

What is the time complexity of printing all substrings?

Enumerating start and end index pairs is O(n^2). Because each substring() call and print can cost up to O(n), the full program that materializes and prints every substring runs in O(n^3) time, with O(n) extra space when printing on the fly.

Is the empty string considered a substring?

Formally the empty string is a substring of every string, but programs that print all substrings usually list only the non-empty ones, which is why the standard count is n*(n+1)/2. The nested-loop approach here naturally skips the empty string.

Related Questions

Test Your Website on 3000+ Browsers

Get 100 minutes of automation test minutes FREE!!

Test Now...

KaneAI - Testing Assistant

World’s first AI-Native E2E testing agent.

...

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests