To find all substrings of a string

Levels of difficulty: / perform operation:

Java program to find substrings of a string :- This program find all substrings of a string and the prints them. For example substrings of “fun” are :- “f”, “fu”, “fun”, “u”, “un” and “n”. substring method of String class is used to find substring. Java code to print substrings of a string is given below.

This java program

Java programing code
import java.util.Scanner;
class SubstringsOfAString
   public static void main(String args[])
      String string, sub;
      int i, c, length;
      Scanner in = new Scanner(;
      System.out.println("Enter a string to print it's all substrings");
      string  = in.nextLine();
      length = string.length();   
      System.out.println("Substrings of \""+string+"\" are :-");
      for( c = 0 ; c < length ; c++ )
         for( i = 1 ; i <= length - c ; i++ )
            sub = string.substring(c, c+i);

Output of program:

For a string of length n there will be (n(n+1))/2 non empty substrings and one more which is empty string. Empty string is considered to be substring of every string also known as NULL string.