You are on page 1of 28

String

Compiled By:
Vinod Kumar
Assistant Professor
Computer Application Department
The String Class

 String objects are handled specially by the compiler.


 String is the only class which has "implicit" instantiation.

 The String class is defined in the java.lang package.

 Strings are immutable. The value of a String object can never be changed
but a new instance is created.
 For mutable Strings, use the StringBuffer/StringBuilder class.

www.cpur.in
Creating String Objects
 Generally, string is a sequence of characters. But in java, string is an object that
represents a sequence of characters. String class is used to create string object.
 Normally, objects in Java are created with the new keyword.

String name;
name = new String(“Avik");

 However, String objects can be created "implicitly":


String name= “Avik";

Strings can also be created using the + operator. The + operator, when applied to
Strings means concatenation.
int age = 21;
String message = “Avik wishes he was " + age + " years old";

www.cpur.in
Example By string literal
Each time you create a string literal, the
JVM checks the string constant pool first. If
the string already exists in the pool, a
reference to the pooled instance is
returned. If string doesn't exist in the pool,
a new string instance is created and placed
in the pool. For example:
public class StringExample{
public static void main(String args[]){ In the above example only one object will
String s1="Welcome"; be created. Firstly JVM will not find any
String s2="Welcome"; string object with the value "Welcome" in
System.out.println(s1); string constant pool, so it will create a new
object. After that it will find the string with
System.out.println(s2);
the value "Welcome" in the pool, it will not
}} create new object but will return the
reference to the same instance.

www.cpur.in
Example By new keyword
public 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);
}}

www.cpur.in
Commonly used String methods
 The String class has many methods. The most commonly used are:
 length() - returns the number of characters in the String

 charAt() - returns the character at the specified index

 equals() - returns true if two strings have equal contents

 compareTo() -returns 0 if equal, -# if one String is "less than” the other, +# if

one String is "greater than" the other.


 indexOf() - returns the index of specified String or character

 substring() -returns a portion of the String's text

 toUpperCase(), toLowerCase() - converts the String to upper or lower case

characters

www.cpur.in
Testing Strings for Equality

Important note: The == operator cannot be used to test String objects for
equality
Variables of type String are references to objects (ie. memory addresses)
Comparing two String objects using == actually compares their memory addresses. Two
separate String objects may contain the equivalent text, but reside at different memory
locations.

• Use the equals method to test for equality.

www.cpur.in
Immutable String in Java
In java, string objects are immutable. class Testimmutablestring1{  
Immutable simply means unmodifiable or  public static void main(String args[]){  
unchangeable.    String s="Sachin";  
Once string object is created its data or    s=s.concat(" Tendulkar");  
state can't be changed but a new string    System.out.println(s);  
object is created.
 }  
class Testimmutablestring{   } 
 public static void main(String args[]){  
   String s="Sachin";  
   s.concat(" Tendulkar");  
   System.out.println(s);   
 } } 
  

www.cpur.in
Java String compare
There are three ways to compare string in java:
By equals() method
By = = operator
By compareTo() method

www.cpur.in
String compare by equals() method
The String equals() method compares the original content of the string. It compares values of string for equality. String class provides two
methods:

public boolean equals(Object another) compares this string to the specified object.

public boolean equalsIgnoreCase(String another) compares this String to another string, ignoring case.

class Teststringcomparison1{  
 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  
 }  } 

www.cpur.in
String compare by equals() method
class Teststringcomparison2{  
 public static void main(String args[]){  
   String s1="Sachin";  
   String s2="SACHIN";  
  
   System.out.println(s1.equals(s2));//false  
   System.out.println(s1.equalsIgnoreCase(s3));//true  
 }  
}  

www.cpur.in
String compare by == operator
The = = operator compares references not values.
class Teststringcomparison3{  
 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 nonpool) 
}  

www.cpur.in
String compare by compareTo() method
The String compareTo() method compares values lexicographically and returns an integer value that
describes if first string is less than, equal to or greater than second string.
class Teststringcomparison4{  
 public static void main(String args[]){  
   String s1="Sachin";  
   String s2="Sachin";  
   String s3="Ratan";  
   System.out.println(s1.compareTo(s2));//0  
   System.out.println(s1.compareTo(s3));//1(because s1>s3)  
   System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )  
 }  
}  

www.cpur.in
String Concatenation in Java
string concatenation forms a new string that is the combination of multiple strings. There are two
ways to concat string in java:
By + (string concatenation) operator
By concat() method
Example
class TestStringConcatenation1{  
public static void main(String args[]){  
 String s="Sachin"+" Tendulkar";  
 System.out.println(s); 
 }  }
The Java compiler transforms above code to this:
String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();  

www.cpur.in
Example
class TestStringConcatenation2{  
public static void main(String args[]){  
   String s=50+30+"Sachin"+40+40;  
   System.out.println(s); 
 }  }
Note: After a string literal, all the + will be treated as string concatenation operator.

www.cpur.in
String Concatenation by concat() method
class TestStringConcatenation3{  

