^

String Class

To work with strings, Java provides three final classes String, StringBuffer and StringBuilder. In this chapter, we will look more deeply at the most commonly used methods provided by these classes.
String class is provided in java.lang package. It provides various constructors and methods to create and manipulate String objects. Objects of String class are immutable, i.e., once the object has been created and initialized, it can not be changed later. Every method in the class that appears to modify the contents of a String object, actually creates a new object having modifi ed contents and the existing object becomes unreferenced.

Creating String Objects

A String object can be created using:
  1. String literals
  2. Constructor functions
1)Using String Literals
Using a string literal is the easiest way to create String object. As shown below:
 String str1 = “HELLO”; 
The above statement creates a String class object having “HELLO” and its reference is assigned to str1 reference variable. As shown below:
real java string
If you assign a new string literal to reference variable: str1, a new object will be created and the existing object becomes unreferenced. As shown below:
real java string hello
Operators + and += can also be used to create String objects. Java does not provide operator overloading like C++ but + and += operators are already overloaded in Java for String class only.
For example:
String st1 = “REAL”;
String st2 = st1 + “ JAVA”; 
As a result, a new object will be created having contents “REAL JAVA”, as shown below:
real java string real java
Consider the following code:
String st3 = “HELLO”;
st3 += “ JAVA”;
Since String objects are immutable, now reference variable st3 will refer to new object having “HELLO JAVA” and the existing object becomes eligible for garbage collection, as shown follows:
real java string hello java
2)Using Constructor Functions
The String class provides the following commonly used constructors:
  • String( )
  • This constructor creates an object which is initialized to empty.
  • String(String object)
  • It creates an object having contents same as the String object passed as argument.
    For example:
    String s1 = “India”;
    String s2 = new String(s1);
    System.out.println(s2); //India 
  • String(char[ ] array)
  • It creates a new object which is initialized with the contents copied from array passed as argument.
    For example:
    char ar[ ] = {‘J’, ‘A’, ‘V’, ‘A’};
    String ss = new String (ar);
    System.out.println(ss); //JAVA 
  • String(char[ ] ary, int startIndex, int count)
  • This constructor consists of three parameters:
    char [ ] ary: Specifi es the array as source of character to be copied in the new object.
    int startIndex: Specifi es the index value from where to start
    int count: Specifi es the number of characters to be copied.
    For example:
    char[ ] ary = {‘R’, ‘E’, ‘A’, ‘L’, ‘J’, ‘A’, ‘V’, ‘A’};
    String st = new String (ary, 4, 4);
    System.out.println(st); //JAVA  
  • String (StringBuilder obj)
  • It creates a new String object from a StringBuilder object.
  • String (StringBuff er obj)
  • It creates a new String object from a StringBuff er object.
  • String(byte[ ]ary)
  • It creates a new String object from the array of bytes passed as arguments.
  • String(byte[ ]ary, int startIndex, int count)
  • It creates a new String object by copying count number of bytes from an array of bytes starting from index startIndex.
    For example:
    byte [] b = [65, 66, 67, 68];
    String s = new String (b, 1, 2);
    System.out.println(); //BC

