×

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

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

Java Math sin() Method

The sin() method of Java Math class returns the trigonometric sine of the specified angle. Syntax: public static double sin(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The sin() method...

1 minute read.

How to Convert String to enum in Java?

In this article, we shall gain the complete knowledge about how to convert the string to enum in Java. The complete process that happens in the approach shall be discussed...

3 minutes read.

Java Arrays

An array is an object that stores a collection of values. An array can store two types of collection data: objects and primitives. An array is a collection of values which...

2 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

How to Read CSV Files in Java?

Comma-Separated Values is the acronym for this format. It is a straightforward file format storing textual tabular data in a database or spreadsheet. The CSV files can be imported into...

3 minutes read.

How to Set Java_home in Linux

To set the Java_home in Linux, we must follow several steps to make us understand it easily.  Java follows the principle called WORA (write once run anywhere). We know that java...

3 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

Java String startsWith() method

Java String startsWith() method checks whether current String starts with given prefix or not . Syntax: public boolean startsWith(String prefix) public boolean startsWith(String prefix, int offset) Parameters: prefix : It is sequence of character Returns: It returns...

2 minutes read.

How to Convert Decimal to Hexadecimal in Java

How to Convert Decimal to Hexadecimal in Java The hexadecimal number uses 16 values to represent a number. Numbers from 0 to 9 represented by digits and the numbers from 10...

3 minutes read.

How to Concatenate Two Strings in Java

How to Concatenate Two Strings in Java Concatenation of two strings means adding the beginning of one string to the end of the other string. Some of the ways to concatenate...

3 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.

Generics in Java

Generics in Java Parameterizedtypes mean generic. Generics allow types (Character, Integer, String, …, etc., as well as user-defined types) to act as parameters to interfaces, classes, and methods. Generics in Java...

9 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

Program to find and replace characters on string in java

In JAVA, Strings are immutable. To overcome this Java String class contains a lot of methods to do operations on Strings. One such method is replace method. String Replace It returns a...

3 minutes read.

Object Definition in Java

In this article, you will be acknowledged about object in Java, its definition and how is this useful in writing the programs in Java. The comprehension of object-oriented technology depends on...

4 minutes read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

This Operator Using in Java

this keyword in Java has a wide range of applications. this reference variable in Programming language refers to the object of interest. This keyword is used in Java. this keyword is...

5 minutes read.

Duodecimal in Java

Duodecimal is a notation style in which a number with a base of 12 is referred to be a duodecimal number. In Java, we can use to convert duodecimal integers...

2 minutes read.