Substring in Java

Substring in Java

March 30th, 2026
1694
05:00 Minutes

The Java Substring method is a technique that enables programmers to easily and accurately extract specific portions of a string. This technique can be used for a variety of applications, such as extracting a user's name from an email address, converting date strings into a readable form or cleaning up raw data, all of which are common tasks for programmers on a daily basis.

Developers can quickly obtain whatever they require from a string without changing its content simply by using an index-based access approach. Using this index based procedure to retrieve data from a string allows the developer to write more efficiently designed software than if he or she were to use other methods. Using these methods allows developers to build more flexible and manageable methods of processing their text data.

Learn what is substring and how this contiguous sequence of characters within a string (Java Class) is used to extract specific portions of text with this Java tutorial.

What is a Substring?

In Java, a substring means a contiguous sequence of characters within a given string. It allows developers to extract specific segments of text data based on defined starting and ending indices. The substring functionality enables a wide range of text processing tasks, which include data parsing, pattern matching and text manipulation.

For example:

public class Main {
    public static void main(String[] args) {
        String text = "Hello World";

        // Extract substring starting from index 6
        String result = text.substring(6);

        System.out.println(result);
    }
}

substring in java example

Syntax of the substring Method in Java

The following are the syntaxes of the substring method in Java, which help in extracting characters from a string in different ways:

String substring(int beginIndex)
  • This version returns the substring starting from beginIndex up to the end of the string.
  • The character at beginIndex is included in the result.
String substring(int beginIndex, int endIndex)
  • This version returns the substring from beginIndex to endIndex - 1.
  • The beginIndex is included, but the endIndex is excluded.

Note:

  • Indexing in Java strings starts from 0.
  • If the index values are out of range, Java throws a StringIndexOutOfBoundsException.
  • The original string is not modified: a new string is returned.

For example:

public class Main {
    public static void main(String[] args) {
        String text = "Programming";

        System.out.println(text.substring(3));      // Output: gramming
        System.out.println(text.substring(0, 6));   // Output: Progra
    }
}

substring in java example

Types of substring Methods

Java provides two types of substring() methods to extract parts of a string using indexes. Understanding these two variations helps in choosing the correct method for different string manipulation needs.

1. substring(int beginIndex)

This method returns part of a string starting from the given index to the end. It ignores all characters before the index and keeps everything after it.

public class Main {
    public static void main(String[] args) {
        String text = "Programming";
        String result = text.substring(3);
        System.out.println(result);
    }
}

substring in java example

Code explanation:

  • String text = "Programming"; stores the word
  • substring(3): starts from index 3
  • Index count: P(0) r(1) o(2) g(3)...
  • So it starts from g
  • Prints everything after: "gramming"

2. substring(int beginIndex, int endIndex)

This method returns part of a string between two indexes. It starts from beginIndex and stops before endIndex, meaning the character at endIndex is not included in result string.

public class Main {
    public static void main(String[] args) {
        String text = "Programming";
        String result = text.substring(0, 6);
        System.out.println(result);
    }
}

substring in java example

Code Explanation:

  • String text = "Programming"; : stores the word
  • substring(0, 6): start at index 0, stop before 6
  • Takes characters: P(0) r(1) o(2) g(3) r(4) a(5)
  • Stops before index 6: "Progra"
  • Prints "Progra"

Real World Applications of Java Substring

Substring is widely used in real-world applications to extract specific parts of text. It helps in tasks like parsing data, formatting strings and processing user input efficiently in Java programs. Following are some of its applications:

1. Extracting Usernames from Email

Substring is used to extract the username part of an email before the @ symbol. This is helpful in login systems, user identification or personalization features where only the name part is required instead of the full email address.

public class Main {
    public static void main(String[] args) {
        String email = "nehal@example.com";
        int index = email.indexOf("@");
        String username = email.substring(0, index);
        System.out.println("Username: " + username);
    }
}

substring in java example

2. Parsing File Names and Extensions

Substring helps separate file names and extensions (like .jpg, .txt). This is useful when organizing files, validating formats or processing uploads in applications where you need to treat file names and extensions differently.

public class Main {
    public static void main(String[] args) {
        String file = "document.pdf";
        int dotIndex = file.indexOf(".");
        String name = file.substring(0, dotIndex);
        String extension = file.substring(dotIndex + 1);
        System.out.println(name + " | " + extension);
    }
}


3. Processing Dates

Substring is used to extract parts of a date like day, month and year from a formatted string (e.g., dd-mm-yyyy). This is useful in applications that need to validate, display or convert date formats.

public class Main {
    public static void main(String[] args) {
        String date = "12-09-1994";
        
        String day = date.substring(0, 2);
        String month = date.substring(3, 5);
        String year = date.substring(6);
        
        System.out.println("Day: " + day);
        System.out.println("Month: " + month);
        System.out.println("Year: " + year);
    }
}

