×

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

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Java Wrapper Class

Wrapper class in Java encapsulates a primitive type within an object. In other words, it is a unique mechanism of Java to convert primitive type in to object and object into primitive type....

3 minutes read.

Convert JSON File to String in Java

Before understanding the conversion of JSON file to string, one must know about JSON. What is JSON? JSON stands for JavaScript Object Notation. It is an open standard format lightweight, text-based, and...

3 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Modules in Golang

Modules are a way to manage dependency versions and enable reproducible builds of Go programs. They were introduced in Go 1.11 and are now the recommended way to manage dependencies...

4 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

Java Integer valueOf() method

The valueOf() method of Java Integer class returns an Integer object holding the specified int value. The second method returns an Integer object holding the specified String value. The third syntax returns...

2 minutes read.

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.

Java Boolean logicalXor() Method

The logicalXor() method of Java Boolean class returns the result of implementing logical XOR operation on the specified Boolean operands. Syntax: public static boolean logicalXor (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

Array Slicing in Java

Array slicing is a method in Java for obtaining a subarray of a specified array. Assume a[] is an array. It contains eight items indexed from a[0] to a[7].a[] =...

3 minutes read.

Generic queue in Java

Before understanding how to implement a generic queue in java, one must know about generics and queue in java. Generics in Java Generics are parameterized types. The goal is to enable type...

6 minutes read.