Strings
Strings
String: String is a group of characters surrounded by double quotes, in java String class is used to
represent these group of characters.
Ex:
String s="sai"
1. Address of the object is assigned to the variable s. This object will be like a character array.
2. Once a string object is created, the data inside the object cannot be modified, that’s why
we say strings are immutable.
Different ways of creating String objects:
String s1=new String();
1. Using new keyword any number of objects are created for the same class.
String s1=new String("sai");
String s2=new String("sai");
The above statements will create two different objects, with different address(same
contents) assigned to different variable s1 and s2 respectively.
2. Assignment operator is used to assign the string to the variable s3. in this case, JVM first
of all checks whether the same object is already available in the string constant pool or not.
If it is available, then it creates another reference to it. If same object is not available, then
it creates another object with the with the content “PREM” and stores it into the string
constant pool.
String s3="sai”;
String s4="sai”;
1
Differences between String,StringBuffer,StringBuilder
Property String StringBuffer StringBuilder
Storage area Constant String pool Heap Heap
and
heap(when using new operator)
Object Mutability Not Mutabe Mutable Mutable
Thread Saftey Safe Safe Not safe
Performance Fast Slow fast
The Java String is immutable which means it cannot be changed. Whenever we change any
string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder
classes.
In Java, string is basically an object that represents sequence of char values. An array of characters works
same as Java string. For example:
String s1=”ALIET”;
Syntax: public final class String extends Object implements Serializable, Comparable,CharSequence
2
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
3.String(char[] value,int offset, int count) ex:String str=”ALIETCSE”; String str1=new String(str,0,4);
5.String(StringBuffer sb)
6.String(StringBuilder sb)
String concatenation:
Appending a string to another String is known as String concatenation. The
+ symbol acts as concatenation operator.
class SCat
{
public static void main (String args[])
{
String s1="eng";
s1=s1+" college";
System.out.println(s1);
}
}
We said that String objects immutable(contents of the object are not changed once created).
s1=s1+" Computers";
when this statement is executed a new string is created with the contents of LHS and RHS of the +
operator. And the old object will eligible for garbage collection.
3
Methods for Extracting Characters from Strings
The following methods are used to extract Characters from Strings
1. charAt()
2. getChars()
3. toCharArray()
4. getBytes()
1. equals()
2. compareTo()
Methods for Modifying Strings
The following methods are used to modify Strings
1. concat()
2. replace()
3. trim()
4. substring()
1. indexOf()
2. lastIndex()
3. charAt()
4. contains()
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. StringBuffer ( int size )
3. StringBuffer ( String str )
4. StringBuffer ( charSequence [ ]ch )
StringBuffer creates an empty string buffer and reserves room for 16 characters.
stringBuffer(int creates an empty string and takes an integer argument to set capacity of the
buffer.
class Test {
public static void main(String args[])
{
String str = "ALIET";
str.concat("CSE");
System.out.println(str); // Output: ALIET
The following methods are some most commonly used methods of StringBuffer class. append()
This method will concatenate the string representation of any type of data to the end of the invoking
StringBuffer object. append() method has several overloaded forms.
5
StringBuffer append(String str)
StringBuffer append(Object obj)
Output : test123
insert()
This method inserts one string into another. Here are few forms of insert() method.
Here the first parameter gives the index at which position the string will be inserted and string
representation of second parameter is inserted into StringBuffer object.
Output : test123
reverse()
replace()
This method replaces the string from specified start index to the end index.
capacity()
Output : 16
ensureCapacity()
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.
Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
Method Description
public StringBuilder It is used to append the specified string with this string.
append(String s) The append() method is overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.
public StringBuilder It is used to insert the specified string with this string at
insert(int offset, String s) 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 char charAt(int index) It is used to return the character at the specified position.
public int length() It is used to return the length of the string i.e. total
number of characters.
public String substring(int It is used to return the substring from the specified
beginIndex) beginIndex.
public String substring(int It is used to return the substring from the specified
beginIndex, int endIndex) beginIndex and endIndex.