substring in java example

4. Extracting OTP or Codes

Substring can extract OTPs or verification codes from messages. This is commonly used in authentication systems where only a specific part of a message contains the important numeric code.

public class Main {
    public static void main(String[] args) {
        String message = "Your OTP is 567890";
        String otp = message.substring(12);
        System.out.println("OTP: " + otp);
    }
}

substring in java example

5. Game Development

In games, a substring can be used to extract commands, player inputs or codes (like “MOVE_LEFT” → “LEFT”). This helps process user actions or game logic based on string inputs.

public class Main {
    public static void main(String[] args) {
        String command = "MOVE_LEFT";
        String action = command.substring(5);
        System.out.println("Action: " + action);
    }
}


substring() vs slice(): Key Differences

Substrings and slices both extract parts of a string, but differ in index handling and behavior. Understanding these differences helps avoid errors and ensures correct string manipulation in programs.

Parameters substring() slice()
Negative Index Does not support negative values (treats them as 0). Supports negative values (counts from end).
Index Order Swaps indices if start > end. Does not swap, returns empty string.
Parameters Uses (start, end). Uses (start, end).
Use Case Simple substring extraction. Flexible slicing including from end.
Behavior More forgiving with inputs. More strict and predictable.

Common Mistakes When Using Substring in Java

Here are some common mistakes beginners and even experienced developers make while using substring() in Java:

1. Confusing endIndex as Inclusive: Many think the endIndex is included in the result, but it is exclusive.

String str = "Hello";
System.out.println(str.substring(0, 4));

In this, the character at index 4 is not included.

2. Index Out of Bounds Error: Using invalid indexes causes StringIndexOutOfBoundsException.

String str = "Java";
System.out.println(str.substring(0, 10)); // Error

The string length is 4, so index 10 is invalid.

3. Using Negative Indexes: Java does not allow negative indexes in substring().

String str = "Code";
System.out.println(str.substring(-1, 2)); // Error

Indexes must always be 0 or positive.

4. Forgetting String Immutability: substring() does not change the original string.

String str = "Hello";
str.substring(1, 4);
System.out.println(str);

You must store the result:

str = str.substring(1, 4);

5. Not Checking String Length Before Use: Using dynamic input without checking length can crash your program.

String str = "Hi";
System.out.println(str.substring(0, 5)); // Error

Fix this by:

if (str.length() >= 5) {
    System.out.println(str.substring(0, 5));
}

Best Practices for Using substring

Following best practices helps ensure your code is safe, efficient and easy to understand. By handling indexes carefully and considering edge cases, you can avoid common mistakes and write more reliable programs:

1. Always Validate Index Values: Before using a substring, make sure the indexes are within the string length. This helps prevent runtime errors like StringIndexOutOfBoundsException, especially when working with user input.

2. Remember, endIndex is Exclusive: The ending index is not included in the result. Keeping this in mind avoids logical mistakes and ensures you extract the correct portion of the string.

3. Store the Result Properly: Strings in Java are immutable, so substring() does not change the original string. Always store the result in a variable if you need to use the extracted part.

4. Use Dynamic Indexing: Instead of hardcoding index values, use methods like indexOf() or length() to find positions. This makes your code more flexible and easier to maintain.

5. Handle Edge Cases Carefully: Always consider cases like empty strings or very short inputs. Adding proper checks makes your program more reliable and prevents unexpected crashes.

Wrapping Up

In summary, the Java string class provides a number of methods for manipulating strings. Of the many different methods available, the substring() method is one of the most powerful because it allows you to extract particular parts of a string efficiently.

Substrings can be useful when working on actual problems such as parsing email addresses, processing date fields or extracting OTP from a string. To write safe code using substring(), developers should be aware of common mistakes (like using the wrong index start) and best practices (like using dynamic methods and validating index boundaries). By mastering substring(), developers will enhance their overall abilities related to Java programming and string handling.

FAQs

1. Can substring() modify the original string in Java?

No, substring() does not modify the original string. It returns a new string because Java strings are immutable, meaning their values cannot be changed once created.

2. Is the end index included in the substring()?

No, the end index is excluded in the substring(beginIndex, endIndex). The method returns characters starting from beginIndex up to one position before the endIndex.

3. What is the time complexity of substring() in Java?

The time complexity of substring() is generally O(n), where n is the length of the resulting substring, as it creates a new string from selected characters.

About the Author
Author Nehal Sharma
About the Author

Nehal Sharma is a skilled Data Analyst with expertise in Java, mobile development, and data analytics. She transforms complex data into actionable insights and has experience in business intelligence, data science, and Salesforce. She also simplifies technical concepts into clear, engaging content for learners and professionals.

Drop Us a Query
Fields marked * are mandatory
×

Your Shopping Cart


Your shopping cart is empty.