String class Methods

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()

/*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);	
	}	
}
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()

/*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());
	}	

}
false
true

3) charAt()

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

public char chatAt(int position)

/*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);
	}	

}
e
J
h

4) toCharArray()

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

/*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+" ");
		}
	}
}
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()

/*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] + " ");
        }
    }
}
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)

/*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);
    }
}
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)

/*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);
    }
}
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)

/*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);
    }
}
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)

/*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);
    }
}
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

/*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);
    }
}
-4

  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

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)

/*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);
    }
}
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)

/*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);
    }
}
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)

/*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);
    }
}
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()

/*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);
	}
}
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);

/*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());
        }

    }
}
 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()

/*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);

    }
}
      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);

/*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());

    }
}
Number of digits in 1421451 : 7

  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)

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)

/*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);

    }
}
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)  

/*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);

    }
}
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 .
//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());

        }

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