Lab 7: String Manipulation in Java

String in Java

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings.

Creating Strings

/\*
The most direct way to create a string is to write:
\*/
String greeting = "Hello world!";

In this case, “Hello world!” is a string literal—a series of characters in your code that is 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, Hello world!.

/\*
As with any other object, you can create String objects by using the new keyword and a constructor. The String class has thirteen constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:
\*/
char\[\] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
//string creations with the help of Constructor
String helloString = new String(helloArray);
System.out.println(helloString);

Note: The String class is immutable so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.

Case 0: Basic understanding about String

// save as StringExample.java
class StringExample{
	public static void main(String args\[\]){
	String s1="java";  //creating string by java string literal  
                char ch\[\]={'s','t','r','i','n','g','s'};  
                String s2=new String(ch);          //converting char array to string  
                String s3=new String("example"); //creating java string by "new" keyword  
                System.out.println(s1);  
                System.out.println(s2);  
                System.out.println(s3); 
	}
} 
/\*
Output:
             F:\\coreJAVA\\12String>javac StringExample.java
             F:\\coreJAVA\\12String>java StringExample
             java
             strings
             example

\*/

Case 1: Create Immutable String in Java

// save as ImmutableString.java
class ImmutableString{  
 public static void main(String args\[\]){  
   String s="Sachin";  
   s.concat(" Tendulkar");   //concat() method appends the string at the end  
   System.out.println(s);   //will print Sachin because strings are immutable objects  
 }  
}  
/\*
Output:
             F:\\coreJAVA\\12String>javac ImmutableString.java
             F:\\coreJAVA\\12String>java ImmutableString
             Sachin
\*/

Case 2: Wap to make comparison between strings

// save as Stringcomparison1.java
class Stringcomparison1{  
 public static void main(String args\[\]){  
   String s1="Sachin";  
   String s2="Sachin";  
   String s3=new String("Sachin");  
   String s4="Saurav";  
   System.out.println(s1.equals(s2));   //true  
   System.out.println(s1.equals(s3));    //true  
   System.out.println(s1.equals(s4));    //false  
 }  
}  
/\*
Output:
             F:\\coreJAVA\\12String>javac Stringcomparison1.java
             F:\\coreJAVA\\12String>java Stringcomparison1
             true
             true
             false
\*/

Case 3: String Comparison 1

// save as Stringcomparison2.java
class Stringcomparison2{  
 public static void main(String args\[\]){  
   String s1="Sachin";  
   String s2="SACHIN";  
  
   System.out.println(s1.equals(s2));//  false   because its case sensitive
   System.out.println(s1.equalsIgnoreCase(s2));//true   because case sensitive avoided by method
 }  
}  
/\*
Output:
             F:\\coreJAVA\\12String>javac Stringcomparison2.java
             F:\\coreJAVA\\12String>java Stringcomparison2
             false
             true
\*/

Case 4: String Comparison 2

//save as Stringcomparison3.java
class Stringcomparison3{  
 public static void main(String args\[\]){  
   String s1="Sachin";  
   String s2="Sachin";  
   String s3=new String("Sachin");  
   System.out.println(s1==s2);     //true (because both refer to same instance)  
   System.out.println(s1==s3);     //false(because s3 refers to instance created in non pool)  
 }  
}  

/\*
Output:
             F:\\coreJAVA\\12String>javac Stringcomparison3.java
             F:\\coreJAVA\\12String>java Stringcomparison3
             true
             false
\*/

Case 5: String Comparison 3

// save as Stringcomparison4.java
class Stringcomparison4{  
 public static void main(String args\[\]){  
   String s1="Sachin";  
   String s2="Sachin";  
   String s3="Ratan";  
   System.out.println(s1.compareTo(s2));   //0  (because s1==s2)
   System.out.println(s1.compareTo(s3));    //1(because s1>s3)  
   System.out.println(s3.compareTo(s1));    //-1(because s3 < s1 )  
 }  
}
/\*
Output:
             F:\\coreJAVA\\12String>javac Stringcomparison4.java
             F:\\coreJAVA\\12String>java Stringcomparison4
             0
             1
             -1
\*/

Case 6: String Concatenation

// save as StringConcatenation1.java
class StringConcatenation1{  
 public static void main(String args\[\]){  
   String s="Sachin"+" Tendulkar"; // “ +  “ is concate  operator 
   System.out.println(s);  //Sachin Tendulkar  
                }  
}  
/\*
Output:
             F:\\coreJAVA\\12String>javac StringConcatenation1.java
             F:\\coreJAVA\\12String>java StringConcatenation1
             Sachin Tendulkar
\*/

Case 7: Use of concat method

// save as StringConcatenation3.java
class StringConcatenation3{  
 public static void main(String args\[\]){  
   String s1="Sachin ";  
   String s2="Tendulkar";  
   String s3=s1.concat(s2);     // concat() is method which append another string to current string
   System.out.println(s3);    //Sachin Tendulkar  
  }  
}  
/\*
Output:
             F:\\coreJAVA\\12String>javac StringConcatenation3.java
             F:\\coreJAVA\\12String>java StringConcatenation3
             Sachin Tendulkar
