×

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 LDAP Authentication

WHAT IS LDAP? Clients can communicate with directory services by sending requests and receiving responses using the Lightweight Directory Access Protocol (LDAP). The term "LDAP server" refers to a directory service...

7 minutes read.

All the important string methods in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

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.

Java Numbers

We use primitive data types like byte, int, long, double, etc to work with the numbers, When we need objects, we use wrapper class like Integer, Double, Long, Byte, etc....

2 minutes read.

Count of Range Sum Problem in Java

In this article, we will discuss the basic approach or native approach used to count range sum problem in java. To solve this problem, we will check for numbers if they...

6 minutes read.

Types of Assignment Operators in Java

In this tutorial, we are going to study assignment operators and their types in Java language. Before proceeding to the types, let us know the term ‘assignment operator’.  The assignment...

5 minutes read.

Java String Interview Questions

Java String Interview Questions String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept....

16 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Class definition in Java

The class definition in Java Java is an object-oriented programming language. We essentially know that programming languages based on object-oriented paradigms have classes and objects in their concepts as main, which...

6 minutes read.

Java Implements Keyword

To understand about the keyword implements we need to learn about the concept of the interfaces and inheritance in java programming languages. So let us learn about the interface and...

3 minutes read.

Java Enhanced For Loop (For-each Loop)

JAVA ENHANCED FOR LOOP The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through...

4 minutes read.

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.

Star Program in Java

By solving the patterns, we can develop our coding skills and logical thinking. Mostly each pattern program uses two or more loops. Loops' number depends on the complexity of logic....

3 minutes read.

Switch Case Program in Java

Switch Case Program in Java The switch case program in Java controls which code snippet gets executed on the basis of the value of the expression mentioned in the switch statement....

22 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

Java Integer toHexString() method

The toHexString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 16. Syntax public static String toHexString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

List of Constants in Java

In this tutorial, we are going to deal with constants available in Java.Every programming language has its constants. Similarly, Javaalso has got constants of its own. In this tutorial, we will...

6 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.