Introduction To String Handling
Introduction To String Handling
String is probably the most commonly used class in java library. String class is encapsulated
underjava.lang package. In java, every string that you create is actually an object of type String.
One important thing to notice about string object is that string objects are immutable that means
once a string object is created it cannot be altered.
String can be created in number of ways, here are a few ways of creating string object.
Each time you create a String literal, the JVM checks the string pool first. If the string literal already
exists in the pool, a reference to the pool instance is returned. If string does not exist in the pool, a
new string object is created, and is placed in the pool. String objects are stored in a special memory
area known as string constant pool inside the heap memory.
And, when we create another object with same string, then a reference of the string literal already
present in string pool is returned.
String str2=str;
str2=str2.concat("world");
Concatenating String
There are 2 methods to concatenate two or more string.
1.
2.
Using + operator
2) Using + operator
string str = "Rahul";
string str1 = "Dravid";
string str2 = str + str1;
string st = "Rahul"+"Dravid";
String Comparison
String comparison can be done in 3 ways.
1.
2.
Using == operator
3.
By CompareTo() method
//true
s.equals(s1) ; //false
Using == operator
== operator compares two object references to check whether they refer to same instance. This
also, will return true on successful match.
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(Sl == s2)
//true
test(s1 == s3)
//false
By compareTo() method
compareTo() method compares values and returns an int which tells if the string compared is less
than, equal to or greater than th other string. Its general syntax is,
int compareTo(String str)
To use this function you must implement the Comparable Interface. compareTo() is the only
function in Comparable Interface.
String s1 = "Abhi";
String s2 = "Viraaj";
String s3 = "Abhi";
s1.compareTo(S2);
s1.compareTo(S3);
//return 0 because s1 == s3
s2.compareTo(s1);
charAt()
charAt() function returns the character located at the specified index.
String str = "studytonight";
System.out.println(str.charAt(2));
Output : u
equalsIgnoreCase()
equalsIgnoreCase() determines the equality of two Strings, ignoring thier case (upper or lower case
doesn't matters with this fuction ).
String str = "java";
System.out.println(str.equalsIgnoreCase("JAVA"));
Output : true
length()
length() function returns the number of characters in a String.
String str = "Count me";
System.out.println(str.length());
Output : 8
replace()
replace() method replaces occurances of character with a specified new character.
String str = "Change me";
System.out.println(str.replace('m','M'));
Output : Change Me
substring()
substring() method returns a part of the string. substring() method has two forms,
public String substring(int begin);
But, if the call to substring() method has two arguments, the second argument specify the end point
of substring.
String str = "0123456789";
System.out.println(str.substring(4));
Output : 456789
System.out.println(str.substring(4,7));
Output : 456
toLowerCase()
toLowerCase() method returns string with all uppercase characters converted to lowercase.
String str = "ABCDEF";
System.out.println(str.toLowerCase());
Output : abcdef
valueOf()
Overloaded version of valueOf() method is present in String class for all primitive data types and for
type Object.
NOTE : valueOf() function is used to convert primitive data types into Strings.
But for objects, valueOf() method calls toString() function.
toString()
toString() method returns the string representation of the object used to invoke this
method. toString() is used to represent any Java Object into a meaningful string representation. It is
declared in the Object class, hence can be overrided by any java class. (Object class is super class
of all java classes.)
public class Car {
toUpperCase()
This method returns string with all lowercase character changed to uppercase.
String str = "abcdef";
System.out.println(str.toUpperCase());
Output : ABCDEF
trim()
This method returns a string from which any leading and trailing whitespaces has been removed.
String str = " hello ";
System.out.println(str.trim());
Output : hello
StringBuffer class
StringBuffer class is used to create a mutable string object. It represents growable and writable
character sequence. As we know that String objects are immutable, so if we do a lot of changes
with String objects, we will end up with a lot of memory leak.
So StringBuffer class is used when we have to make lot of modifications to our string. It is also
thread safe i.e multiple threads cannot access it simultaneously. StringBuffer defines 4 constructors.
They are,
1.
StringBuffer ( )
2.
3.
4.
StringBuffer() creates an empty string buffer and reserves room for 16 characters.
stringBuffer(int size) creates an empty string and takes an integer argument to set
capacity of the buffer.
// Output: study
// Output: studytonight
}
}
append()
This method will concatenate the string representation of any type of data to the end of the
invokingStringBuffer object. append() method has several overloaded forms.
StringBuffer append(String str)
StringBuffer append(int n)
insert()
This method inserts one string into another. Here are few forms of insert() method.
StringBuffer insert(int index, String str)
reverse()
This method reverses the characters within a StringBuffer object.
StringBuffer str = new StringBuffer("Hello");
str.reverse();
System.out.println(str);
Output : olleH
replace()
This method replaces the string from specified start index to the end index.
StringBuffer str = new StringBuffer("Hello World");
str.replace( 6, 11, "java");
System.out.println(str);
Output : Hello java
capacity()
This method returns the current capacity of StringBuffer object.
StringBuffer str = new StringBuffer();
System.out.println( str.capacity() );
Output : 16
ensureCapacity()
This method is used to ensure minimum capacity of StringBuffer object.
StringBuffer str = new StringBuffer("hello");
str.ensureCapacity(10);
StringBuilder class
StringBuilder is identical to StringBuffer except for one important difference it is not synchronized,
which means it is not thread safe. Its because StringBuilder methods are not synchronised.
StringBuilder Constructors
1.
2.
StringBuilder ( int size ), create an empty string and takes an integer argument to set
capacity of the buffer.
3.
StringBuilder ( String str ), create a StringBuilder object and initialize it with string str.
StringBuilder class
StringBuffer is synchronized.
StringBuilder is not
synchronized.
Example of StringBuilder
class Test {
public static void main(String args[])
{
StringBuilder str = new StringBuilder("study");
str.append( "tonight" );
System.out.println(str);
str.replace( 6, 13, "today");
System.out.println(str);
str.reverse();
System.out.println(str);
str.replace( 6, 13, "today");
}
}
Output :
studytonight
studyttoday
yadottyduts