String Handling -


  • String is a collection of characters.
  • In java string is implemented as objects of String class contained in java.lang package.
  • String class objects are immutable i.e. once you have defined a String object representing a certain string after that you cannot change its contents.
  • But this does not mean that you cannot perform any operations on these strings. Any time you make changes to a string, a new object representing that modified string will be created.
  • Java also supports two more classes StringBuilder and StringBuffer contained in java.lang package to create strings. Strings created by these two classes are mutable i.e. you are free to change contents of these strings.

Creating String -

Java provides the various ways to create strings. String class have several constructors to create strings -

1- To create an empty string you can call its default constructor like this -
String s1 = new String();
It will create an object of string containing no characters i.e. an empty string.

2- To create string from character array String class support the following constructor -
String(char CharArray[]);      
        
For example -
Char  ch[] = {'W' ,'E'', 'L', 'C', 'O', 'M', 'E'};  
String s1 = new String(ch);
        
Here s1 will represent a string - "WELCOME".

3- We can also create a string containing only defined subrange of array elements using the following constructor -
String(char CharArray[], int StartIndex, int NumOfChars);
Here StartIndex refers to index of array at which subrange starts and NumOfChars refers to number of characters you want to include in string.
For example -
char  ch[] = {'W' ,'E', 'L', 'C', 'O', 'M', 'E'};  
String s1 = new String(ch, 3, 4);
Here s1 will represent a string - "COME".

        

Example -

public class Test {

    public static void main(String[] args) {

        String s1 = new String(); 
        char ch[] = {'W','E','L','C','O','M','E'};
        String s2 = new String(ch);
        String s3 = new String(ch, 3, 4);
        System.out.println("s1 = "+s1);
        System.out.println("s2 = "+s2);
        System.out.println("s3 = "+s3);       
    }
}    
        

Output -

s1 = 
s2 = WELCOME
s3 = COME

4- We can also create string from a byte array containing ASCII values of characters using the following constructors -
String(byte ASCIIChars[]);
String(byte ASCIIChars[], int StartIndex , int NumOfChars);
For example -
byte b[] = {65, 66 , 67, 68, 69, 70};
String s1 = new String(b);
String s2 = new String(b, 3,2);
Here s1 will represent the string - "ABCDEF"
And s2 will represent the string - "DE"

    
5- We can also create a string from a previously existing string by using the following constructor -
String(String obj);
For example -
char ch[] = "WELCOME";
String s1 = new String(ch);
String s2 = new String(s1);
String s3  = new String("Hello");	// We can also pass String literals.
String s2 will represent the same string as s1 i.e. - "WELCOME". And s3 will represent the string "Hello".

        

Example -

public class Call {

    public static void main(String[] args) {

        byte b[] = {65,66,67,68,69,70};
        String s1 = new String(b);
        String s2 = new String(b, 3, 2);
        String s3 = new String(s1);
        String s4 = new String("Hello");
        System.out.println("s1 = "+s1);
        System.out.println("s2 = "+s2);
        System.out.println("s3 = "+s3);
        System.out.println("s4 = "+s4);
        
    }
}

        

Output -

s1 = ABCDEF
s2 = DE
s3 = ABCDEF
s4 = Hello

        

String Literals -

For each string literals you define in your program, Java automatically created a String object for them. So we can initialize a string object by any string literal. For example -
String s1 = "WELCOME";
is a valid string declaration.
But there is a minor difference between this declaration and other declaration of strings that we define by using constructors. Consider the following code -
 
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
    
It can be represented as follows-

If we define two strings with same value using string literal, then for second one there will be no separate value in string pool. In that case both will have the same reference.
However if we define using constructor then each string will have separate entries in string pool irrespective of their values.
So if we compare s1 and s2 using == operator i.e. s1 == s2 the answer will be true.
Similarly s1 == s3 will be false.
i.e. '==' compares their reference values not actual values contained in the string objects.

Length of String -

Java provides us a method named length() to calculate the length of any string.
Note - Do not confuse with length property of arrays.

For example -

String s1 = "WELCOME";
int length = s1.length();    // the output will be 7.
   
     

String Methods -

String class provides a number of string manipulation methods. We will cover here commonly used methods -

String Comparison Methods -

String class provides the following methods to compare two strings or substring within string.

1- equals() and equalsIgnoreCase()

equals() method is used to check whether two strings are equal or not. It has the following syntax-
boolean equals(Object str)
It performs the case sensitive comparison of two strings and return true if both the strings are identical and false otherwise.
equalsIgnoreCase() method as the name indicates perform the case insensitive comparison and return true if both are same and false otherwise. Case insensitive means it consider A-Z to be the same as a-z. It has the following syntax -
boolean equalsIgnoreCase(Object str)

Example -

public class Call {

    public static void main(String[] args) {

       String s1 = "Welcome";
       String s2 = "Welcome";
       String s3 = "WELcomE";
       boolean b1 = s1.equals(s2);
       boolean b2 = s1.equals(s3);
       boolean b3 = s1.equalsIgnoreCase(s3);
       boolean b4  = s1.equals("Hello");
       System.out.println("s1.equals(s2) = "+b1+"\n s1.equals(s3) = "+b2+"\n s1.equalsIgnoreCase(s3) = "+b3+"\n s1.equals("Hello") = "+b4);
    }
}
      

Output -

                s1.equals(s2) = true
                s1.equals(s3) = false
                s1.equalsIgnoreCase(s3) = true
                s1.equals("Hello") = false
       
      

2- startsWith() and endsWith()

startsWith() method as the name indicates checks whether a string is starts with some specified string or not. It return true if it starts with specified string and false otherwise. It has the following syntax -
boolean startsWith(String str)
Similarly endsWith() method checks whether a string is ends with some specified string or not. And it too return true if string ends with that specified string and false otherwise. It has the following syntax -
boolean endsWith(String str)

Example -

public class Call {

    public static void main(String[] args) {

       String s1 = "Rohit Kamboj";
        System.out.println("s1.startsWith("Roh") = "+ s1.startsWith("Roh"));
        System.out.println("s1.startsWith("roh") = "+ s1.startsWith("Roh"));
        System.out.println("s1.endsWith("amboj") = "+ s1.endsWith("amboj"));   
    }
}
        

Output -

               s1.startsWith("Roh") = true
               s1.startsWith("roh") = true
               s1.endsWith("amboj") = true

        

3- compareTo() and compareToIgnoreCase() -

This method is used for comparing two strings to check whether one string is equal to or greater than or less than the second string. It has the following syntax -
int compareTo(String str) The compareTo() method compares two strings character by character continuously until either corresponding character found to be different or last character in one or both of the string reached.
The value returned by compareTo() method is the difference between the ASCII values of first character that is different in both the string.
  • If it returns zero that means invoking string and string passed as argument are identical.
  • If it returns any positive value that means invoking string is greater than the string passes as arguments.
  • If it returns any negative value that means invoking string is less than the string passed as argument.

Example -

public class Call {

    public static void main(String[] args) {

        String s1 = "Hello";
        int i = s1.compareTo("Hello");
        int j = s1.compareTo("Helln");
        int k = s1.compareTo("Iallo");  
        System.out.println("i = "+i+"j = "+j+"k = "+k);
    }
}

Output -

 i = 0  j = 1   k = -1
The value of I is 0 because both the string are identical, in next line value of j is 1 , the ASCII code difference between ?o? and ?n?.
Note the value of k is -1 that is the ASCII code difference between 'H' and 'I'.
compareToIgnoreCase() is the another method that performs the case free comparison of two strings. It is exactly similar to compareTo() method except that here case difference between invoking string and string passed as argument is ignored.

Example -

public class Call {

    public static void main(String[] args) {

        String s1 = "Hello";
        int i = s1.compareTo("hello");
        int j = s1.compareToIgnoreCase("hello");
        System.out.println("i = "+i+" j = "+j);
    }
}

    

Output -

i = -32  j = 0
value of i is -32 that is the ASCII code difference between the values of ?H? and ?h?. Whereas value of j is zero because here case will be ignored, so ?H? and ?h? will be considered identical.

Extracting String Characters -

String class provides a number of methods for accessing characters from strings.

1- charAt() -

It is used to extract a character from a string. It has the following syntax -
char charAt(int position)
Here position will be the index of the character that you want to access. Index should not be less than zero or greater than the length of the string, in that case StringIndexOutOfBoundsException will be thrown and programs terminate.

Example -

                String s1 = ?WELCOME?;
                char ch = s1.charAt(2);
            
Here the value of ch will be ?L?(character at 2nd index)Note that index starts from 0.

2- getChars() -

It is used to access a substring as array of characters from the sour e string. It has the following syntax -
void getChars(int SourceStart, int SourceEnd, char Target[], int TargetStart)
Here SourceStart refers to the starting index position of substring from source string and SourceEnd refers to the one past ending index of substring from source string. SO substring will have the characters from SourceStart to SourceEnd - 1.
Target[] is the array in which you want to receive the substring and TargetStart will be the index from where you want to copy the substring in Target array.

Example -

public class Call {

    public static void main(String[] args) {

        String s1 = "welcome to java";
        char c1 = s1.charAt(2);
        char ch[] = new char[10]; // Array should be large enough to hold the substring
        s1.getChars(11,15,ch,0);
       System.out.println("s1.charAt(2) = "+c1);
        System.out.println(ch);
        
    }
}

Output -

              s1.charAt(2) = l
              Java

3- getBytes() -

It is used to extract all characters of a string into a byte array. It converts all characters of string into their corresponding ASCII code and that is stored in byte array. It has the following syntax -
byte[ ] getBytes()

Example -

public class Call {

    public static void main(String[] args) {

        String s1 = "ABCD";
        byte[] b = s1.getBytes();
        for(byte i:b)
        {
        System.out.print(i+"\t");
        }
    }
}

    

Output -

65	66	67	68	

4- toCharArray() -

It is used to convert all characters of string into a character array. It has the following syntax -
char[] toCharArray()

Example -

public class Call {

    public static void main(String[] args) {

        String s1 = "WELCOME";
        char[] ch = s1.toCharArray();
        for(char c:ch)
        {
        System.out.print(c+"\t");
        }
    }
}

Output -

W	E	L	C	O	M	E

Searching a character or substring in a string -

Java provides two methods for searching a character or any substring within a string -

1- indexOf()

This method search for the occurrence of a character or substring within the string. indexOf() is available in 4 different overloaded versions -
int indexOf(int ch)
This will search for the first occurrence of character ch in the invoking string in forward direction and returns the index position of the first occurrence of character ch.
int indexOf(String str)
This will search for the first occurrence of the substring str in invoking string in forward direction and return the index position of first character in the matched substring in invoking string.
int indexOf(int StartingIndex, int ch)
This is similar to the first version but here search for the character ch in invoking string starts from the specified StartingIndex.
int indexOf(int StartingIndex, String str)
This is similar to second version but here search for the substring str starts from the specified StartingIndex.

Example -

public class Call {

    public static void main(String[] args) {

     String s = "This is just a demo";
    int i = s.indexOf('s'); /*Search for index of first occurrence of 's' from 0                                                                                     
                                            index */
     int j = s.indexOf("is");  /*Search for  index of first occurrence of "is" from 0 
                                                  index */
     int k = s.indexOf('s',4);  /*Search for index of first occurrence of 's' from 
                                                   index position 4 */
     int l = s.indexOf("is",4);  /* Search for index of first occurrence of "is" from                    
                                                      index position 4 */
     System.out.println("i = "+i+" j = "+j+" k = "+k+" l = "+l);
        
    }
}

          

Output -

i = 3 j = 2 k = 6 l = 5

2- lastIndexOf()-

This method is similar to the indexOf() except that it search for the substring or character in the backward direction starting from the last character of the invoking string. It also has 4 overloaded versions -
int lastIndexOf(int ch)
int lastIndexOf(String str)
int lastIndexOf(int ch, int StartingIndex)
int lastIndexOf(String str, int StartingIndex)

Example-

public class Call {

    public static void main(String[] args) {

        String s = "This is just a demo";
        int i = s.lastIndexOf('s'); /*Search for 1st occurrence of 's' from last  
                                                        index position */
        int j = s.lastIndexOf("is");  /*Search for 1st occurrence of "is" from last 
                                                           index position */
        int k = s.lastIndexOf('s',4);  /*Search for 1st occurrence of 's' from 4th 
                                                           index position in backward direction */
        int l = s.lastIndexOf("is",4);  /*Search for 1st occurrence of "is" from 
                                                         4th index position in backward direction */
        System.out.println("i = "+i+" j = "+j+" k = "+k+" l = "+l);
    }
}

    

Output -

i = 10 j = 5 k = 3 l = 2

Modifying a String -

As we already know string objects are immutable i.e. we cannot modify any existing string. Every time when you try to modify any string a new object is created and this new object contain your modifications.

1- substring() -

This method is used to extract a substring from a given string. It has the two form -
String substring(int BeginIndex)
This will return a substring containing all the character of invoking string from BeginIndex position up to the end of the string.
String substring(int BeginIndex, int EndIndex)
This will return a substring containing all the character of invoking string from BeginIndex position up to the EndIndex -1 position. That is EndIndex is not included in the substring.

Example -

public class Call {

    public static void main(String[] args) {

        String s = "This is just a demo";
        String str1 = s.substring(7);
        String str2 = s.substring(8,16);
        System.out.println("str1 = "+str1+" str2 = "+str2);
    }
}

     

Output -

str1 =  just a demo      str2 = just a d

2- concat() -

This is used to merge or concatenate two strings. We can also perform the same operation using + operator also. It has the following syntax -
String concat(String str)

Example -

                 String s1 = "Hello";
                 String s2 = "Welcome";
                String s3 =  s1.concat(s2);
Here the value of string s3 will be "HelloWelcome".
             

3- replace() -

It is used to replace all occurrences of any specific character within a string with some other specified character. It has the following syntax -
String replace(char OldChar, char NewChar)
With jdk5 a new version of replace() is included which is used to replace all occurrences of any specific character sequence within a string with some other character sequence.
String replace(CharSequence Target, CharSequence Replacement)

Example -

public class Call {

    public static void main(String[] args) {

        String s = "This is just a demo";
        System.out.println("s.replace(s, z)"+ s.replace('s', 'z'));
        System.out.println("s.replace(is, was) = "+ s.replace("is", "was"));
      
    }
}

        

Output -

            s.replace(s, z) = Thiz iz juzt a demo
            s.replace(is, was) = Thwas was just a demo

        

4- trim() -

It is used to remove any whitespaces from the beginning and end of the given string. It has the following syntax -
String trim()

Example -

String s1 = "   This is just a demo        ";
String s2 = s1.trim();
It will produce the output - "This is just a demo"

All spaces before and after the string will be trimmed. Note that it does not trim the spaces between strings words or characters.

5- toUpperCase() and toLowerCase() -

toUpperCase() method converts all characters of a given string into uppercase and toLowerCase() converts all characters of a given string in lowercase. Note that all nonalphabetical characters such as digits and special symbol remain unaffected.

Example -

public class Call {

    public static void main(String[] args) {

        String s = "This Is Just A Demo";
        System.out.println("s.toUpperCase() = "+ s.toUpperCase());
        System.out.println("s.toLowerCase() = "+ s.toLowerCase());
      
    }
}

    

Output -

        s.toUpperCase() = THIS IS JUST A DEMO
        s.toLowerCase() = this is just a demo