\*/

Case 8: Print the sub string of strings

//save as Substring.java
class Substring{  
 public static void main(String args\[\]){  
   String s="SachinTendulkar";  
   System.out.println(s.substring(6));  //after skipping 6 character remaining will be printed
   System.out.println(s.substring(0,6));    //StartIndex: inclusive , EndIndex: exclusive
 }  
}  
/\*
Output:
             F:\\coreJAVA\\12String>javac Substring.java
             F:\\coreJAVA\\12String>java Substring
             Tendulkar
             Sachin
\*/

Implementation of String’s Methods in Java

Method 1:

//save as Methodofstringclass.java
class Methodofstringclass{
 public static void main(String args\[\]){
  String s="Sachin";
   System.out.println(s.toUpperCase());      //SACHIN
   System.out.println(s.toLowerCase());     //sachin
   System.out.println(s);  } //Sachin(no change in original) 
}
/\*
Output:
             F:\\coreJAVA\\12String\\method of string>javac Methodofstringclass.java
             F:\\coreJAVA\\12String\\method of string>java Methodofstringclass
             SACHIN
             sachin
             Sachin
\*/

Method 2:

// save as Methodofstringclass1.java
class Methodofstringclass1{
 public static void main(String args\[\]){
   String s="  Sachin  ";
   System.out.println(s);                //Sachin  
   System.out.println(s.trim());    //Sachin
 }
}
/\*
Output:
             F:\\coreJAVA\\12String\\method of string>javac Methodofstringclass1.java
             F:\\coreJAVA\\12String\\method of string>java Methodofstringclass1
             Sachin
             Sachin
\*/

Method 3:

//save as Methodofstringclass2.java
class Methodofstringclass2{
 public static void main(String args\[\]){
   String s="Sachin";
   System.out.println(s.startsWith("Sa"));//true
   System.out.println(s.endsWith("n"));//true
 }
}
/\*
Output:
             F:\\coreJAVA\\12String\\method of string>javac Methodofstringclass2.java
             F:\\coreJAVA\\12String\\method of string>java Methodofstringclass2
             true
             true
\*/

Method 4:

// save as Methodofstringclass3.java
public class Methodofstringclass3{
 public static void main(String args\[\]){
 
   String s="Sachin";
   System.out.println(s.charAt(0)); //S
   System.out.println(s.charAt(3)); //h
 }
}
/\*
Output:
             F:\\coreJAVA\\12String\\method of string>javac Methodofstringclass3.java
             F:\\coreJAVA\\12String\\method of string>java Methodofstringclass3
             S
             h
\*/

Method 5:


//save as Methodofstringclass4.java
public class Methodofstringclass4{
 public static void main(String args\[\]){
 
   String s="Sachin";
   System.out.println(s.length());//6
  }
  }
/\*
Output:
             F:\\coreJAVA\\12String\\method of string>javac Methodofstringclass4.java
             F:\\coreJAVA\\12String\\method of string>java Methodofstringclass4
             6
\*/

Method 7:

// save as Methodofstringclass5.java
public class Methodofstringclass5{
 public static void main(String args\[\]){
 
   String s=new String("Sachin");
   /\*//When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.\*/
   String s2=s.intern();     
   System.out.println(s2); //Sachin
  }
}
/\*
Output:
             F:\\coreJAVA\\12String\\method of string>javac Methodofstringclass5.java
             F:\\coreJAVA\\12String\\method of string>java Methodofstringclass5
             Sachin
\*/

Method 8:

// save as Methodofstringclass6.java
class Methodofstringclass6{
	public static void main(String args\[\]){
		int a=10;
		String s=String.valueOf(a);
		System.out.println(s+10);
	}
}
/\*
Output:
             F:\\coreJAVA\\12String\\method of string>javac Methodofstringclass6.java
             F:\\coreJAVA\\12String\\method of string>java Methodofstringclass6
             1010
\*/

Method 9:

// svae as ReplaceMethod.java
class ReplaceMethod{
	public static void main(String args\[\]){
		String s="Java is the best ,Java is a platform independent. Java is an Island.";
		String replacestr=s.replace("Java","Health"); // Java is replaced by Health 
		System.out.println(replacestr);
	}
}
/\*
Output:
             F:\\coreJAVA\\12String\\method of string>javac ReplaceMethod.java
             F:\\coreJAVA\\12String\\method of string>java ReplaceMethod
             Health is the best, Heath is a platform independent. Heath is an Island of smart people.
\*/

How to create Mutable String in Java

Java StringBuffer class is used to create a mutable (modifiable) string. The StringBuffer class in java is the same as the String class except it is mutable i.e. it can be changed.

Case 0: Creation of Mutable strings

//save as StringBufferExample.java
class StringBufferExample{  
public static void main(String args\[\]){  
StringBuffer sb=new StringBuffer("Hello ");  
sb.append("Java");  //now original string is changed  
System.out.println(sb);  //prints Hello Java  
}  
}  
/\*
Output:
             F:\\coreJAVA\\12String>javac StringBufferExample.java
             F:\\coreJAVA\\12String>java StringBufferExample
             Hello Java
