Java.lang.String class in Java | Set 2

Java.lang.String class in Java | Set 1
In this article we would be discussing different constructor and methods provided by java.lang.String. Strings in java are immutable.
Now lets discuss some of the methods provided by String class.
Methods:

  1. public int codePointAt(int index) – It takes as parameter a index which must be from 0 to length() – 1. ad returns a character unicode point of a index.
  2. public int codePointBefore(int index) – It takes as parameter a index which must be from 0 to length() – 1. and returns a unicode point of a character just before the index .
  3. public int codePointCount(int start_index, int end_index) – It takes as parameter start_index and end_index and returns the count of Unicode code points between the range.
  4. Lets see an example of the above methods:
    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java Program to demonstrate codePointAt
    // codePointBefore and codePointCount
    public class GFG_1 {
    public static void main(String[] args)
        {
      
            String s = "GeeksforGeeks";
      
            // codePointAt()
            System.out.print("Character (unicode point) at index 1 : "
                             + s.codePointAt(1) + "  ");
            System.out.println(s.codePointAt(5));
      
            // codePointBefore()
            System.out.print("Character (unicode point) before index 1 : "
                             + s.codePointBefore(1) + "  ");
            System.out.println(s.codePointBefore(7));
      
            // codePointCount()
            s = "G eek123 G**k";
            System.out.println("Character code point count : "
                               + s.codePointCount(0, 5));
        }
    }

    chevron_right

    
    

    Output:

    Character (unicode point) at index 1 : 101  102
    Character (unicode point) before index 1 : 71  111
    Character code point count : 5
    
  5. public CharSequence subSequence(int start_index, int end_index) – This method returns CharSequence which is a subsequence of the String on which this method is invoked.

    Note: It behaves similarly to subString(int start_index, int end_index), but subString() returns String while subSequence returns CharSequence.

  6. public boolean contains(CharSequence char_seq) – It returns true if the given CharSquence is present in the String on which its invoked.
  7. public boolean contentEquals(CharSequence char_seq) – It returns true only if the given CharSequence exactly matches the String on which its invoked
  8. Lets see an example of the above methods:
    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java Program to demonstrate subSequence
    // and contains and contentEquals
    public class GFG_2 {
    public static void main(String[] args)
        {
            String s = "geeksforgeeks";
      
            // subSequence()
            // contains "for"
            CharSequence cs = s.subSequence(5, 8);
      
            // contains "geeks"
            CharSequence cs1 = s.subSequence(0, 5);
      
            String s_1 = "geekforgeek";
      
            // contains()
            System.out.println("Reult of contains on s_1 "
                               + "with charSequence cs " + s_1.contains(cs));
            System.out.println("Reult of contains on s_1 "
                               + "with charSequence cs1 " + s_1.contains(cs1));
      
            // contentEqual()
      
            System.out.print("Result of contentEqual ");
            System.out.println("geeks".contentEquals(cs1));
      
            System.out.print("Result of contentEqual ");
            System.out.println("geeksfor".contentEquals(cs1));
        }
    }

    chevron_right

    
    

    Output:

    Reult of contains on s_1 with charSequence cs true
    Reult of contains on s_1 with charSequence cs1 false
    Result of contentEqual true
    Result of contentEqual false
    
  9. public boolean endsWith(String suf) – It takes in parameter a String suffix and return true if the String has same suffix.
  10. public boolean startsWith(String pre) – It takes in parameter a String prefix and returns true if the String has a same prefix
  11. Lets see an example of the above methods:
    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java Program to demonstrate endsWith
    // and startWith
    public class GFG_3 {
    public static void main(String[] args)
        {
      
            String s = "geeksforgeeks";
      
            // endsWith
            String ends_1 = "geeks";
            String ends_2 = "eks";
            String ends_3 = "for";
      
            System.out.println(s + "end with " + ends_1 + " " + s.endsWith(ends_1));
            System.out.println(s + "end with " + ends_2 + " " + s.endsWith(ends_2));
            System.out.println(s + "end with " + ends_3 + " " + s.endsWith(ends_3));
      
            // startWith
            String start_1 = "geeks";
            String start_2 = "for";
      
            System.out.println(s + " starts with " + start_1
                               + "  " + s.startsWith(start_1));
            System.out.println(s + " starts with " + start_2
                               + "  " + s.startsWith(start_2));
        }
    }

    chevron_right

    
    

    Output:

    geeksforgeeksend with geeks true
    geeksforgeeksend with eks true
    geeksforgeeksend with for false
    geeksforgeeks starts with geeks  true
    geeksforgeeks starts with for  false
    
  12. public void getChars(int start, int end, char[] destination, int destination_start) : It takes in four parameters, start and end refers to the range which is to copied to the character array, destination is the character array to be copied to, and destination_start is the starting location of the destination array.
  13. public char[] toCharArray() – It coverts the entire String to the character array.

    Note :- getChars provide more flexibility when, a range of characters is to be copied to an exiting array or a new array while toCharArray converts the entire string to a new character array.

  14. Lets see an example of the above methods:
    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java Program to demonstrate getChars
    // and toCharArray
    public class GFG_4 {
    public static void main(String args[])
        {
            String s = "geeksforgeeks";
      
            // toCharArray
            char[] arr;
            arr = s.toCharArray();
            System.out.println("String toCharArray: ");
            for (char i : arr)
                System.out.print(i + " ");
      
            // getChars
            s.getChars(5, 8, arr, 0);
            System.out.println("\nSubString to existing "
                               + "char array");
            for (char i : arr)
                System.out.print(i + " ");
        }
    }

    chevron_right

    
    

    Output:

    String toCharArray: 
    g e e k s f o r g e e k s 
    SubString to existing char array
    f o r k s f o r g e e k s 
    
  15. public int hashCode() – It returns hashcode of the given String. There is predefined formula to compute the hashcode of the String:
    s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
    where,
    n - is the length of the String
    i - is the ith character of the string
    
  16. public String intern() – It returns the canonical form of the String object on which it is invoked.
    ” When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. ” – Java String Documentation.
  17. Lets see an example of the above method:-
    To understand the example better refer to Initialize and compare String
    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java program to demostrate
    // hashCode and intern
    class GFG_5 {
    public static void main(String[] args)
        {
      
            // hashCode
            String s = "geeks";
            System.out.println("Hashcode of String s is "
                               + s.hashCode());
      
            // intern()
            String s_1 = "geeks";
            String s_2 = new String("geeks");
            String s_3 = s_2.intern();
      
            // returns true
            System.out.println(s_1 == s_2);
      
            // returns false
            System.out.println(s_1 == s_3);
        }
    }

    chevron_right

    
    

    Output:

    Hashcode of String s is 98232047
    false
    true
    
  18. public boolean isEmpty() – It returns true if the length of the String is 0.
  19. public static String format(String f, Object… arguments) – Returns the formatted String according to the format specifier f, the arguments should exactly equal to the number of format specifier used .
    Variation:
    public static String format(Locale l, String f, Object… arguments)– Returns the formatted String as per Locale used.
  20. Lets see an example of the above methods:
    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import java.util.Locale;
    // Java program to demostrate
    // isEmpty and format
    class GFG_6 {
    public static void main(String[] args)
        {
      
            String s = "geeksforgeeks";
      
            // format()
            String s1 = String.format("%s : %d", s, 10);
            System.out.println(s1);
      
            String s2 = String.format("%s = %f ",
                                      "Value of PI is", Math.PI);
            System.out.println(s2);
      
            // format() with locale
            // we are using the default locale here
      
            String s3 = String.format(Locale.getDefault(),
                                      "%s : %d", s, 10);
            System.out.println(s3);
      
            // isEmpty
            String s4 = "";
            System.out.println("is String s empty "
                               + s.isEmpty());
      
            System.out.println("is String s4 empty? "
                               + s4.isEmpty());
        }
    }

    chevron_right

    
    

    Output:

    geeksforgeeks : 10
    Value of PI is = 3.141593 
    geeksforgeeks : 10
    is String s empty false
    is String s4 empty? true
    
  21. public boolean matches(String reg_exp) – It returns true if the string matches the regular expression( reg_exp).
  22. public boolean regionMatches(int start_OString, String another, int start_AString, int no_of_char) – It returns true if the region of original string staring with index start_OString matches with the region of another string starting with string_AString, and no_of_char refers to the number of character to be compared.

    Variation :
    public boolean regionMatches(boolean ignore_case, int start_OString, String another, int start_AString, int no_of_char) – This variation of a method provide flexibility when we want to ignore the case while comparing substring. If the first parameter i.e. ignore_case is true it neglects the case and compares but if it is false it behaves similarly as the first version of the method without ignore_case

  23. Lets see an example of the above methods:
    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java Program to demonstrate
    // matches and regionMatches
    class GFG_7 {
    public static void main(String[] args)
        {
            String s = "geeksforGeeks";
      
            // matches
            System.out.println("Matches 1 :"
                               + s.matches("(.*)Geeks"));
            System.out.println("Matches 2 :"
                               + s.matches("(.*)for(.*)"));
            System.out.println("Matches 3 :"
                               + s.matches("geeksfor"));
      
            // regionMatches(int, String, int, int)
      
            String s2 = "Geeksforgeeks";
      
            System.out.println("RegionMatches 1 :" + s.regionMatches(5, s2, 5, 3));
            System.out.println("RegionMatches 2 :" + s.regionMatches(5, s2, 6, 3));
      
            // regionMatches(boolean, int, String, int, int)
            // ignore the case while comparing
            System.out.println("Region Matches 3 :" + s.regionMatches(true, 0, s2, 0, 3));
      
            // consider the case while comparing
            System.out.println("Region Matches 3 :" + s.regionMatches(false, 0, s2, 0, 3));
        }
    }

    chevron_right

    
    

    Output:

    Matches 1 :true
    Matches 2 :true
    Matches 3 :false
    RegionMatches 1 :true
    RegionMatches 2 :false
    Region Matches 3 :true
    Region Matches 3 :false
    
  24. public String[] split(String reg_exp) – It splits the string around the regular expression and returns a String array.

    Variation :
    public String[] split(String reg_exp, int limit) – It splits the string around the regular expression and limit refers to the number of times the reg_exp is applied and it is the length of the resulting array and reg_exp is n is applied only length – 1 times.

  25. Lets see an example of the above methods:
    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java Program to demonstrate
    // split
    class GFG_8 {
    public static void main(String[] args)
        {
            String s = "Geeks for Geeks";
      
            // split
            System.out.println("Spliting the string a"
                               + "round spaces");
            String[] geek_arr = s.split("\\s+");
            for (String i : geek_arr)
                System.out.println(i);
      
            System.out.println("\nSpliting the string around the spaces"
                               + "\nbut controlling the length of resulting array :");
            String s_1 = "Geeks for Geeks Geeks for Geeks";
            String[] geek_arr1 = s_1.split("\\s+", 2);
            for (String i : geek_arr1)
                System.out.println(i);
      
            System.out.println("\nSpliting the string around the spaces"
                               + "\nbut controlling the length of resulting array :");
            geek_arr1 = s_1.split("\\s+", 4);
            for (String i : geek_arr1)
                System.out.println(i);
        }
    }

    chevron_right

    
    

    Output:

    Spliting the string around spaces
    Geeks
    for
    Geeks
    
    Spliting the string around the spaces
    but controlling the length of resultng array :
    Geeks
    for Geeks Geeks for Geeks
    
    Spliting the string around the spaces
    but controlling the length of resultng array :
    Geeks
    for
    Geeks
    Geeks for Geeks
    
  26. public static String join(CharSequence de_limiter, CharSequence… elements) – It returns a string which contains all the elements joins by the de_limiter.

    Variation:
    public static String join(CharSequence de_limiter, Iterable elements) – It performs the same function but the second parameter is Iterable which makes it flexible to work with different collection classes.

  27. Lets see an example of the above methods:
    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java Program to demonstrate
    // join
    import java.util.LinkedList;
    class GFG_9 {
    public static void main(String[] args)
        {
            // join()
            System.out.print("Example of join 1 : ");
            System.out.println(
                String.join(", ", "Geeks", "for", "Geeks"));
      
            System.out.print("Example of join 2 : ");
            LinkedList<String> ll = new LinkedList<String>();
            ll.add("browsing");
            ll.add("geeks");
            ll.add("for");
            ll.add("geeks");
            ll.add("is");
            ll.add("fun");
            System.out.println(String.join("-a-", ll));
        }
    }

    chevron_right

    
    

    Output:

    Example of join 1 : Geeks, for, Geeks
    Example of join 2 : browsing-a-geeks-a-for-a-geeks-a-is-a-fun
    
  28. public String replaceAll(String reg_exp, String replacement) – It replaces all the Substring of the original string that matches the reg_exp with replacement and returns the modified String.
  29. public String replaceFirst(String reg_exp, String replacement) – It replaces the first occurrence of the reg-exp in the original string with the replacement and returns the modified String.
    Note :- replaceAll and replaceFirst does’nt changes the original String rather it creates a new string with modification.
  30. Lets see an example of the above methods:
    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java Program to demonstrate
    // replaceAll and replaceFirst
    class GFG_10 {
    public static void main(String[] args)
        {
            String s = "GeeksforGeeks";
            ;
      
            // replaceAll()
            String s1 = s.replaceAll("Geeks", "Quiks");
            System.out.println("Replace all Geeks "
                               + "with Quiks :" + s1);
      
            System.out.print("Replace any UpperCase letter "
                             + "with F :");
            System.out.println(s.replaceAll("[A-Z]+", "F"));
      
            // replaceFirst()
            String s2 = s.replaceFirst("Geeks", "Quiks");
            System.out.println("Replace first Occurance"
                               + "of Geeks with Quiks :" + s2);
        }
    }

    chevron_right

    
    

    Output:

    Replace all Geeks with Quiks :QuiksforQuiks
    Replace any UpperCase letter with F :FeeksforFeeks
    Replace first Occuranceof Geeks with Quiks :QuiksforGeeks
    

For more methods on String refer to String class in java
Reference:
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : bhaktiramnan