Java String - methods with example

Class String

public final class String extends Object implements Serializable, Comparable<String>, CharSequence

In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string.For Example :

  char data[] = { 'j', 'a', 'v','a' };
String str = new String(data);

is same as:

                String str = "java";

  • Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
  • The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
  • The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in java by using these three classes.
  • The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.

Create a String Object

By String Literal:

A string literal should be enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "'.

      String str="";

By new Keyword:

String str=new String("");

Java String class methods

  • charAt(int index):It returns the character at the specified index.

        String str="knowledegafctory";


  • length():It returns the length of a String.
        String str="knowledegafctory";


  • equals(Object obj):Compares the string with the specified string and returns true if both matches else false.
       String str="knowledegafctory";
       String strnew="knowledegafctorys";


  • equalsIgnoreCase(String string):It does a case insensitive comparison.
        String str="knowledegafctory";
        String strnew="KnowledegafctorY";


  • compareTo(String string):This method compares the two strings based on the Unicode value of each character in the strings.
        String str="knowledegafctory";
        String strnew="KnowledegafctorY";


  • compareToIgnoreCase(String str):Same as CompareTo method however it ignores the case during comparison.
       String str="knowledegafctory";
       String strnew="KnowledegafctorY";


  • startsWith(String prefix):It tests whether the string is having specified prefix, if yes then it returns true else false.
       String str = "knowledegafctory";


  • startsWith(Str prefix,int offset):It checks whether the substring (starting from the specified offset index) is having the specified prefix or not.
       String str = "knowledegafctory";


  • endsWith(String suffix):Checks whether the string ends with the specified suffix.
       String str = "knowledegafactory";


  • hashCode():It returns the hash code of the string.
       String str = "knowledegafactory";


  • indexOf(int ch): It returns the index of the first occurrence of character ch in a given String.
       String str = "knowledegafactory";


  • indexOf(int ch, int fromIndex): It returns the index of first occurrence of character ch in the given string after the specified index “fromIndex”. 
       String str = "knowledegafactory";


  • lastindexOf(String str): Returns the index of last occurrence of string str.

  • substring(int beginIndex): It returns the substring of the string. The substring starts with the character at the specified index.
       String str = "knowledegafactory";


  • substring(int beginIndex, int endIndex): Returns the substring. The substring starts with character at beginIndex and ends with the character at endIndex.
       String str = "knowledegafactory";


  • replace(char oldChar, char newChar): It returns the new updated string after changing all the occurrences of oldChar with the newChar.
       String str = "knowledegafactory";


  • boolean contains(CharSequence s): It checks whether the string contains the specified sequence of char values. If yes then it returns true else false.
       String str = "knowledegafactory";


  • toUpperCase(): Converts the string to upper case.
       String str = "knowledegafactory";


  •  intern(): This method searches the specified string in the memory pool and if it is found then it returns the reference of it, else it allocates the memory space to the specified string and assign the reference to it.
  •  isEmpty(): This method returns true if the given string has 0 length. If the length of the specified Java String is non-zero then it returns false.
        String str = "knowledegafactory";


  • String join(): This method joins the given strings using the specified delimiter and returns the concatenated Java String

  • replaceFirst(String regex, String replacement): It replaces the first occurrence of substring that fits the given regular expression “regex” with the specified replacement string.
  • replaceAll(String regex, String replacement): It replaces all the occurrences of substrings that fits the regular expression regex with the replacement string.

  • split(String regex): Same as split(String regex, int limit) method however it does not have any threshold limit.
       String str="java string split method by knowledgefactory";  

       String[] words=str.split("\\s");//splits the string based on  whitespace  
       //using java foreach loop to print elements of string array  
for(String w:words){  


  • split(String regex, int limit): It splits the string and returns the array of substrings that matches the given regular expression. limit is a result threshold here.

  • toLowerCase(): It converts the string to lower case string.

  • format(): This method returns a formatted java String

  • trim(): Returns the substring after omitting leading and trailing white spaces from the original string.
       String str = "knowledgefactory  ";

  • toCharArray(): Converts the string to a character array.
  • copyValueOf(char[] data): It returns a string that contains the characters of the specified character array.

  • copyValueOf(char[] data, int offset, int count): Same as above method with two extra arguments – initial offset of subarray and length of subarray.

  • valueOf(): This method returns a string representation of passed arguments such as int, long, float, double, char and char array.

       int num = 1223;
       char character = 'a';


  • length(): It returns the length of a String.

  • getBytes(String charsetName): It converts the String into sequence of bytes using the specified charset encoding and returns the array of resulted bytes.

  • getBytes(): This method is similar to the above method it just uses the default charset encoding for converting the string into sequence of bytes.

This article is contributed by Sibin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above