Using String Class Methods

  • String toUpperCase( )
  • String toLowerCase( )
  • The method toUpperCase()converts lower case characters to upper case and toLowerCase()converts characters to lower case. If none of the characters are changed, both methods return reference to the same String object, otherwise returns new String object.
    For example:
    String S1 = “SST”;
    String S11 = S1.toLowerCase( );
    System.out.println (S1 == S11); // false
    String S22 = S1.toUpperCase( );
    System.out.println(S1 == S22); //  true
  • String[] split(String regExp)
  • This method returns an array of String objects on the basis of regular expression pattern (regExp) passed as argument.
    For example:
    String s = “Hello Java Hello Programmers”;
    String[] sa = s.split(“ ”);
    for (String v : sa)
    System.out.println(v);
    The statement: String[] sa = s.split(“ ”); , can be replaced with the following code also:
    String [] sa = Pattern.compile(“ ”).split(s1);
  • int length()
  • This method returns the number of characters in a string.
    For Example:
    String S = “Real Java”;
    int l = S.length();
    System.out.println(l); // 9
  • int indexOf(int character)
  • This method returns the index of fi rst occurrence of the character passed as argument. It returns -1 if the character is not presented in the string.
    For Example:
    String s1 = “Real Java”;
    int index = s1.indexOf(‘a’);
    System.out.println(index); // 2
  • int indexOf(int character, int startIndex)
  • This method fi nds fi rst occurrence of specifi ed character. It starts search from specifi ed index (startIndex).
    For Example:
    String s1 = “Real Java”;
    int index = s1.indexOf(‘a’);
    System.out.println(index); // 2  
  • int indexOf(int character, int startIndex)
  • This method fi nds first occurrence of specifi ed character. It starts search from specifi ed index (startIndex).
    For Example:
    String s = “Real Java”;
    int indx = s.indexOf(‘a’, 3);
    System.out.println(indx); // 6
  • int indexOf (String str)
  • int indexOf(String str, int startIndex)
  • The first method starts search of argument string from zero index, whereas second method starts searching from specifi ed startIndex.
    For Example:
    String s = “Step by Step”;
    int indx1 = s.indexOf(“Step”);
    System.out.println(indx1); // 0
    int indx2 = s.indexOf(“Step”, 2);
    System.out.println(indx2); // 8
  • String substring (int startIndex)
  • This method returns a new String object containing substring that starts from specifi ed startIndex.
    For Example:
    String s = “Sun-Soft Technologies”;
    String ss = s.substring(9);
    System.out.println(ss); // Technologies
  • String substring (int startIndex, int endIndex)
  • This method returns a new String object containing substring that starts from specifi ed startIndex to the endIndex-1.
    For Example:
    String S = “Sun-Soft Technologies”;
    String SS = S.substring(4, 8);
    System.out.println(SS); // Soft
      
  • char charAt (int index)
  • This method returns a character at specifi ed index.
    For Example:
    String s = “India”;
    char ch = s.charAt(2);
    System.out.println(ch); //d
  • void getChars(int startIndx, int endIndx, char[] dest, int desStartIndx)
  • This method copy characters from String object into an array of characters. It starts reading characters from specifi ed startIndx to endIndx-1. These are copied in destination (dest) array starting at desStartIndx.
    For Example:
    String s = “Sun-Soft Tech”;
    char ch[ ] = new char[4];
    s.getChars(4, 8, ch, 0);
    for(int i = 0; i < ch.length; i++)
             {
               System.out.println(ch[i]);
             }
  • char[ ] toCharArray()
  • This method copies all characters from string object to an array of characters.
    For Example:
    String s = “Real Java”;
    char[]ch = s.toCharArray();
    for(int i = 0; i < ch.length; i++)
              System.out.println(ch[i]); 
  • boolean isEmpty()
  • This method returns true if the length of the string is zero(0) else return false.
    For Example:
    String s = “James Gosling”;
    System.out.println(s.isEmpty());  
  • int compareTo(String object)
  • This method compares the contents of invoking string object with the string object passed as argument. Characters are compared lexicographically. It returns a value +ve, -ve zero.
    The zero(0) value means both strings are same.
    The +ve value means that the invoking object is lexicographically greater than the other string
    The -ve value means that the invoking string object is lexicographicall less than the other string object.
    For Example:
    String s1 = “ABCDE”;
    String s2 = “BC”;
    int v1 = s1.compareTo(s2);
    System.out.println(v1); // -1  
    The above code prints -1 (ASCII of ‘A’ - ASCII of ‘B’) which means that s1 is less than s2. The above code prints 1 (ASCII of ‘B’ - ASCII of ‘A’), which means that s2 is greater than s1.
    The following program sorts a list of strings using compareTo() method:
    //program to sort a list of strings
    public class Sorting {
    	public static void main(String[] args) {
    	 String[] list={“BANANA”,”APPLE”,”ORANGE”,”LICHI”,”GUAVA”};
    	     for (int i = 0; i < list.length; i++) 
    		{  for (int j = 0; j < list.length-1-i; j++) 
    		   {if(list[j].compareTo(list[j+1])>0)
    				{String temp=list[j];
    				list[j]=list[j+1];
    				list[j+1]=temp;
    				}
    			}
    		}
    	System.out.println(“Sorted List of Strings:”);
    	for (int i = 0; i < list.length; i++) 
    	{ 
        	 System.out.print(list[i]);
    	}
    	}
    }
              Output:
                     Sorted List of Strings:
                     APPLE, BANANA, GUAVA, LICHI,ORANGE.
               
  • boolean equals (Object obj)
  • The equals()method is a member of java.lang.Object class. It basically checks the reference equality but java.lang.Stringclass override this method for content equality. If the contents are same than it returns true else false.
    For Example:
    String s1 = “Real Java”;
    String s2 = “Real Java”;
    System.out.println(s1.equals(s2)); // true
    
  • String concat(String str)
  • This method creates a new string object by joining the contents of invoking string object and argument object.
    For Example:
    String s1 = “Real”;
    String s2 = “Java”;
    String s3 = s1.concat(s2);
    System.out.println(s3); // RealJava
    In the above code, s3 refers to a new string object containing the contents of s1 and s2 objects, s1.concat(s2) creates a new string object containing “RealJava” but its reference will not be stored anywhere, however, the contents of object s1remain same (“Real”) due to immutable nature of string objects.
    But,If we write: s1 = s1.concat(s2); then it generates new string object containing “RealJava” and its reference will be stored in s1. As shown below:
    real java string concat
  • String trim()
  • This method removes spaces from the front and the end of a string.
    For Example:
    String s = “ Hello ”;
    System.out.println(“Before :*” + s+ “**”); //Before:* Hello **
    s = s.trim();
    System.out.println(“After:*” + s + “**”); // After:*Hello** 
  • String replace(char existingChar, char newChar)
  • This method replaces all occurrences of existing character with the new character passed as arguments and returns a new string object.
    For Example:
    String s = “Banglore”;
    String s1 = s.replace(‘a’, ‘A’);
    System.out.println(s1); // BAnglore
      
  • String replaceAll(String target, String replacement)
  • This method replaces all substrings that matches the target string with replacement string.
    For Example:
    String s = “two one three one”;
    String s1 = s.replaceAll(“one”, “four”);
    System.out.println(s1); // two four three four
    
    String s = “BANGLORE COMP. EDUCATION”;
    String s2 = s.replaceAll(“[AEO]”, “*”);
    System.out.println(s2); // B*NGL*R* C*MP. *DUC*TI*N
  • Conversion from primitive values to string objects
  • String class consists of various static overloaded forms of valueOf()method to convert primitive values to string objects.
    Some of them are listed below:
    static String valueOf(int)
    static String valueOf(float)
    static String valueOf(char)
    static String valueOf(boolean)
    static String valueOf(char[])
    static String valueOf(double)
    For Example:
    int i = 7;
    float f=2.4f;
    double d=3.4;
    boolean b=true;
    String s1 = String.valueOf(i);
    String s2 = String.valueOf (f);
    String s3 = String.valueOf(d);
    String s3 = String.valueOf(b);
    String s4 = String.valueOf (new char[] {‘B’, ‘C’, ‘E’});
    static String valueOf(Object)
    For Example:
     class Rect
              { int L=5, B=10;
               public String toString()
                 {
                   return(“L=” + L + “B=” + B + ” Area=” + L * B);
                 }
              }
        class demo{
              public static void main(String list[])
                { Rect r=new Rect();
             String s5 = String.valueOf(r);
             System.out.println(s5); //L = 5 B = 10 Area = 50.
                }
            }

