top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Substring in Java

Introduction

Java uses a string method to create, modify, and otherwise work with input strings because strings are conceptualized as objects in Java. A series of characters encased in double quotes is referred to as a string in Java. A fragment of another string is referred to as a substring in Java.

This tutorial will explore what substring in Java means, its types, usage, workings, syntax, and examples.

Overview

A substring in Java is a string segment that may be obtained by calling the substring() function. A continuous sequence of characters from the original string can be used to construct a new string using this method, a built-in method of the String class in Java. The starting and ending sets of the chosen substring inside the original string are specified by one or two integer parameters sent to Java's substring() function.

The starting location of the substring is the sole argument needed in the first variant of the substring() function. It takes the substring and extracts it from the starting point of the string to the end at the specified place. The starting and ending locations of the substring must be specified as two parameters in the second variant of the substring() function. It takes the first parameter position as the start point and ends right before the second parameter position.

Remember that the substring() function creates a new string that includes the characters of the requested substring. No changes are made to the original string.

What is a Substring in Java?

A substring in Java is a section of a string that has been extracted using the substring function. It is a brand-new string with a continuous run of the characters from the first string. The requested substring's start and end indexes are the two arguments that the built-in substring method in Java requires. 

Let's look at an illustration to see how the substring() technique works. Let's say we want to extract the substring "everyone" from the text "Good morning everyone"

Example of Java substring() method

Here is an example Java application for the substring:

Using String.split() method

Here is an example Java application for the string.split():

Variants of substring 

  • String substring()

The substring() technique has two variations. Getting a substring from a string after a particular word in Java is returned by this method, which has two variations. The substring stretches from the character at the supplied index to the string's last character. 

In this example, a string str with the phrase "Good morning, everyone" is present. Using the substring technique, we take a substring() out of the original string.  In this scenario, the substring is "everyone" since we begin at position 13 (which is equivalent to the letter "E" in this case) and end at place 21 (which is equivalent to the letter "e" in this case).

  • String substring(begIndex, endIndex)

There are two variations of this function, which produces a new string that is a substring of the original string. The substring starts at the character at the given index and goes to the end of the string or up to endIndex - 1 if the second parameter is provided. 

This example contains a string with the phrase "This is an example" in it. We use the substring(begIndex, endIndex) method to separate a substring from the original text. The begIndex and endIndex arguments specify the starting and ending positions of the substring, respectively (inclusive and exclusive). If we start at position 10 (which is equivalent to the letter "E" in this case) and stop at position 18 (which is equivalent to the letter "e" in this case), the resulting substring will be "example."

Some Exception Handling and Corner Cases Programs in Java

Here are some other Java-based programs that handle exceptions and have corner cases:

Handling FileNotFoundException

When trying to access a file that doesn't exist or can't be accessed, a FileNotFoundException error message appears. Using a try-catch block, we can manage this exception. Here's an illustration:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileNotFoundExceptionExample {
public static void main(String[] args) {
File file = new File("file.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
    }
scanner.close();
 } catch (FileNotFoundException e) {
System.out.println("File not found!");
 }
 }
}

The file "file.txt" in this example is nonexistent. A FileNotFoundException is raised when we attempt to read the information inside of this file using the Scanner class. The message "File not found!" is printed when we handle this error using a try-catch block.

Handling ClassCastException

When we attempt to convert a class to a type incompatible with the object's real type, we see a ClassCastException. Using a try-catch block, we can cope with this exception. Here's an illustration:

public class ClassCastExceptionExample {
    public static void main(String[] args) {
        Object obj = "Hello World";
        try {
            Integer num = (Integer) obj;
            System.out.println(num);
        } catch (ClassCastException e) {
            System.out.println("Cannot cast to Integer!");
        }
    }
}

A ClassCastException will be raised when a string object, obj, is attempted to be converted to an integer type with the (Integer) operator. Try-catch blocks handle this error, and "Cannot cast to Integer!" is printed. 

Corner case with Integer division

Java's implementation of integer division generates an integer quotient and tosses the remainder. Corner situations like dividing by zero and overflow must be considered when performing division with an integer type. Here's an illustration:

public class IntegerDivisionExample {
    public static void main(String[] args) {
        int num1 = 2147483647; // maximum value of int
        int num2 = -1;
        try {
        int result = num1 / num2;
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero or integer overflow!");
        }
    }
}