\*/

Various Operations on Mutable Strings

//Insert() method:
class StringBufferExample2{  
	public static void main(String args\[\]){  
		StringBuffer sb=new StringBuffer("Hello ");  
		// inserts the given string with this string at the given position.
		sb.insert(1,"Java");
		System.out.println(sb);//prints HJavaello  
	}  
}  

//delete() method: 
class StringBufferExample4{  
	public static void main(String args\[\]){  
		StringBuffer sb=new StringBuffer("Hello"); 
		// deletes the string from the specified beginIndex to endIndex.
		sb.delete(1,3);  
		System.out.println(sb);//prints Hlo  
	}   
}

//Reverse() method:
class StringBufferExample5{  
	public static void main(String args\[\]){  
		StringBuffer sb=new StringBuffer("Hello");  
		sb.reverse();  // reverses the current string.
		System.out.println(sb);  //prints olleH  
	}  
}  

//Capacity() method 
class StringBufferExample6{  
	public static void main(String args\[\]){  
		StringBuffer sb=new StringBuffer();  
		System.out.println(sb.capacity());//default 16  
		sb.append("Hello");  
		System.out.println(sb.capacity());//now 16  
		sb.append("java is my favourite language");  
		System.out.println(sb.capacity());//now (16\*2)+2=34 i.e (oldcapacity\*2)+2  
	}  
}  
/\*
Output:
	  F:\\coreJAVA\\12String\\StringBuffer>javac StringBufferExample6.java
	  F:\\coreJAVA\\12String\\StringBuffer>java StringBufferExample6
	  16
	  16
	  34
\*/
//EnsureCapacity() method:
class StringBufferExample7{  
	public static void main(String args\[\]){  
		StringBuffer sb=new StringBuffer();  
		System.out.println(sb.capacity());    //default 16  
		sb.append("Hello");  
		System.out.println(sb.capacity());   //now 16  
		sb.append("java is my favourite language");  
		System.out.println(sb.capacity()); //now (16\*2)+2=34 i.e (oldcapacity\*2)+2  
		sb.ensureCapacity(10);   //now no change  
		System.out.println(sb.capacity());  //now 34  
		sb.ensureCapacity(50);   //now (34\*2)+2  
		System.out.println(sb.capacity());  //now 70  
	}  
}  
/\*
Output:
	   F:\\coreJAVA\\12String\\StringBuffer>javac StringBufferExample7.java
	   F:\\coreJAVA\\12String\\StringBuffer>java StringBufferExample7
	   16
	   16
	   34
	   34
	   70
\*/

String Builder in Java

In java StringBuilder class is used to create a mutable (modifiable) string. All the methods of StringBuilder class are the same as the methods of the StringBuffer class. The main difference between them is, methods of StringBuffer are sync synchronized whereas methods of StringBuilder re not synchronized.

// save as StringBuilderExample.java
class StringBuilderExample{  
	public static void main(String args\[\]){ 
		// Creating a object of StringBuilder class
		StringBuilder sb=new StringBuilder("Hello ");  
		sb.append("Java");//now original string is changed  
		System.out.println(sb);//prints Hello Java  
	}  
}
/\*
Output:
	     javac StringBuilderExample.java
	     java StringBuilderExample
	     Hello Java
\*/

insert() method of StringBuilder :

// save as StringBuilderExample2.java
class StringBuilderExample2 {
	public static void main(String args\[\]) {
		StringBuilder sb = new StringBuilder("Hello ");
		sb.insert(1, "Java"); // now original string is changed
		System.out.println(sb); // prints HJavaello
	}
}
/\*
Output:
	     javac StringBuilderExample2.java
	     java StringBuilderExample2
	     HJavaello
\*/

Test: Find out which one is fast String or StringBuffer

// save as ConcatTest.java

class ConcatTest{  
    public static String concatWithString()    {  
        String t = "Java";  
        for (int i=0; i<10000; i++){  
            t = t + "Tpoint";  
        }  
        return t;  
    }  
    public static String concatWithStringBuffer(){  
        StringBuffer sb = new StringBuffer("Java");  
        for (int i=0; i<10000; i++){  
            sb.append("Tpoint");  
        }  
        return sb.toString();  
 }  
    public static void main(String\[\] args){  
        long startTime = System.currentTimeMillis();  // calculate the time
        concatWithString();  
        System.out.println("Time is taken by Concating with String: "+(System.currentTimeMillis()- 
        startTime)+"ms");  
        startTime = System.currentTimeMillis();  
        concatWithStringBuffer();  
        System.out.println("Time is taken by Concating with  StringBuffer: "+(System.currentTimeMillis()- 
        startTime)+"ms");  
    }  
}  

Output

F:\\coreJAVA\\image>javac ConcatTest.java
F:\\coreJAVA\\image>java ConcatTest
Time is taken by Concating with String: 811ms
Time is taken by Concating with StringBuffer: 1ms
F:\\coreJAVA\\image>java ConcatTest
Time is taken by Concating with String: 727ms
Time is taken by Concating with StringBuffer: 1ms