String Method in Java - Part-1

String MethodsString indexOfString join

In the last blog, we learned about String in Java. If you want to learn more about the String then visit Strings in Java. 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. Following are the methods:

  1. getBytes()

    getBytes() is used for encoding the string into a sequence of bytes using UTF-8(default charset of the platform) and storing its result in the new byte array.

    Syntax

    public byte[ ] getBytes();
    public byte[ ]     getBytes(Charset charsetObj);
    public byte[ ] getBytes(String strObj);

    e.g

    import java.util.Arrays;
    import java.nio.charset.Charset;
    
    class getBytesEx {
      public static void main(String[] args) {
    
        String str = "Java Shortkicks";
        byte[] byteArray;
        try{
           // using UTF-8 for encoding
        System.out.println("getBytes() without using Parameter");
        byteArray = str.getBytes(Charset.forName("UTF-8"));
        System.out.println(Arrays.toString(byteArray));
        // using UTF-16 for encoding
        System.out.println("getBytes() using Charset Parameter");
        byteArray = str.getBytes(Charset.forName("UTF-16"));
        System.out.println(Arrays.toString(byteArray));
        // using UTF-16 for encoding
        System.out.println("getBytes() using String Parameter ");
        byteArray = str.getBytes("UTF-16");
        System.out.println(Arrays.toString(byteArray));
        }catch (Exception e) {
          System.out.println(e);
          }
       }
    }

    Output

    getBytes() without using Parameter
    [74, 97, 118, 97, 32, 83, 104, 111, 114, 116, 107, 105, 99, 107, 115]
    getBytes() using Charset Parameter
    [-2, -1, 0, 74, 0, 97, 0, 118, 0, 97, 0, 32, 0, 83, 0, 104, 0, 111, 0, 114, 0, 116, 0, 107, 0, 105, 0, 99, 0, 107, 0, 115]
    getBytes() using String Parameter
    [-2, -1, 0, 74, 0, 97, 0, 118, 0, 97, 0, 32, 0, 83, 0, 104, 0, 111, 0, 114, 0, 116, 0, 107, 0, 105, 0, 99, 0, 107, 0, 115]
  2. getChars()

    getChars() is used for copying the content of the current string into the character array.

    Syntax

    public void getChars(int sourceBeginIndex, int sourceEndIndex, char[] destination, int destinationBeginIndex);

    sourceBeginIndex - is the index from where the characters should be copied.

    sourceEndIndex - is the index until where the last character should be copied from the source string.

    destination - destination array where the string will be copied.

    destinationBeginIndex - is the index from where the characters from the string should start pushing elements.

    e.g

    public class GetCharsEx {
      public static void main(String args[]){
          String str = new String("Welcome to Java Shortkicks");
          char[] shortkicks = new char[30];
          try {
              str.getChars(9, 26, shortkicks, 0);
              System.out.println(shortkicks);
          } catch(Exception ex) {
              System.out.println(ex);
          }
      }
    }

    Output

    o Java Shortkicks
  3. indexOf()

    indexOf() is used when we want to know the position of the specified character or sequence of characters(string) that occurs first in the string.

    Syntax

    int indexOf(int char);

    used when we want to know the index position of the character value.

    int indexOf(int char, int fromIndex);

    It returns the index position of the character value and from which index to start.

    int indexOf(String string);

    returns the index position of the given sequence of characters mentioned in the parameter i.e. string.

    int indexOf(String string, int fromIndex);

    returns the index position of the string, and fromIndex is used for the index from where to start.

    e.g

    public class IndexOfEx {
      public static void main(String args[]) {
          String str="Java Shortkicks is the learning tool";
    
          int str1 = str.indexOf('l');
          System.out.println("Index Position of 'l' = " + str1);
    
          int str2 = str.indexOf('s',5);
          System.out.println("Index Position of 's' = " + str2);
    
          int str3 = str.indexOf("learning");
          System.out.println("Index Position of 'learning' = " + str3);
    
          int str4 = str.indexOf("Shortkicks");
          System.out.println("Index Position of 'Shortkicks' = " + str4);
      }
    }

    Output

    Index Position of 'l' = 23
    Index Position of 's' = 14
    Index Position of 'learning' = 23
    Index Position of 'Shortkicks' = 5
  4. isEmpty()

    isEmpty() is used for checking if the input string is empty or not, if the string is empty (i.e. if its length is 0) then it returns true, otherwise returns false.

    Syntax

    public boolean isEmpty();

    e.g

    public class IsEmptyEx {
      public static void main(String args[]) {
        String string="Java Shortkicks";
        String string1 = "";
        System.out.println("Result of IsEmpty() = " + string.isEmpty());
        System.out.println("Result of IsEmpty() = " + string1.isEmpty());
      }
    }

    Output

    Result of IsEmpty() = false
    Result of IsEmpty() = true

    Blank strings can also be handled using isEmpty()

    e.g

    public class IsEmptyExample   {
      public static void main(String argvs[])  {
        String string = "     ";
        if(string.length() == 0)  {
            System.out.println("Empty String.
    ");
        }
        else if(string.length() > 0 && string.trim().isEmpty())  {
            System.out.println("Blank String.
    ");
        }
        else {
            System.out.println("String is not blank.
    ");
        }
      }
    }

    Output

    Blank String.
  5. join()

    join() can be used in the string where we want to add a specific delimiter like -, etc. A delimiter will be added to each and every word before starting every word.

    Syntax

    public static String join(CharSequence delimiter, CharSequence elements);

    e.g

    public class JoinEx {
      public static void main(String args[]) {
          String str=String.join("-","Welcome","to","Java","Shortkicks");
          System.out.println("Result of join() = " + str);
      }
    }

    Output

    Result of join() = Welcome-to-Java-Shortkicks

    null cannot be used as a delimiter, if used then null pointer exception will be thrown. Let's see it through the example:

    e.g

    public class JoinEx {
      public static void main(String argvs[])  {
         String string = null;
         string = String.join("Java Shortkicks", null);
         System.out.println(string);
      }
    }

    Output

    string = String.join("Java Shortkicks", null);
    ^
    both method join(CharSequence,CharSequence...) in String and method join(CharSequence,Iterable<? extends CharSequence>) in String match
    /tmp/Uv72Lbdm9F/JoinEx.java:7: warning: non-varargs call of varargs method with inexact argument type for last parameter;
    string = String.join("Java Shortkicks", null);
                             ^
    cast to CharSequence for a varargs call
    cast to CharSequence[] for a non-varargs call and to suppress this warning
    1 error
    1 warning

    But if we attach some elements with the delimiter from which some are string and some are null, then the exception will not be thrown, null will be considered as a normal string. Let's see this with the help of an example:

    e.g

    public class JoinEx  {
      public static void main(String argvs[])  {
          String string = null;
          string = String.join("/", null, " Welcome ", " Java ", " Shortkicks ");
          System.out.println(string);
      }
    }

    Output

    null/ Welcome / Java / Shortkicks
  6. lastIndexOf()

    lastIndexOf() is used when we want the last index of the character or the string. If the character or string is not found, then it returns -1. Following are the types of lastIndexOf().

    Syntax

    int lastIndexOf(int char);

    It returns the position of the last index of the given character.

    int lastIndexOf(int ch, int fromIndex);

    It returns the position of the last index of the given character and fromIndex is from where to start the count of the string.

    int lastIndexOf(String string);

    It returns the position of the last index of the given string

    int lastIndexOf(String substring, int fromIndex);

    It returns the position of the last index of the given string and fromIndex is the index from where to start counting the string.

    e.g

    public class LastIndexOfEx {
      public static void main(String args[]) {
          String string = "This is an example of lastIndex() method";
          int strResult = string.lastIndexOf('e');
          System.out.println("Index position of the last occurence of e = "+ strResult);
          int strResult1 = string.lastIndexOf('a',20);
          System.out.println("Index position of the last occurence of a = "+ strResult1);
          int strResult2 = string.lastIndexOf("example");
          System.out.println("Index position of the last occurence of example = "+ strResult2);
          int strResult3 = string.lastIndexOf("ex",30);
          System.out.println("Index position of the last occurence of ex = "+ strResult3);
    
      }
    }

    Output

    Index position of the last occurence of e = 35
    Index position of the last occurence of a = 13
    Index position of the last occurence of example = 11
    Index position of the last occurence of ex = 29
  7. length()

    length() method is used when we want to find the length of the specific string.

    Syntax

    public int length();

    e.g

    public class LengthEx {
      public static void main(String args[]) {
          String string = "Welcome to Java Shortkicks";
          String string1 = "This is an example of length() method";
          System.out.println("The length of string is = "+ string.length());
              System.out.println("The length of string1 is = "+ string1.length());
      }
    }

    Output

    The length of string is = 26
    The length of string1 is = 37
  8. replace()

    replace() is used when we want to replace the old characters or sequence of characters with the new characters in the string.

    Syntax

    public String replace(char oldCharacter, char newCharacter);
    public String replace(CharSequence target, CharSequence replacement);

    e.g

    public class ReplaceEx {
      public static void main(String args[]) {
          String string = "Welcome to Java Shortkicks";
          String string1 = string.replace('o','a');
          System.out.println("Replacement of characters = "+ string1);
          String string2 = "This is an example of replace() method ";
          String string3 = string2.replace('e','i');
          System.out.println("Replacement of characters = "+ string3);
      }
    }

    Output

    Replacement of characters = Welcame ta Java Shartkicks
    Replacement of characters = This is an ixampli of riplaci() mithod

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.