In this example, we have two integers, num1, and num2, where num1 is the maximum value of int and num2 is -1. We try to perform the division of num1 by num2, which will result in an ArithmeticException due to integer overflow. We handle this exception using a try-catch block and print a message "Cannot divide by zero or integer overflow!". 

Methods to Get a Substring 

Java string methods are often used to take off a specific string section. This approach comes in two different forms:

Public String substring(int startIndex) 

This variation produces a new string that is a substring of the original text, beginning at the startIndex position supplied and continuing until the end of the original string.

In the above example, the substring begins at index 13 of the original string ("E") and contains all characters from there to the string's end.

Public String substring(int startIndex, int endIndex) 

This variation provides a new string that is a substring of the original content, starting at the startIndex position and going all the way to the endIndex position but not incorporating it.

The substring in the example above begins at index 0 ("G") and ends at index 12("g"). However, the character at index 12 is not a part of the substring. 

Internal Implementation of Substring Function in Java

To take a section of a specified string, use Java's substring() method. The function generates a new string that contains a segment of the original string, beginning at the provided index and ending at the specified index. This article will examine the Java substring() function's internal implementation. 

Syntax of Substring() Function 

public String substring(int startIndex) Example : System.out.println(" Substring starting from index 13: "+ s.substring(13));// Everyone

public String substring(int startIndex, int endIndex) Example : System.out.println(" Substring starting from index 0 to 12: "+ s.substring(0,12));// Good morning

StartIndex and endIndex are the two inputs for the substring() function. The substring's starting index is defined by the startIndex option. It defines the substring's ending index and is an optional argument called endIndex. If endIndex is left blank, the substring will begin at the startIndex index and go to the end of the main string.

Internal Implementation of Substring Function

Java's String class has an implementation of the substring() method. The Java Virtual Machine (JVM) produces a new string object and transfers the necessary characters from the old string object to the new string object when the substring() method is invoked on a string object.

The function only accepts the startIndex input in the first implementation. The startIndex is first verified as valid by the function. An exception called StringIndexOutOfBoundsException is issued if the startIndex is either larger than or equal to the length of the original string.

Use and Applications of Substring 

Numerous applications implement the Java substring methods.

1. Removing Prefixes or Suffixes: The Java approach uses the substring to eliminate prefixes and suffixes. For instance, here is an example showing how to extract the greeting from the provided text:

2. Parsing Strings: Here is an example of how to parse texts and extract particular elements or data using the substring methods. The example uses the substring technique to separate the year from a date original string.

3. Extracting Portions of Strings: Extracting particular sections of a string is one of substring()'s main purposes. For example, you could isolate a specific passage of a longer text or extract a person's initial name from their complete name. 

Explain the Variants of the Substring() Method 

The two substring() technique variations are:

  • String substring() - This variation produces a new string that is a substring of the original text, beginning at the startIndex position supplied and continuing until the end of the original string. 

  • String substring(startIndex, endIndex) -  This variation provides a new string that is a substring of the original content, starting at the startIndex position and going all the way to the endIndex position but not incorporating it.

Conclusion 

Understanding the substring() function is crucial for efficient string manipulation in various computer languages, including Java. Using its many versions, developers can extract substrings based on the precise beginning and ending indices or relative locations.

With the ability to remove the initial character, extract a specific range, or get substrings from the end of a string, the substring() function provides variety and flexibility in extracting parts of strings. Developers may improve their string handling abilities and successfully handle a variety of programming difficulties by understanding the principles and uses of the substring() technique.

FAQs 

1. How to find length of substring in Java? 

The substring stretches from the character at beginIndex to that at endIndex. Therefore, (endIndex - beginIndex) is the length of the substring.

2. What is a Substring in Javascript?

Substring is a built-in function in Javascript frequently used to return a portion of a given string so that smaller strings may be made out of the larger string. Because Javascript strings are immutable, the original string is preserved, and a new string is returned each time. It doesn't modify or manipulate the original string in any way. 

3. What is substring() in SQL?

In SQL, the substring function extracts characters from a given string. With this function, you can extract any quantity of substrings from a single text.

Leave a Reply

Your email address will not be published. Required fields are marked *