String Method in Java - Part-2

String MethodsString trimString split

In the last blog, we learned about String in Java. If you want to learn more about the String then visit String Methods in Java Part 1. In the Strings, in Java blog, we have learned some methods of String. In this blog, we will continue with the remaining methods of String. The following are the methods:

  1. replaceAll()

    replaceAll() method gives us the string replacing all the sequence of characters matching regular expressions and replacement string.

    Syntax

    public String replaceAll(String regular expression, String replacement);

    e.g

    public class ReplaceAllEx {
      public static void main(String args[]) {
        String string1 = "This is an example of replace() method";
        String string2 = string1.replaceAll("e","a");
        String string3 = string2.replaceAll("This","It");
        String string4 = "Welcome to Java Shortkicks";
        String string5 = string4.replaceAll("Shortkicks","Blog");
        System.out.println("Replacement of char = "+ string2);
        System.out.println("Replace string This with It = "+string3);
        System.out.println("Replace string Shortkicks with Blog = "+string5);
      }
    }

    Output

    Replacement of char = This is an axampla of raplaca() mathod
    Replace string This with It = It is an axampla of raplaca() mathod
    Replace string Shortkicks with Blog = Welcome to Java Blog
  2. split()

    split() breaks(splits) the string into multiple strings by providing the delimiter which separates the string.

    Syntax

    public String split(String regularExpression(regex));
    public String split(String regularExpression(regex), int limit);

    e.g

    public class SplitEx {
      public static void main(String args[]) {
          String string="Java Shortkicks is the learning tool";
          String[] string2=string.split("\s");
          System.out.println("The string is:");
          for(String shortkick:string2) {
              System.out.println(shortkick);
          }
    
      }
    }

    Output

    The string is:
    Java
    Shortkicks
    is
    the
    learning
    Tool

    Above example is without using any limit just displaying every word of the string in next line.

    Now we will see how we can split the string by giving the limit to it

    e.g

    public class SplitIntoLimitEx {
      public static void main(String args[]) {
          String string="Java Shortkicks is the learning tool";
          String[] strArr1=string.split("\s",2);
          String[] strArr2=string.split("\s",3);
          String[] strArr3=string.split("\s",5);
          String[] strArr4=string.split("r",3);
          System.out.println();
          System.out.println("Splitting the string into 2 parts:");
    
          for(String shortkick:strArr1){
              System.out.println(shortkick);
          }
    
          System.out.println();
          System.out.println("Splitting the string into 3 parts:");
    
          for(String shortkick:strArr2){
              System.out.println(shortkick);
          }
    
          System.out.println();
          System.out.println("Splitting the string into 5 parts:");
    
          for(String shortkick:strArr3){
              System.out.println(shortkick);
          }
          System.out.println();
          System.out.println("Splitting the string by using delimiter r into 3 parts:");
    
          for(String shortkick:strArr4){
              System.out.println(shortkick);
          }
      }
    }

    Output

    Splitting the string into 2 parts:Java
    Shortkicks is the learning tool
    
    Splitting the string into 3 parts:
    Java
    Shortkicks
    is the learning tool
    
    Splitting the string into 5 parts:
    JavaShortkicks
    is
    the
    learning tool
    
    Splitting the string by using delimiter r into 3 parts:
    Java Sho
    tkicks is the lea
    ning tool
  3. startsWith()

    startsWith() method is used when we want to check if the string starts with the mentioned prefix. If the string contains the given prefix, then it returns true, otherwise returns false.

    Syntax

    public boolean startsWith(String givenPrefix);
    public boolean startsWith(String givenPrefix, int offset);

    e.g

    public class StartsWithEx {
      public static void main(String args[]) {
          String string="Java Shortkicks is the learning tool";
          System.out.println(string.startsWith("Java"));
          System.out.println(string.startsWith("Java Shortkicks"));
          System.out.println(string.startsWith("JAVA SHRTKICKS"));
          System.out.println(string.startsWith("learning"));
      }
    }

    Output

    true
    true
    false
    false

    Now we will see the example of startsWith() having offset, offset is nothing but the index from where we want to start matching the prefix in the string.

    e.g

    public class StartsWithEx {
      public static void main(String args[]) {
          String string="Java Shortkicks is the learning tool";
          System.out.println(string.startsWith("Shortkicks",5));
          System.out.println(string.startsWith("Java Shortkicks"));
          System.out.println(string.startsWith("learning",23));
      }
    }

    Output

    true
    true
    true

    In the above example for Shortkicks offset is 5 and there is no offset mentioned for Java Shortkicks, so the offset considered will be 0 by default.

  4. substring()

    substring() is used to extract the substring from the large string.

    Syntax

    public String substring(int startIndexValue);
    public String substring(int startIndexValue, int endIndexValue);

    e.g

    public class SubStringEx {
      public static void main(String args[]) {
          String string="Java Shortkicks is the learning tool";
          System.out.println(string.substring(5));
          System.out.println(string.substring(5,15));
    
          /* Here it will give expectation that is StringIndexOutOfBoundsException:
             because the length of string is 36 and the endIndex mentioned is 37 */
        System.out.println(string.substring(5,37));
      }
    }

    Output

    Shortkicks is the learning tool
    Shortkicks
    
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 5, end 37, length 36
    at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319)at java.base/java.lang.String.substring(String.java:1874)
        at DevSubStringEx.main(DevSubStringEx.java:6)
  5. toLowerCase()

    toLowerCase() returns all the characters of the string in lowercase letters.

    Syntax

    public String toLowerCase();

    e.g

    public class ToLowerCaseEx {
      public static void main(String args[]) {
          String string="JAVA SHORTKICKS iS tHe Learning TooL";
          System.out.println(string.toLowerCase());
      }
    }

    Output

    java shortkicks is the learning tool
  6. toUpperCase()

    toUpperCase() returns all the characters of the string in uppercase letters.

    Syntax

    public String toUpperCase();

    e.g

    public class ToLowerCaseEx {
      public static void main(String args[]) {
          String string="JAVA SHORTKICKS iS tHe Learning TooL";
          System.out.println(string.toUpperCase());
      }
    }

    Output

    JAVA SHORTKICKS IS THE LEARNING TOOL
  7. trim()

    trim() is used for eliminating the beginning and ending spaces in the string.

    Syntax

    public String trim();

    e.g

    public class trimEx {
      public static void main(String args[]) {
          String string= "    java shortkicks is the learning tool         ";
          System.out.println("String without using trim:");
          System.out.println(string);
          System.out.println("String using trim:");
          System.out.println(string.trim());
      }
    }

    Output

    String without using trim:
    java shortkicks is the learning tool
    String using trim:
    java shortkicks is the learning tool
  8. valueOf()

    valueOf() is used for converting the different types of values like int, float, long, boolean, etc into the string. Using this method we can convert int to string, float to string, long to string, boolean to string, etc.

    Syntax

    public static String valueOf(boolean value);
    public static String valueOf(char char);
    public static String valueOf(char[] char);
    public static String valueOf(int value);
    public static String valueOf(long value);
    public static String valueOf(float value);
    public static String valueOf(double value);
    public static String valueOf(Object object);

    e.g

    public class ValueOfEx {
      public static void main(String[] args) {
          short shortValue = 19;
          int value = 59;
          long longValue = 99L;
          float floatValue = 43.67f;
          double doubleValue = 7897.32d;
          char character[] = {'j','a','v','a','s','h','o','r','t','k','i','c','k','s'};
          boolean booleanValue = false;
          byte byteValue = 10;
          DevValueOfEx object=new DevValueOfEx();
    
          String string1 = String.valueOf(object);
          String string2 = String.valueOf(shortValue);
          String string3 = String.valueOf(value);
          String string4 = String.valueOf(longValue);
          String string5 = String.valueOf(floatValue);
          String string6 = String.valueOf(doubleValue);
          String string7 = String.valueOf(character);
          String string8 = String.valueOf(booleanValue);
          String string9 = String.valueOf(byteValue);
    
          System.out.println(string1);
          System.out.println(string2);
          System.out.println(string3);
          System.out.println(string4);
          System.out.println(string5);
          System.out.println(string6);
          System.out.println(string7);
          System.out.println(string8);
          System.out.println(string9);
      }
    }

    Output

    DevValueOfEx@5a07e868
    19
    59
    99
    43.67
    7897.32
    javashortkicks
    false
    10