java.lang.StringBuffer & StringBuilder Classes

The StringBuffer and StringBuilderclasses are like String class, but their objects are mutable, i.e., their contents can be modifi ed through certain method calls.
Overloaded forms of insert() and append() methods, provided in these classes make them more useful when regular changes are to be made in the character sequence. Its append() method adds characters at the end of the string and insert()method adds characters at the specifi ed index.
The StringBuff er class is a thread safe class. The methods of this class are synchronized, whereas StringBuilder class is not thread safe. The StringBuilder class should be preferred over StringBuff er class because it is faster than as it does not perform synchronization.

StringBuilder Constructors

  • StringBuilder()
  • It constructs an object without characters in it but creates an array of characters (char[] value) having room for 16 characters. A StringBuilder object also consists of a variable count, that tracks the number of characters the array consists of. It takes zero value by default. The value of count variable increases as the characters are inserted or appended in the array of characters (char[] value).
  • StringBuilder(int length)
  • It constructs an object without contents. The initial capacity is set to the length passed as argument.
  • StringBuilder(String str)
  • It constructs an object initialized to the contents of the specifi ed String argument. The initial capacity will be the length of String argument plus 16.
    For Example:
    StringBuilder s = new StringBuilder(“SST”);
    The initial capacity of object will be 19(3 + 16).

    StringBuilder Methods

    StringBuilder class provides some new methods to append, insert and delete characters in existing StringBuilder objects, which is not possible with String objects.

    Appending Characters:

    StringBuilder class provides various overloaded forms of append() method to add characters at the end of the array of characters.
    • StringBuilder append(String Str)
    • StringBuilder append(boolean b)
    • StringBuilder append(int i)
    • StringBuilder append(double d)
    • StringBuilder append(fl oat f)
    • StringBuilder append(char ch)
    • StringBuilder append(char ary)
    For Example:
    int i = 7;
    float f = 3.2f;
    char c = ‘A’;
    boolean b = true;
    char []ca = {‘A’, ‘B’, ‘C’};
    StringBuilder all = new StringBuilder(“*”);
    all.append(i);
    all.append(f).append(c).append(b).append(ca);
    all.append(“*”);
    System.out.println(all); //*73.2AtrueABC*
      

    Inserting Characters:

    StringBuilder class consists of some overloaded forms of insert() method.
    • StringBuilder insert (int pos, String str)
    • StringBuilder insert (int pos, char ch)
    • StringBuilder insert(int pos, boolean b)
    • StringBuilder insert(int pos, int i)
    • StringBuilder insert(int pos, char []c)
    • StringBuilder insert(int pos, double d)
    • StringBuilder insert(int pos, long l)
    • StringBuilder insert(int pos, byte)
    For Example:
         
         StringBuilder bl = new StringBuilder(“Java”);
         bl.insert(0, “Learn”);
         System.out.println(bl); // LearnJava
         bl.insert(5,'’); 
         System.out.println(bl); // Learn Java
         boolean t = true;
         int v = 6;
         bl.insert(5, t).insert(9, V);
         System.out.println(bl); //Learntrue6 Java
      

    Deleting Characters:

    StringBuilder class provides the following methods to delete the characters:
  • StringBuilder deleteCharAt (int index)
  • This method deletes a single character at specifi ed index given as an argument.
  • StringBuilder delete (int start, int end)
  • This method deletes all these characters from start index up to end-1 index.
    For Example:
     StringBuilder sb = new StringBuilder(“Java World”);
    sb.deleteCharAt(5);
    System.out.println(sb); //Java orld
    sb.delete(4, sb.length());
    System.out.println(sb); //Java

    Creating String object from StringBuilder object:

    The characters of StringBuilder object can be copied to String object using toString()method. The toString()method is also overridden in StringBuilder class. It returns a String object containing contents from StringBuilder object.
     StringBuilder sb = new StringBuilder(“Hello”);
       String s = sb.toString();
       System.out.println(s); //Hello

    Using equals( ) with StringBuilder objects:

    StringBuilder class does not override equals() method to match the characters of two objects. Therefore equals() method of StringBuilder objects checks the reference equality and not the content equality. So the contents of StringBuilder object should be converted to String object using toString() method. For Example:
    StringBuilder s1 = new StringBuilder(“Hello”);
    StringBuilder s2 = new StringBuilder(“Hello”);
    System.out.println(s1.toString().equals(s2.toString())); //true

About the Author
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
20 Years experience in Training & Development. Founder of realJavaOnline.com, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android,MERN Stack(MongoDB,Express,ReactJS,NodeJS). If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on amazon.in.
#Email : bcebti@gmail.com #Contact : 98722-46056
Available on Amazon
Card image cap
Under the guidance of Founder & Author of "realJavaOnline.com". M:9872246056
Card image cap