In this section, we will learn about methods of string class.
The java.lang.String class provides many useful methods to perform operations with String.
Commonly used methods of java.lang.String class --

  • 1) length()

    This method is used to obtain the number of characters(length of string) of invoking string .
    Syntax:

    public int length()

    Example)
    drag_handle
     /*using length() method
    */
    class Test
    {
    	public static void main(String[] args) {
    		//creating the object
    		String x=new String("hello John, how are you?");
    		int l=x.length();
    		System.out.println(x);
    		System.out.println("Number of characters ="+l);	
    	}	
    }
    Output:
    hello John, how are you?
    Number of characters =24
  • 2) isEmpty()

    This method is used to check that invoking string object is empty or not. If the string is empty then it returns true othewise false.
    Syntax:

    public boolean isEmpty()

    Example)
    drag_handle
     /*using isEmpty() method
    */
    class Test
    {
    	public static void main(String[] args) {
    		//creating the object
    		String x=new String("hello John, how are you?");
    		boolean flag=x.isEmpty();
    		System.out.println(flag);
    		System.out.println(new String().isEmpty());
    	}	
    
    }
    Output:
    false
    true
    
  • 3) charAt()

    It is used to obtain any specific character at given position inside invoking string.
    Syntax:

    public char chatAt(int position)

    Example)
    drag_handle
     /*using charAt() method
    */
    class Test
    {
    	public static void main(String[] args) {
    		//creating the object
    		String x=new String("hello John, how are you?");
    		char ch=x.charAt(1);
    		char ch1=x.charAt(6);
    		char ch2=x.charAt(0);
    		System.out.println(ch);
    		System.out.println(ch1);
    		System.out.println(ch2);
    	}	
    
    }
    Output:
    e
    J
    h
    
  • 4) toCharArray()

    This method is used to convert invoking string into character array
    Syntax:
    public char[] toCharArray()

    Example)
    drag_handle
     /*using toCharArray() method
    */
    class Test
    {
    	public static void main(String[] args) {
    		//creating the object
    		String x=new String("hello John, how are you?");
    		char []a=x.toCharArray();
    		System.out.println("Length of array is ="+a.length);
    		System.out.println("printing all elements of array");
    		for(char z:a)
    		{
    			System.out.print(z+" ");
    		}
    	}
    }
    Output:
    Length of array is =24
    printing all elements of array
    h e l l o   J o h n ,   h o w   a r e   y o u ?
  • 5) getBytes()

    This method is used to convert invoking string into its byte type array.
    Syntax:
    public byte[] getBytes()

    Example)
    drag_handle
     /*using getBytes() method
     */
    
    class Test {
    
        public static void main(String[] args) {
            //creating the object
            String x = new String("ABC");
            byte[] a = x.getBytes();
            System.out.println("Length of array is =" + a.length);
            System.out.println("printing all elements of array");
            for (int i = 0; i < a.length; i++) {
                System.out.print(a[i] + " ");
            }
        }
    }
    
    Output:
    Length of array is =3
    printing all elements of array
    65 66 67
  • 6) concat()

    This method provides the facility to concatenate any string with invoking string. This method work same as plus(+) operator.
    Syntax:
    public String concate(String str)

    Example)
    drag_handle
     /*using concat() method
     */
    
    class Test {
    
        public static void main(String[] args) {
            //creating the object
            String x = new String("ABC");
    
            String newString = x.concat("EFG");
            System.out.println(newString);
        }
    }
    
    Output:
    ABCEFG
  • 7) substring()

    This method is used to extract a part of string from the current invoking string. substring is single word.
    Syntax:
    public String substring(int startIndex)
    public String substring(int startIndex,int end-1)

    Example)
    drag_handle
     /*using substring() method
     */
    
    class Test {
    
        public static void main(String[] args) {
            //creating the object
            String x = new String("My name is petter");
    
            String a = x.substring(6);
            String b = x.substring(0, 2);
            System.out.println(a);
            System.out.println(b);
        }
    }
    
    Output:
    e is petter
    My
    
  • 8) indexOf()

    This method is used to obtain the index of first occurrence of any character or string inside the current string.
    Syntax :

    
    public int indexOf(char c)
    public int indexOf(String str)
    
    

    Example)
    drag_handle
     /*using indexOf() method
     */
    
    class Test {
    
        public static void main(String[] args) {
            //creating the object
            String x = new String("My name is petter");
            int i = x.indexOf('e');
            System.out.println(i);
            int j = x.indexOf("name");
            System.out.println(j);
        }
    }
    
    Output:
    6
    3
    
  • 9) lastIndexOf()

    This method is used to obtain the index of lastoccurrence of any character or string inside the current string.
    Syntax :

    
    public int lastIndexOf(char c)
    public int lastIndexOf(String str)
    
    

    Example)
    drag_handle
     /*using lastIndexOf() method
     */
    
    class Test {
    
        public static void main(String[] args) {
            //creating the object
            String x = new String("My name is petter");
            int i = x.lastIndexOf('e');
            System.out.println(i);
            int j = x.lastIndexOf("name");
            System.out.println(j);
        }
    }
    
    Output:
    15
    3
    
  • 10) compareTo()

    This method is used to compare two strings.It is used to implement sorting logic.
    Syntax:

    
    public int compareTo(String str)
    public int compareToIgnoreCase(String str)//it ignores the cases
    

    • return 0 - if both invoking string and parameterized string are same

    • return +ive - if invoking string comes after parameterized string.

    • return -ve - if invoking string comes before parameterized string.

    • what is invoking and parameterized string object? suppose there are two string object ob and ob1

      1905665215.jpg
    Example)
    drag_handle
     /*using compareTo() method
     */
    
    class Test {
        
        public static void main(String[] args) {
            //creating the object
            String str = "ABC";
            String str1 = "EFG";
            int r = str.compareTo(str1);
            System.out.println(r);
        }
    }
    
    Output:
    -4
  • 11) startsWith()

    This method is used to check that the current invoking string starts with the given string or not.
    Syntax:

    public boolean startsWith(String str)

    Example)
    drag_handle
     /*using startsWith() method
     */
    
    class Test {
    
        public static void main(String[] args) {
            //creating the object
            String str = "java is robust language";
            String str1 = "java";
            boolean r = str.startsWith(str1);
            System.out.println(r);
        }
    }
    Output:
    true
  • 12) endsWith()

    This method is used to check that the current invoking string ends with the given string or not.
    Syntax:

    public boolean startsWith(String str)

    Example)
    drag_handle
     /*using endsWith() method
     */
    
    class Test {
    
        public static void main(String[] args) {
            //creating the object
            String str = "java is robust language";
            String str1 = "java";
            boolean r = str.endsWith(str1);
            System.out.println(r);
        }
    }
    
    Output:
    false
  • 13 ) equals() and equalsIgnoreCase()

    These two methods are used to check the equality of two string. whether the two string is equal or not.
    equalsIgnoreCase()- checks the equality in case-insensitive manner
    equals()- is case sensitive
    Syntax:

    public boolean equals(String str)
    public boolean equalsIgnoreCase(String str)

    Example)
    drag_handle
     /*using equals() methods
     */
    
    class Test {
    
        public static void main(String[] args) {
            //creating the object
            String str = "java is robust language";
            String str1 = "Java is robust language";
            boolean r = str.equals(str1);
            boolean r1 = str.equalsIgnoreCase(str1);
            System.out.println(r);
            System.out.println(r1);
        }
    }
    
    Output:
    false
    true
  • 14) toUpperCase() and toLowerCase()

    These methods are used to change the case of invoking string into lowercase and uppercase respectively.
    1) toLowerCase()- convert the string into lowercase.
    2) toUpperCase()-convert the string into uppercase.
    Syntax:

    
    public String toLowerCase();
    public String toUpperCase()
    

    Example)
    drag_handle
     /*using toLowerCase() and toUpperCase() method
    */
    class Test
    {
    	public static void main(String[] args) {
    		//creating the object
    		String x=new String("My name is petter");
    		String temp=x.toLowerCase();
    		String temp1=x.toUpperCase();
    		System.out.println(temp);
    		System.out.println(temp1);
    	}
    }
    Output:
    my name is petter
    MY NAME IS PETTER
    
  • 15) split()

    This method is used to break invoking string into a number of parts according to regex passed in parameter.
    Syntax:

    
    public String[]  split(String regex);
    

    Example)
    drag_handle
     /*using split() methods
     */
    
    class Test {
    
        public static void main(String[] args) {
            //creating the object
            String str = "java is robust language";
            //we are going to break our string and the break  point is space
            //so the regex=" "
            String[] myarray = str.split(" ");
            for (int i = 0; i < myarray.length; i++) {
                System.out.println(myarray[i] + " : " + myarray[i].length());
            }
    
        }
    }
    
    Output:
     java : 4
    is : 2
    robust : 6
    language : 8
  • 16) trim()

    This method is used to remove the the blank spaces(white spaces) from the beginning and ending of the invoking string.
    Syntax:

    public String trim()

    Example)
    drag_handle
     /*using split() methods
     */
    
    class Test {
    
        public static void main(String[] args) {
            //creating the object
            String str = "      java is robust language   ";
            String r = str.trim();
            System.out.println(str);
            System.out.println(r);
    
        }
    }
    
    Output:
          java is robust language   
    java is robust language
  • 17) valueOf()

    This method is used to change any primitive type value to String.
    Syntax:

     public static String valueOf(boolean);
      public static String valueOf(char);
      public static String valueOf(int);
      public static String valueOf(long);
      public static String valueOf(float);
      public static String valueOf(double);
    

    • Note: These method are static, so we don't need the object of String class to call them we can directly call these methods with class Name.
      For example: String .valueOf(any primitve value)

    Example)
    drag_handle
     /*using valueOf() methods
     */
    
    class Test1 {
    
        public static void main(String[] args) {
            int i = 1421451;
            //going to count number of digits
            String temp = String.valueOf(i);//
            //in the same way we can conver any primitive value to string
            System.out.println("Number of digits in " + i + " : " + temp.length());
    
        }
    }
    
    Output:
    Number of digits in 1421451 : 7
  • 18) contains()

    This method is used to check whether invoking string contains the specified sequence of char values or not.
    Syntax:

    public boolean contains(String sequence)
    

    Example)
    drag_handle
     /*using valueOf() methods
     */
    //program for using contains() method
    
    class Test1 {
    
        public static void main(String[] args) {
            String str = "Hello this is my pc ";
            boolean b = str.contains("thiss");
            System.out.println(b);
    
        }
    }
    
    Output:
    false
  • 19) replace()

    This method is used to replace all the old char or CharSequence to new char or CharSequence.
    Syntax:

    public String replace(char oldChar, char newChar)  
    public String replace(CharSequence target, CharSequence replacement)  

    Example)
    drag_handle
     /*using valueOf() methods
     */
    //program for using contains() method
    
    class Test1 {
    
        public static void main(String[] args) {
            String str = "Hello, this is my pc ";
            String newString = str.replace("my", "your");
            System.out.println(str);
            System.out.println(newString);
    
        }
    }
    
    Output:
    Hello, this is my pc 
    Hello, this is your pc 

Program to count the number of word in a string and also count length of each word .
drag_handle
//programm to take a string from user and count number of words 
// also count letters of each word.

import java.util.Scanner;

class WordCount {

    public static void main(String[] args) {
        //creating the object of scanner class ,which helps us to take input from user.
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the String :");
        String str = scanner.nextLine();//reading the input 

        String array[] = str.split(" ");//splipting the array 

        //number of words =length of string array
        int words = array.length;

        //printing number of words in the string
        System.out.println("Number of words : " + words);
        System.out.println("==============================");

        for (int i = 0; i < array.length; i++) {
            String word = array[i];
            System.out.println(word + " : " + word.length());

        }

    }
}

Output:

Enter the String :
java is object-oriented programming language
Number of words : 5
==============================
java : 4
is : 2
object-oriented : 15
programming : 11
language : 8

What next?

The next topic is String Pool in Java

Share this page