Mostly asked Questions

  1. String abc = "abc";

    System.out.println(abc=="abc");

    Creates space in stack to store the reference abc. It creates space in the String literal pool to store the constant i.e. abc. Reference abc will point to the constant(abc) in the pool. The address of the reference abc is the same as "abc" used in the print statement. So it will print true here as both have the same address i.e. abc.

  2. String stringObj = new("ABC");

    System.out.println(stringObj =="ABC");

    Creates a space in the stack to store the reference i.e. stringObj. Creates a space in the heap to store the constant("abc") in the heap. Reference stringObj points to the newly created object("abc") in the heap. The address of the reference object(stringObj) is the address in the heap and the constant("abc") address is in the string constant pool, so the result will be false.

  3. String abc = "ABC";

    String strObj = new("ABC");

    String strObj1 = new("ABC");

    System.out.println(abc == strObj);

    System.out.println(strObj == strObj1);

    In the first statement space will be created in the stack to store the reference and for string, the string constant space will be created in string constant pool. In the second statement, a space will be created in the stack for the reference (strObj) and a separate space will be created for the string (abc) in the heap. In the third statement, the same process will be followed as in the second statement. The next statement will return the result false because abc address is in the String pool and strObj address is in the heap. The same result will be returned for the last statement i.e. false because the same will be applied here. strObj address is the address in the heap but it is located at a different location, and strObj1 will also be stored in the heap memory, but it will have a different location as it is created using the "new" keyword.

Core Java Tutorial

Get in Touch

Atrowel will be pleased to receive your feedback and suggestions. Those of you who would like to contribute, please send us an email.