Substring in Java: Methods & Examples

In Java, string manipulation plays a significant role in many programming tasks, and the substring() method is one of the most commonly used tools for extracting parts of a string. Whether you're working on basic string operations or more complex text processing, understanding how to use substring() effectively is essential for mastering Java string methods.

This article will provide an overview of Java’s substring() method, with examples and explanations on how to use it for various string manipulations.

What is a Substring in Java?

Definition of a Substring

A substring in Java is a part of a string. The substring()method in Java allows you to extract a portion of a string by specifying the starting and ending positions of the desired segment.

Java provides two forms of the substring() method:

  • substring(int start) – Extracts a substring starting from the specified index to the end of the string.
  • substring(int start, int end) – Extracts a substring starting from the specified start index to the end index (excluding the character at the end index).

Java String Manipulation Overview

Java provides a wide array of string methods, and substring() is just one tool used for string manipulation. Other commonly used methods include:

  • charAt() – Retrieves a character at a specific index.
  • indexOf() – Finds the first occurrence of a substring.
  • length() – Returns the length of the string.
  • toLowerCase() and toUpperCase() – Converts a string to lowercase or uppercase.

Using the substring() Method in Java

Syntax of substring()

public String substring(int start)

This extracts a substring starting from the start index and continues to the end of the string.

public String substring(int start, int end)

This extracts a substring starting from the start index and ending just before the

end index.

Examples of substring() in Java

Example 1: Using substring(int start)

public class SubstringExample { public static void main(String[] args) { String str = "Hello, Java!"; String result = str.substring(7); System.out.println(result); // Output: Java! } }

Here, the substring starts at index 7 and goes to the end of the string. The result is "Java!".

Example 2: Using substring(int start, int end)

public class SubstringExample { public static void main(String[] args) { String str = "Hello, Java!"; String result = str.substring(0, 5); System.out.println(result); // Output: Hello } }

In this case, the substring starts at index 0 and ends just before index 5. The result is "Hello".

Java String Operations with substring()

Extracting Specific Parts of a String

You can use substring() to extract any part of a string by specifying the starting and ending indices. For example, if you want to extract a domain name from an email address:

public class SubstringExample { public static void main(String[] args) { String email = "user@example.com"; String domain = email.substring(email.indexOf('@') + 1); System.out.println(domain); // Output: example.com } }

In this case,  substring() extracts everything after the @ symbol, which is the domain name.

Removing a Prefix or Suffix from a String

If you want to remove a prefix or suffix from a string, substring() can be very handy. For example:

public class SubstringExample { public static void main(String[] args) { String filename = "report.txt"; String extension = filename.substring(filename.lastIndexOf('.') + 1); System.out.println(extension); // Output: txt } }

This example extracts the file extension by finding the last occurrence of the period (.) and using substring() to get everything after it.

Common Issues with substring()

  • IndexOutOfBoundsException: If the start or end index is out of bounds (negative or greater than the length of the string), you will encounter an exception.

    Example:

    String str = "Hello";
    System.out.println(str.substring(0, 10)); // Throws StringIndexOutOfBoundsException
  • Empty Strings: Calling substring() with start equal to end will return an empty string, which may be unexpected if not handled correctly.

    Example:

    public class SubstringExample { public static void main(String[] args) { String str = "Hello"; String emptyString = str.substring(2, 2); System.out.println("Empty String: '" + emptyString + "'"); // Output: '' } }

FAQs

How does the substring() method work in Java?

The substring() method extracts a part of a string from the original string. It takes one or two arguments:

  • One argument: extracts the string from the specified index to the end.
  • Two arguments: extracts the string from the start index to the end index (excluding the end index).

What is the difference between  substring(int start) and substring(int start, int end)?

  • substring(int start): Extracts a substring starting from the given index start to the end of the string.
  • substring(int start, int end): Extracts a substring starting from the start index and ending at the end index (excluding the end index).

Can I modify the original string using substring() in Java?

No, strings in Java are immutable. The substring() method does not modify the original string; instead, it returns a new string that represents the desired portion of the original string.

What happens if the start index is greater than the end index in substring(int start, int end)?

If the start index is greater than the end index, it will throw a StringIndexOutOfBoundsException. Always ensure that the start index is less than the end index.

Can I extract a substring using substring() without specifying an end index?

Yes, if you provide only the start index, the substring will be extracted from the start index to the end of the string.

line

Copyrights © 2024 letsupdateskills All rights reserved