java substring method

A piece of string is called java substring.  substring is a subset of another string. In the event of substring startIndex is inclusive and endIndex is exclusive.

Syntax-

public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)

In this instructional exercise I will discuss the java substring() method. Understand that the primary character of a string is situated at the 0 index. The substring() method is overloaded and has two unique signatures. The substring(int beginIndex) just returns every remaining character at and including the character at the predetermined index. For example:

String s = "9876543210";
String sub= s.substring(4);
System.out.println("sub= " + sub); // sub= 543210

The substring(int beginIndex, int endIndex) is a little more complicated this method returns new String object containing the substring of the given string from specified startIndex to endIndex. The first parameter educates the substring method to start returning characters at and including the character at the predetermined index. The second parameter trains the substring method to quit returning characters barring the character at the predefined index. For instance:

String s1 = "0987654321";
String sub1= s1.substring(4, 8);
System.out.println("sub1= " + sub1); // sub1= 7654

Program -

public class SubstringProgram{
 public static void main(String args[]){
 
   String s="JavaTechWorld";

   System.out.println(s.substring(4));//Tendulkar
   System.out.println(s.substring(0,4));//Sachin
 }
}

java substring

Leave a Comment