Substring in Java

A part of string is called substring. In other words, substring is a subset of another string. In case of substring startIndex is inclusive and endIndex is exclusive.
You can get substring from the given string object by one of the two methods:
  • public String substring(int startIndex):
  • This method returns new String object containing the substring of the given string from specified startIndex (inclusive).
  • public String substring(int startIndex, int endIndex):
  • This method returns new String object containing the substring of the given string from specified startIndex to endIndex.
    In case of string:
  • startIndex: inclusive
  • endIndex: exclusive
  • Let's understand the startIndex and endIndex by the code given below.

    Code:

    String s="hello";  
    System.out.println(s.substring(0,2));  //he
    In the above substring, 0 points to h but 2 points to e (because end index is exclusive).

    Example of java substring

    Example:

    public class TestSubstring{  
    public static void main(String args[]){  
       String s="AmitabhBachchan";  
    System.out.println(s.substring(7)); //Bachchan  
    System.out.println(s.substring(0,7));  //Amitabh  
     }  
    } 
    

    Output:

     Bachchan
     Amitabh

    String compare by compareTo() method

    The String compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string.
    Suppose s1 and s2 are two string variables. If:
  • s1 == s2 :0
  • s1 > s2 :positive value
  • s1 < s2 :negative value
  • Example:

    class Examplestringcomparison3{  
    public static void main(String args[]){  
       String s1="Amit";  
       String s2="Amit";  
       String s3="Pritam";  
    System.out.println(s1.compareTo(s2));  //0  
    System.out.println(s1.compareTo(s3));  //1(because s1>s3)  
    System.out.println(s3.compareTo(s1));  //-1(because s3 < s1 )  
     }  
    }

    Output:

    0
    -15
    15