You are on page 1of 9

String Handling in Java:

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();

String s2=new String("sai");


String s3="sai";
Difference between new and " "

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

Interface Char Sequence:


The CharSequence interface is used to represent the sequence of characters. String,
StringBuffer and StringBuilder classes implement it. It means, we can create strings in Java by using
these three classes.

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.

Modifier and Type Method and Description


Char charAt(int index)
Returns the char value at the specified index.
Int length()
Returns the length of this character sequence.
CharSequence subSequence(int start, int end)
Returns a CharSequence that is a subsequence of this sequence.
String toString()
Returns a string containing the characters in this sequence in the same order
as
this sequence
Boolean Equal()
Example:
Class String:

In Java, string is basically an object that represents sequence of char values. An array of characters works
same as Java string. For example:

Charch[]={‘A’,’L’,’I’,’E’,’T’}; String s1=new String(ch);

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.

How to create a string object?

There are two ways to create String object:

1.By string literal—ex: String s="welcome";


2.By new keyword-ex: String s=new String("Welcome");

Constructors of String class:

1.String() ex:String str=new Strig();

2.String(char[] value)ex:char ch[]={‘a’,’l’,’I’,’e’,’t’}; String str=new Strinh(ch);

3.String(char[] value,int offset, int count) ex:String str=”ALIETCSE”; String str1=new String(str,0,4);

4.String (String originalString)ex:String str=new String(“ALIET”);

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()

Methods for Comparison of Strings


The following methods are used to compare Strings

1. equals()
2. compareTo()
Methods for Modifying Strings
The following methods are used to modify Strings

1. concat()
2. replace()
3. trim()
4. substring()

Methods for Searching Strings


The following methods are used searching Strings

1. indexOf()
2. lastIndex()
3. charAt()
4. contains()

Data Conversion and Miscellaneous Methods

Exceptions thrown by string class methods:


1.IndexOutOfBoundsException:
1.charAt(int index),2.codepoint(int index)3.getchar()4.subString(int beginindex)5.subSequence(int indexbegin,int
indexend)
2.UnSupportedEncodingException: getBytes()
3.PatternSyntaxException:
1.Matches(String Regularexpression) 2.repalceAll(String Regularexpression,String Replacement)
3.Split(String Regularexpression)
4
4.NullPointerException:
1.contains(CharSequence cseq) 2.format(Striing format)3.replace(CharSequence current,CharSequence
replacement)

StringBuffer class in Java

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.

Example showing difference between String and StringBuffer

class Test {
public static void main(String args[])
{
String str = "ALIET";
str.concat("CSE");
System.out.println(str); // Output: ALIET

StringBuffer strB = new StringBuffer("ALIET");


strB.append("CSE");
System.out.println(strB); // Output: ALIETCSE
}
}

Important methods of StringBuffer class

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)

The string representation of each parameter is appended to StringBuffer object.

StringBuffer str = new StringBuffer("test");


str.append(123);
System.out.println(str);

Output : test123

insert()

This method inserts one string into another. Here are few forms of insert() method.

StringBuffer insert(int index, String str)

StringBuffer insert(int index, int num)

StringBuffer insert(int index, Object obj)

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.

StringBuffer str = new StringBuffer("test");


str.insert(4, 123);
System.out.println(str);

Output : test123

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);

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

Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.

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

StringBuilder(int It creates an empty String Builder with the specified capacity as


length) length.

Important methods of StringBuilder class

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 StringBuilder It is used to replace the string from specified startIndex


replace(int startIndex, int and endIndex.
endIndex, String str)

public StringBuilder It is used to delete the string from specified startIndex


delete(int startIndex, int and endIndex.
endIndex)

public StringBuilder It is used to reverse the string.


reverse()

public int capacity() It is used to return the current capacity.

public void It is used to ensure the capacity at least equal to the


ensureCapacity(int given minimum.
minimumCapacity)

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.

You might also like