Introduction to Java substring
The substring() Java method returns a specified part of a given String in Java programming.
Syntax of Substring method-
public String substring(int startIndex)
public String substring(int startIndex, int endIndex)
For example-
If a variable called mystring
is “Hello” and we print mystring.substring(1,4)
.
public class SubStringDemo {
public static void main(String[] args) {
String mystring = "Hello";
System.out.println(mystring.substring(1,4));
}
}
We get “ell” as output.
ell
In Java, Strings are basically words with or without spaces or any special character. Say- “hi”, “Good Morning”, “@#__BLAH BLAH” … All are examples of String.
The Java.lang Package
offers some fundamental features to implement in our Java program.
The substring() is one such method defined for a String class.
In other words, If we want to use a part of the String we have, then we use the substring() method.
What does substring do in Java?
Before we dig in, we must understand the indexing of a String in Java. If you already know that, feel free to jump straight to Java substring examples.
An index number is used to identify every character in a Java String. For instance, The String “Hi There!” has 9 characters. Each character is assigned a number starting from zero(0). So the letter ‘H’ has index ‘0’, ‘i’ is ‘1’… so on.
Here is a Java code to understand better.
public class SubStringDemo {
public static void main(String[] args) {
String mystring = "Hi There!";
for(int i = 0; i<mystring.length(); i++) {
System.out.print(mystring.charAt(i)+" ");
}
System.out.println();
for(int i = 0; i<mystring.length(); i++) {
System.out.print(i+" ");
}
}
}
Output
H i T h e r e !
0 1 2 3 4 5 6 7 8
Notice That space is also assigned an index. We have also used the charAt() method from Java.lang.String
to print the character at provided index.
public char charAt(int index)
]
Java Substring Examples
Try to predict what the below code will generate as output?
public class SubStringDemo {
public static void main(String[] args) {
String mystring = "Hi There!";
System.out.println(mystring.substring(3));
}
}
Click to see the Output
There!
Great! if you were correct.
Do not worry if you missed it, when only a single parameter is passed to the substring method as input, then it is treated as the beginning index of the result sub-string.
In this case, the beginning index will be 3. The program simply returns a new String starting from the 4th character to the end of the given String.
Another Example
Well, now try to guess the output for this code.
public class SubStringDemo {
public static void main(String[] args) {
String mystring = "Hi There!";
System.out.println(mystring.substring(3,6));
}
}
Click to see the Output
The
Well, done if got it correct. In this program, the substring method is called with 2 parameters: start index and end index. The method simply returns the string from index 3 to 5, excluding 6. Keep a note on that one.
A Challenge for You!
Try to write a Java code to ask the user to input their name with proper spacing. Process the String and show first name and last name using the Java substring method. For example –
The input should be:
Letstacle Team
Your output should be:
First Name: Letstacle | Last Name: Team
Here’s the code for user input using the Scanner class.
import java.util.Scanner;
public class SubStringDemo {
public static void main(String[] args) {
String name = "";
Scanner sc = new Scanner(System.in); //create object of Scanner class
System.out.println("Enter Full Name: "); // ask user to enter name
name = sc.nextLine(); // store name
/************************
* write your code here *
************************/
sc.close();
}
}
I have complete faith if your read the article till here you can surely do this using what you learned just now. [hint: use lastIndexOf()
method to know the index of the last occurrence of a space].
Well, great if you tried.
Here's the code Solution for your help.
import java.util.Scanner;
public class SubStringDemo {
public static void main(String[] args) {
String name = "";
Scanner sc = new Scanner(System.in); //create object of Scanner class
System.out.println("Enter Full Name: "); // ask user to enter name
name = sc.nextLine(); // store name
name = name.trim(); // removes trailing white spaces from left and right ends of the string
int lastSpaceIndex = name.lastIndexOf(" "); // get the index of last last occurrence of space in the string
String firstName = name.substring(0,lastSpaceIndex); // All characters before the last space is first name
String lastName = name.substring(lastSpaceIndex+1); // All characters after the last space is last name
System.out.println("First Name: "+firstName+" | "+"Last Name: "+lastName);
sc.close();
}
}
Handling Exceptions with substring method Java
Though very useful we must be cautious in the use of the substring method. If we try to access indexes that do not exist in the String then the program will hit a java.lang.StringIndexOutOfBoundsException
.
Such erroneous situations are to be handled just like the way we handle any other exception in Java. Either using a throws declaration or using try-catch block.

String index out of range while using substring java
Using throws keyword
The Java throws
keyword is used to declare an exception.
It gives information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions.
But in this case, we have an unchecked exception, java.lang.StringIndexOutOfBoundsException
.
So, throws will not help much.

java.lang.StringIndexOutOfBoundsException
Using try-catch
On the other hand, using a try-catch block, we can specify what to be executed if an exception occurs.
So the exception gets handled without disrupting the program flow.
Code for try-catch if an exception occurs while using substring
import java.util.Scanner;
public class SubStringDemo {
static String mystring;
public static void main(String[] args){
try {
mystring = "Pot";
System.out.println(mystring.substring(4));
}catch(Exception e) {
System.out.println("GOTCHA! max accessible "
+ "index: "+(mystring.length()-1));
}
}
}
Output
GOTCHA! max accessible index: 2

try-catch for java substring, error handling
✌️ Hope you liked this article, Follow us on Facebook and Instagram. You can also subscribe to our newsletter.