×

Java Substring

What is a substring in Java?

Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of a string. For example, if "JavaTpoint " is a string, then Java, T, etc... are substrings. It is a built-in method of string.

Before knowing about the substrings. Let's recall the strings in general.

String in Java

Strings can be divided into their individual characters. For example,

String name = "JavaTpoint";

Or

String name = new String("JavaTpoint");

It can be represented as,

JavaTpoint

0                   1             2             3             4            5             6              7                8        9

JavaTpoint is a string that is divided into individual characters, and we can access these characters through index numbers. Every character has an index associated with it. The indexing in the string starts from 0 and ends at (n-1), where n is the length of the string. So, if we want to look for "J" then we should look at 0, not 1. A string has many operations like length, concatenation, comparison, etc… And many methods like replace(), contain(), substring(), etc…

Let us understand string with a simple program,

StringExample.java

public class StringExample
{
public static void main(String args[])
{
String name = "JavaTpoint"; // creating a string without new keyword
String name1 = new String("JavaTpoint"); // creating a string with new keyword
System.out.println(name); // displaying the string
System.out.println(name1); // displaying the string
}
}

Output :

Substring in Java

Now let us come to our main topic which is substring,

substring() method in Java

The method substring() returns a String that is part of the original String. So, if I have “ HelloProgrammers “ as a string then, Programmers can be one of the substrings.

In order to get a substring from a given String, Java provides us with two methods. The two methods are :

1.  substring (int start index)

2. substring (int start index, int end index)

We can choose any one of the above methods to get the substring of a string. The important point to note here is start index is inclusive and the end index is exclusive.

For example,

Let us consider the string “ JavaTpoint “. If we want just Java to print, then we should give parameters to the substring method as substring(0,4).

Here the string in the substring is not capitalized. Most of the methods in Java are " Camel case " that is the second word is capitalized. But here in the substring method, all are in lowercase.

substring(int start index) :

This method in Java returns the substring from the given starting index till the end.

This method will throw an exception that is " IndexOutOfBound " when giving a start index larger than the length of the string.

Let us understand this method with the program.

StringExample1.java

public class StringExample1
{
public static void main(String args[])
{
String s = new String("JavaTpoint is my favourite website"); // declaring a string using // new keyword 
String ss = s.substring(5); // using substring method 
System.out.println(" The substring is " +ss); // displays the substring
}
}

Output :

Substring in Java

Here we have given the start index as 5. Since p is at the 5th index the substring starts from p.

public class StringExample2
{
public static void main(String args[])
{
String s = new String("JavaTpoint is my favourite website"); // declaring a string using // new keyword
String ss = s.substring(40); // using substring method
// run time error start index is larger than the length of the string
System.out.println(" The substring is " +ss); 
}
}

Output :

Substring in Java

Here we have given the start index as 40, length of the string is 34. Since 40 is greater than 34 that is given the start index is greater than the length of the string we have got the " IndexOutOfBound " exception.

substring(int start index, int end index)

This method in Java is used to get the substring of the desired length. This method also throws the exception " IndexOutOfBound " if the start index is less than 0 or greater than the end index or the end index is greater than the string length.

Let us understand this method using an example program

StringExample3.java

public class StringExample3
{
public static void main(String args[])
{
String s = new String("JavaTpoint is my favourite website"); // declaring string using // new keyword
String ss = s.substring(0,20); // using substring method
System.out.println(" The string is " +s); // displaying entire string
System.out.println(" The substring is " +ss); // displaying substring from 0 to 19th //index
}
}

Output :

Substring in Java

Here we wanted to get a substring of length 0 to 19. Since the end index is exclusive, we gave 20 as the end index.

StringExample4.java

public class StringExample4
{
public static void main(String args[])
{
String s = new String("JavaTpoint is my favourite website"); // declaring a string using // new keyword
String ss = s.substring(0,40); // using substring method
System.out.println(" The string is " +s); // displaying entire string
System.out.println(" The substring is " +ss); // runtime error
}
}

Output :

Substring in Java

Here end index is greater than the length of the string, so we got a run time error.

So, this is all about substring () method.


Related Topics

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Bubble Sort in Java

Bubble Sort in Java Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left...

5 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

How to create an array in Java

An array is a linear data structure stores a collection of fixed number ofelements of similar type. The size of an array is specified when it is created. The array...

14 minutes read.

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.

Java Thread Priority in Multithreading

As we realise, java, being object-situated, works inside a multithreading climate in which the string scheduler relegates the processor to a string in light of the need for a string....

6 minutes read.

Java SHA256

Definition: In cryptography, SHA is a hash function that takes 20 bytes of input and produces an approximate 40-digit hexadecimal integer as the hash result. Class for Message Digest: Java's MessageDigest Class,...

2 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

Camel Case in Java

Java names its classes, interfaces, methods, as well as variables using camel-case syntax. If the name consists of two words, the second word will always begin with a capital letter,...

3 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

What’s New in Java 15

Sealed classes are the new concept that was introduced by Java 15. Sealed classes are a preview feature. Most of the features which are released in java 15 are in...

3 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Deadlock in Java

Deadlock is when two or more processes wait for the state to do their tasks, but none of them can do so. It is a very common problem that one...

6 minutes read.

Multithreading in Java

Multithreading is a specialized form of multitasking. It is responsible for executing more than one task at a time of a single program, and each task is a separate thread. A program...

8 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.