 public static void main(String args[]){  

   String s1="Sachin ";  

   String s2="Tendulkar";  

   String s3=s1.concat(s2);  

   System.out.println(s3);

 }  } 

www.cpur.in
Java String Buffer class
Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer
class in java is same as String class except it is mutable i.e. it can be changed.

Java StringBuffer class is thread-safe i.e. multiple threads cannot access it


simultaneously. So it is safe and will result in an order.

Important Constructors of StringBuffer class:

•StringBuffer(): creates an empty string buffer with the initial capacity of 16.

•StringBuffer(String str): creates a string buffer with the specified string.

•StringBuffer(int capacity): creates an empty string buffer with the specified capacity


as length.

www.cpur.in
Important methods of StringBuffer class
public synchronized StringBuffer append(String s): is used to append the
specified string with this string. The append() method is overloaded like
append(char), append(boolean), append(int), append(float), append(double) etc.
public synchronized StringBuffer insert(int offset, String s): is used to insert the
specified string with this string at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float),
insert(int, double) etc.
public synchronized StringBuffer replace(int startIndex, int endIndex, String
str): is used to replace the string from specified startIndex and endIndex.
public synchronized StringBuffer delete(int startIndex, int endIndex): is used to
delete the string from specified startIndex and endIndex.
public synchronized StringBuffer reverse(): is used to reverse the string.

www.cpur.in
Example
public int capacity(): is used to return the current capacity.
public void ensureCapacity(int minimumCapacity): is used to ensure the
capacity at least equal to the given minimum.
public char charAt(int index): is used to return the character at the specified
position.
public int length(): is used to return the length of the string i.e. total number of
characters.
public String substring(int beginIndex): is used to return the substring from the
specified beginIndex.
public String substring(int beginIndex, int endIndex): is used to return the
substring from the specified beginIndex and endIndex.

www.cpur.in
StringBuffer append() method
class A{   class A{  

public static void main(String args[]){   public static void main(String args[]){  

StringBuffer sb=new StringBuffer("Hello ");   StringBuffer sb=new StringBuffer("Hello ");  

sb.append("Java"); sb.insert(1,"Java");

//now original string is changed   //now original string is changed  

System.out.println(sb);//prints Hello Java   System.out.println(sb);//prints HJavaello  

}   }  

}  }
• StringBuffer insert() method

www.cpur.in
StringBuffer replace() method StringBuffer delete()
method
class A{  

class A{   public static void main(String args[]){  

public static void main(String args[]){   StringBuffer sb=new StringBuffer("Hello");  

StringBuffer sb=new StringBuffer("Hello");   sb.delete(1,3);  

sb.replace(1,3,"Java");   System.out.println(sb);//prints Hlo  

System.out.println(sb);//prints HJavalo   }  

}   }  

}  

www.cpur.in
StringBuffer reverse() method StringBuffer capacity() method
class A{  
class A{  
public static void main(String args[]){   public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello");   StringBuffer sb=new StringBuffer();  
System.out.println(sb.capacity());//default 16  
sb.reverse();  
sb.append("Hello");  
System.out.println(sb);//prints olleH   System.out.println(sb.capacity());//now 16  
}   sb.append("java is my favorite language");  
System.out.println(sb.capacity());
}
//now (16*2)+2=34 i.e (oldcapacity*2)+2  
•The capacity() method of StringBuffer class returns the
current capacity of the buffer. The default capacity of the }  
buffer is 16. If the number of character increases from its
current capacity, it increases the capacity by
(oldcapacity*2)+2. For example if your current capacity is 16,
}  
it will be (16*2)+2=34.

www.cpur.in
StringBuffer ensureCapacity() method
class A{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer();  
• The ensureCapacity() method of
System.out.println(sb.capacity());//default 16
StringBuffer class ensures that
the given capacity is the
sb.append("Hello");  
minimum to the current
System.out.println(sb.capacity());//now 16  
capacity. If it is greater than the
sb.append("java is my favourite language");   current capacity, it increases the
System.out.println(sb.capacity()); capacity by (oldcapacity*2)+2.
//now (16*2)+2=34 i.e (oldcapacity*2)+2 For example if your current
sb.ensureCapacity(10);//now no change   capacity is 16, it will be
System.out.println(sb.capacity());//now 34   (16*2)+2=34
sb.ensureCapacity(50);//now (34*2)+2  
System.out.println(sb.capacity());//now 70  
}  
}  

www.cpur.in
Java StringBuilder class
Java StringBuilder class is used to create mutable (modifiable) string. The Java
StringBuilder class is same as StringBuffer class except that it is non-synchronized.
It is available since JDK 1.5.

Important Constructors of StringBuilder class:

•StringBuilder(): creates an empty string Builder with the initial capacity of 16.

•StringBuilder(String str): creates a string Builder with the specified string.

•StringBuilder(int length): creates an empty string Builder with the specified


capacity as length.

www.cpur.in
Important methods of StringBuilder class

www.cpur.in
Important methods of StringBuilder class

www.cpur.in
Difference between String and StringBuffer

www.cpur.in
www.cpur.in

You might also like