Introduction
In Java, the substring method is very useful. With the substring method we can take out a part of the text and print it. Suppose we need to write only four letters of the complete name then it is very useful for that purpose.
Substring ( )
When we need only a part of the complete text then we use the substring method. The substring method takes out the required text depending on the given instructions. The instructions can be provided to, for example, start from a specific position and then stop extracting the characters at a specific position of the string.
Various Examples of Substring method
Example 1
In this example, the substring method will take the text from the given string. It will start taking the characters from position one of the string and stop taking characters when three characters are taken.
- package demo99;
- import java.util.*;
- public class Demo99 {
- public static void main(String args[]) {
- String Name = "Raghu Ram Rathod";
- String NewName = "";
- NewName = Name.substring(1, 3);
- System.out.println(NewName);
- }
- }
Output

Example 2
In this example, the substring method will take the text from the given string. It will start taking the characters from position three of the string and stop at the end of the string.
package demo99;
- import java.util.*;
- public class Demo99 {
- public static void main(String args[]) {
- String Name = "Raghu Ram Rathod";
- String NewName = "";
- NewName = Name.substring(3);
- System.out.println(NewName);
- }
- }
Output

Example 3
In this example the substring method will start taking the characters from position two of the string and go to the complete string but stops when three characters remain. Suppose we have a string "computer" then it will start taking out characters from position two of the string. The total length of the string is eight characters and eight minus three equals to five. So it will start taking out characters from position two and stop at position five of the string.




Join the conversation! Your thoughts help the community grow.