See the Tutorial List

Java String class functions

The methods specified below are some of the most commonly used methods of the String class in Java. We will learn about each method with help of small code examples for better understanding.

charAt() method

charAt() function returns the character located at the specified index.

String str = "studytonight";
System.out.println(str.charAt(2));

Output: u

NOTE: Index of a String starts from 0, hence str.charAt(2) means third character of the String str.


equalsIgnoreCase() method

equalsIgnoreCase() determines the equality of two Strings, ignoring thier case (upper or lower case doesn't matters with this fuction ).

String str = "java";
System.out.println(str.equalsIgnoreCase("JAVA"));

true


indexOf() method

indexOf() function returns the index of first occurrence of a substring or a character. indexOf() method has four forms:

  • int indexOf(String str): It returns the index within this string of the first occurrence of the specified substring.
  • int indexOf(int ch, int fromIndex): It returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
  • int indexOf(int ch): It returns the index within this string of the first occurrence of the specified character.
  • int indexOf(String str, int fromIndex): It returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

Example:

public class StudyTonight {
    public static void main(String[] args) {
        String str="StudyTonight";
        System.out.println(str.indexOf('u'));   //3rd form
        System.out.println(str.indexOf('t', 3));    //2nd form
        String subString="Ton";
        System.out.println(str.indexOf(subString)); //1st form
        System.out.println(str.indexOf(subString,7));   //4th form
    }
}

2 11 5 -1

NOTE: -1 indicates that the substring/Character is not found in the given String.


length() method

length() function returns the number of characters in a String.

String str = "Count me";
System.out.println(str.length());

8


replace() method

replace() method replaces occurances of character with a specified new character.

String str = "Change me";
System.out.println(str.replace('m','M'));

Change Me


substring() method

substring() method returns a part of the string. substring() method has two forms,

public String substring(int begin);

public String substring(int begin, int end);
/*
    character of begin index is inclusive and character of end index is exclusive.
*/

The first argument represents the starting point of the subtring. If the substring() method is called with only one argument, the subtring returned, will contain characters from specified starting point to the end of original string.

But, if the call to substring() method has two arguments, the second argument specify the end point of substring.

String str = "0123456789";
System.out.println(str.substring(4));

456789

System.out.println(str.substring(4,7));

456


toLowerCase() method

toLowerCase() method returns string with all uppercase characters converted to lowercase.

String str = "ABCDEF";
System.out.println(str.toLowerCase());

abcdef


toUpperCase() method

This method returns string with all lowercase character changed to uppercase.

String str = "abcdef";
System.out.println(str.toUpperCase());

ABCDEF


valueOf() method

Overloaded version of valueOf() method is present in String class for all primitive data types and for type Object.

NOTE: valueOf() function is used to convert primitive data types into Strings.

public class Example{
    public static void main(String args[]){
        int num = 35;
        String s1 = String.valueOf(num);    //converting int to String
        System.out.println(s1+"IAmAString");
    }
}

35IAmAString

But for objects, valueOf() method calls toString() function.


toString() method

toString() method returns the string representation of the object used to invoke this method. toString() is used to represent any Java Object into a meaningful string representation. It is declared in the Object class, hence can be overrided by any java class. (Object class is super class of all java classes.)

public class Car {
    public static void main(String args[])
    {
        Car c = new Car();
        System.out.println(c);
    }
    public String toString()
    {
        return "This is my car object";
    }
}

This is my car object

Whenever we will try to print any object of class Car, its toString() function will be called. toString() can also be used with normal string objects.

String str = "Hello World";
System.out.println(str.toString());

Hello World


NOTE: If we don't override the toString() method and directly print the object, then it would print the object id.

Example:

public class Car {
    public static void main(String args[])
    {
        Car c = new Car();
        System.out.println(c);
    }
}

studytonight.Car@15db9742 (here studytonight is a user-defined package).


toString() with Concatenation

Whenever we concatenate any other primitive data type, or object of other classes with a String object, toString() function or valueOf() function is called automatically to change the other object or primitive type into string, for successful concatenation.

int age = 10;
String str = "He is" + age + "years old.";

In above case 10 will be automatically converted into string for concatenation using valueOf() function.


trim() method

This method returns a string from which any leading and trailing whitespaces has been removed.

String str = "   hello  ";
System.out.println(str.trim());

hello

NOTE: If the whitespaces are between the string, for example: String s1 = "study tonight"; then System.out.println(s1.trim()); will output "study tonight".

trim() method removes only the leading and trailing whitespaces.


contains()Method

contains() is a string method. It is used to check the sequence of characters in the given string. It returns true if a sequence od string is found else it returns false

    
public class ContainsDemo1 
{  
    public static void main(String[] args) 
    {  
        String a = "Hello welcome to studytonight.com";  
boolean b = a.contains("studytonight.com");  
System.out.println(b);    
System.out.println(a.contains("javatpoint"));  
    }  
}  
    

true false


endsWith() Method

endsWith() is a string method. It is used to check whether the string ends with the given suffix or not. It returns true when suffix matches the string else it returns false.

    
public class EndsWithDemo1
{  
    public static void main(String args[])
    {  
        String a="Hello welcome to studytonight.com";  
        System.out.println(a.endsWith("m"));  
        System.out.println(a.endsWith("com"));  
    }
}  
    

true true


format() Method

format() is a string method. It is used to the format of the given string.

Following are the format specifier and their datatype:

Format Specifier Data Type
%a floating point
%b Any type
%c character
%d integer
%e floating point
%f floating point
%g floating point
%h any type
%n none
%o integer
%s any type
%t Date/Time
%x integer
    
public class FormatDemo1
{  
    public static void main(String[] args) 
    {  
        String a1 = String.format("%d", 125);            
        String a2 = String.format("%s", "studytonight");  
        String a3 = String.format("%f", 125.00);        
        String a4 = String.format("%x", 125);            
        String a5 = String.format("%c", 'a');  
System.out.println("Integer Value: "+a1);  
System.out.println("String Value: "+a2);  
System.out.println("Float Value: "+a3);  
System.out.println("Hexadecimal Value: "+a4);  
System.out.println("Char Value: "+a5);  
    }  
}  
    

true true


getBytes() Method

getBytes() is a string function in java. It is used to get the byte array of the string

    
public class GetBytesDemo1
{  
    public static void main(String args[])
    {  
        String a="studytonight";  
        byte[] b=a.getBytes();  
        for(int i=0;i<b.length;i++)
        {  
            System.out.println(b[i]);  
        }  
    }
}  
    

getbyte-example


getChars() Method

getChars() is a string function in java. It is used to copy the content of the string into a char array.

    
public class GetCharsDemo1
{  
    public static void main(String args[])
    {  
        String a= new String("Hello Welcome to studytonight.com");  
        char[] ch = new char[16];  
        try
        {  
        a.getChars(5, 12, ch, 2);  
        System.out.println(ch);  
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }  
    }
}  
    

Welcom


isEmpty() Method

isEmpty() is a string method in Java . It is used to check whether the string is empty or not. It returns true when length string is zero else it returns false.

    
public class IsEmptyDemo1
{  
    public static void main(String args[])
    {  
        String a="";  
        String b="studytonight";  
        System.out.println(a.isEmpty());  
        System.out.println(b.isEmpty());  
    }
}  
    

true false


join() Method

join() is a string method in Java. It is used to join strings with the given delimiter. The given delimiter is copied with each element.

    
public class JoinDemo1
{  
    public static void main(String[] args) 
    { 
    String s = String.join("*","Welcome to studytonight.com");
    System.out.println(s);           
        String date1 = String.join("/","23","01","2020");    
System.out.println("Date: "+date1);    
        String time1 = String.join(":", "2","39","10");  
System.out.println("Time: "+time1);  
    }  
}  
    

Welcome to studytonight.com Date: 23/01/2020 Time: 2:39:10


startsWith() Method

startsWith() is a string method in java. It is used to check whether the given string starts with given prefix or not. It returns true when prefix matches the string else it returns false.

    
public class StartWithDemo1
{  
    public static void main(String[] args)
    {  
        String str = "studytonight";  
System.out.println(str.startsWith("s"));   
System.out.println(str.startsWith("t"));   
System.out.println(str.startsWith("study",1)); 

    }  
}  
    

true false false