0% found this document useful (0 votes)
5 views112 pages

Module 2

The document provides an overview of string handling in Java, including the creation of string objects using constructors and string literals, as well as methods for string concatenation, comparison, and character extraction. It covers various string methods such as equals(), compareTo(), charAt(), and getChars(), along with examples demonstrating their usage. Additionally, it explains the toString() method and how to represent objects as strings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views112 pages

Module 2

The document provides an overview of string handling in Java, including the creation of string objects using constructors and string literals, as well as methods for string concatenation, comparison, and character extraction. It covers various string methods such as equals(), compareTo(), charAt(), and getChars(), along with examples demonstrating their usage. Additionally, it explains the toString() method and how to represent objects as strings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 112

Dept.

of ISE
Department of Information Science &
Engineering
Advance Java BIS402
Faculty: Sahibdeep Singh
Module 2- String Handling

STRING
 object that represents sequence of
char values.
 Present in a package called
Dept. of ISE java.lang.String
 For example:
char[] ch={‘C’,’S’,’E’};
String s=new String(ch);

Is same as:
String s=“CSE”
String Constructors

1. String();
2. String(char chars[ ])
3. String(char chars[ ], int startIndex, int
Dept. of ISE
numChars)
4. String(byte asciiChars[ ])
5. String(byte asciiChars[ ], int startIndex,
int numChars)
String class supports several
constructors.
 To create an empty String, we call the
default constructor.
Dept. of ISE  For example,
String s = new String();
will create an instance of String with no
characters in it.
To create a String initialized by an array
of characters, use the constructor shown
here:
String(char chars[ ])
Dept. of ISE Here is an example:
char[] chars = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the
string “abc”.
•We can specify a subrange of a character array as
an initializer using the following constructor:
String(char chars[ ], int startIndex, int
numChars)
 startIndex specifies the index at which the
subrange begins

Dept. of ISE
numChars specifies the number of
characters to use.
Example:
char[] chars = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes s with the characters cde.
String class provides constructors that

initialize a string when given a byte array.

Their forms are shown here:

Dept. of ISE • String(byte asciiChars[ ])

• String(byte asciiChars[ ], int

startIndex, int numChars)


EXAMPLE

class SubStringCons {
public static void main(String args[]) {
byte[] ascii = {65, 66, 67, 68, 69, 70 }; Output:

ABCDEF
String s1 = new String(ascii);
CDE
Dept. of ISE
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
How to create String object?

Two ways to create String object:


 By string literal
 By new keyword

Dept. of ISE
String Literal

• Is created by using double quotes.

• For Example:

String s="welcome";

Dept. of ISE
 String s1="Welcome";

 String s2="Welcome“;

Dept. of ISE

Presented By: Pankaj Kumar


By new keyword

public class StringExample


{
public static void main(String args[]) {
String s1="java“;
char ch[]={'s','t','r','i','n','g','s'};
Dept. of ISE
String s2=new String(ch);
String s3=new String("example");
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
String Concatenation in Java

•String concatenation forms a new string


that is the combination of multiple strings.
•Two ways to concat string in java:
1. B y + ( s t r i n g c o n c a t e n a t i o n )
Dept. of ISE operator
2. By concat() method
By + (string concatenation) operator

Example:

String s=“ACIT"+“Engineering";
System.out.println(s);
Dept. of ISE
Output:
ACIT Engineering
Guess the answer

String s=50+30+“CSE"+40+40;
System.out.println(s);

Output:
80CSE4040
Dept. of ISE
Note: After a string literal, all the + will be
treated as string concatenation operator.
String Concatenation by concat()

String s1=“Acharya ";


String s2=“ Institute";
String s3=s1.concat(s2);
System.out.println(s3);
Dept. of ISE

Output:
Acharya Institute
Java toString() method

 If you want to represent any object as a


string, toString() method comes into
existence.
 toString() method returns the string
Dept. of ISE representation of the object.
Understanding problem without toString()

class Student{
int rollno;
String name;
String city;

Student(int rollno, String name, String city)


{
this.rollno=rollno;
this.name=name;
this.city=city;
}

Dept. of ISE public static void main(String args[]){


Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay",“Bengaluru");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}

Output:
Student@1fee6fc
Student@1eed786
Example of Java toString() method

class Student{
int rollno;
String name;
String city;

Student(int rollno, String name, String city)


{ Output:
this.rollno=rollno; 101 Raj lucknow
this.name=name;
this.city=city; 102 Vijay Bengaluru
}

Dept. of ISE
public String toString()
{
return rollno+" "+name+" "+city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay",“Bengaluru");
System.out.println(s1);
System.out.println(s2);
}
}
Dept. of ISE
Character Extraction
Java String charAt()

•String charAt() method returns a char value at the given index


number.
•It has this general form:
char charAt(int where)
Here, where is the index of the character that we want to obtain
Dept. of ISE •Index number starts from 0 and goes to n-1, where n is length of the
string
•returns StringIndexOutOfBoundsException if given index number is
greater than or equal to this string length or a negative number.
Example

public class CharAtExample {


public static void main(String args[]) Output:
r
{
String name=“Acharya";
Dept. of ISE char ch=name.charAt(4);
System.out.println(ch);
} }
getChars()

Method copies the content of this string into specified


char array.
To extract more than one character at a time, we can
use the getChars( ) method.
Dept. of ISE Syntax
void getChars(int sourceStart, int sourceEnd, char target[ ],
int targetStart)
Parameters description:

sourceStart – index of the first character in the string to


copy.
sourceEnd – index after the last character in the string to
copy.
Dept. of ISE
target – Destination array of characters in which the
characters from String gets copied.
targetStart – The index in Array starting from where the
chars will be pushed into the Array.
Example

public class StringGetCharsExample {


public static void main(String args[]) {
String str = new String(“Hello Kumar how r
u"); Output:
char[] ch = new char[10]; Kumar how

Dept. of ISE
try{
str.getChars(6, 16, ch, 0);
System.out.println(ch);
}catch(Exception ex)
{ System.out.println(ex); }
}}
Example

String str=new String("Hello Engg how r u");


char[]ch=new char[10];
Output:
ch[0]='a'; aEngg

ch[1]='b';
Dept. of ISE try{
str.getChars(6,10,ch,1);
System.out.println(ch);}
catch(Exception ex){ System.out.println(ex
); }
Example:
String str=new String("Hello Kumar how r u");
char[] ch=new char[10];
ch[0]='a';
Output:
ch[1]='b'; abKuma
K
try
Dept. of ISE {
str.getChars(6,10,ch,4);
System.out.println(ch);
System.out.println(ch[4]);
}catch(Exception ex)
{ System.out.println(ex); }
String getBytes()

•getBytes() method returns the byte array of


the string.
•its simplest form:
byte[ ] getBytes( )
Dept. of ISE
Example

String s1="ABCDEFG";
byte[] barr=s1.getBytes(); Output:
65
for(int i=0;i<barr.length;i++)
66
Dept. of ISE { 67
68
System.out.println(barr[i]); 69
70
} 71
String toCharArray

 toCharArray() method converts this


string into character array
 returns a newly created character array,
its length is similar to this string
Dept. of ISE  syntax
public char[] toCharArray()
Example

String s1="hello";
char[] ch=s1.toCharArray();
Output:
for(int i=0;i<ch.length;i++) { h
e
l
System.out.println(ch[i]); } l
o

Dept. of ISE
String Comparison

Dept. of ISE
There are three ways to compare string in
java:

 By equals() method
Dept. of ISE  By = = operator
 By compareTo() method
1) String compare by equals()

 Compares values of string for equality.


 String class provides two methods:
I. public boolean equals(String
str)
Dept. of ISE II. p u b l i c b o o l e a n
equalsIgnoreCase(String str)
Example for equals

String s1=“Kumar";
String s2=“Kumar";
String s3=new String(“Kumar");
String s4=“Atlas";
System.out.println(s1.equals(s2));
Dept. of ISE
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));

Output
true
true
false
Example for equalsIgnoreCase

String s1=“Kumar";
String s2=“KUMAR";
System.out.println(s1.equals(s2))
System.out.println(s1.equalsIgnoreCase(s
Dept. of ISE 2));

Output:
false
true
Example for equals and equalsIgnoreCase
class equalsDemo {
public static void main(String args[]) Output:
Hello equals Hello -> true
{ Hello equals Good-bye -> false
String s1 = "Hello"; Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +s1.equals(s3));
Dept. of ISE
System.out.println(s1 + " equals " + s4 + " -> " +s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> "
+s1.equalsIgnoreCase(s4));
}
}
2) String compare by == operator

The == operator compares two object references to

see whether they refer to the same instance

The = = operator compares references not values.

Dept. of ISE
Example for compare by == operator

class Teststringcomparison3{
public static void main(String args[]){
Output:
true
String s1=“Kumar"; false

String s2=“Kumar";
Dept. of ISE String s3=new String(“Kumaa");
System.out.println(s1==s2);
System.out.println(s1==s3);
} }
Example for equals() vs ==
Output:
Hello equals Hello ->
class Demo1 true
Hello == Hello ->
false
public static void main(String args[])
{
String s1 = "Hello";
Dept. of ISE String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -
> " +s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " +
(s1 == s2));
}}
3) String compare by compareTo() method

Compares values lexicographically and returns an


integer value that describes if f ir st string is less
than, equal to or greater than second string
It has this general form:
int compareTo(String str).
Dept. of ISE
str is the String being compared with the
invoking String
Suppose s1 and s2 are two string variables. If:
 s1 == s2 :0
 s1 > s2 :positive value
 s1 < s2 :negative value
Example

String s1="Sachin";
String s2="Sachin"; Output:
0
1
String s3="Ratan"; -1

System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));
Dept. of ISE
System.out.println(s3.compareTo(s1));
Example

Output:
• 0 because both are equal
String s1="hello"; • -5 because "h" is 5 times lower tha
n "m"
• -1 because "l" is 1 times lower than
String s2="hello"; "m"
• 2 because "h" is 2 times greater ”f"
String s3="mello";
String s4="hemlo";
Dept. of ISE
String s5="flag";
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));
System.out.println(s1.compareTo(s4));
System.out.println(s1.compareTo(s5));
Example

String s1="Sachin";
String s2="sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2)); Output:
-32
Dept. of ISE System.out.println(s1.compareTo(s3)); 1
-1

System.out.println(s3.compareTo(s1));
Java String compareTo(): empty string

If you compare string with blank or empty


string, it returns length of the string.
If second string is empty, result would be
positive. If first string is empty, result would
Dept. of ISE be negative.
public class CompareToExample2{
Output:
5
public static void main(String args[]) -2

{
String s1="hello";
Dept. of ISE String s2="";
String s3="me";
System.out.println(s1.compareTo(s2));
System.out.println(s2.compareTo(s3));
}}
String startsWith

 Checks if this string starts with given prefix.


 Returns true if this string starts with given
prefix else returns false
 syntax
Dept. of ISE public boolean startsWith(String prefix)
Example

String s1="java string split method";


System.out.println(s1.startsWith("ja"));
System.out.println(s1.startsWith("java strin
g"));
Dept. of ISE

Output:
true
true
String endsWith

 Checks if this string ends with given


suffix.
 Returns true if this string ends with given
suffix else returns false.
Dept. of ISE syntax
public boolean endsWith(String su
ffix)
Example:

String s1=“Acharya Institute of technology";


System.out.println(s1.endsWith(“yt”));
System.out.println(s1.endsWith("technolog
y"));
Dept. of ISE
Output:
false
true
Dept. of ISE
Searching String
String indexOf

 Returns index of given character value


or substring.
 If it is not found, it returns -1.
 The index counter starts from zero.
Dept. of ISE
4 types of indexOf method in java.

No. Method Description

1 int indexOf(char ch) returns index position for the


given char value

2 int indexOf(char ch, int startIndex) returns index position for the
given char value and from
index
Dept. of ISE
3 int indexOf(String substring) returns index position for the
given substring

4 int indexOf(String substring, int returns index position for the


startIndex) given substrin g an d from
index
Example

String s1="this is index of example";


Output:
int index1=s1.indexOf("is"); 2 8
5
int index2=s1.indexOf("index"); 3

System.out.println(index1+" "+index2);
Dept. of ISE int index3=s1.indexOf("is",4);
System.out.println(index3);
int index4=s1.indexOf('s');
System.out.println(index4);
Java String lastIndexOf

 Returns last index of the given


character value or substring.
 If it is not found, it returns -1.
 Index counter starts from zero.
Dept. of ISE
N Method Description
o.

1 int lastIndexOf(int ch) returns last index position for the


given char value

2 i n t l a s t I n d e x O f ( i n t c h , i n t returns last index position for the


fromIndex) given char value and from index

3 int lastIndexOf(String substring) returns last index position for the


Dept. of ISE
given substring

4 int lastIndexOf(String substring, returns last index position for the


int fromIndex) given substring and from index
Example

String s1="this is index of example";


index1=s1.lastIndexOf('s');
System.out.println(index1);
Dept. of ISE

Output:
6
Example:

String str = "This is last index of example";


int index = str.lastIndexOf('s',5);
System.out.println(index); Output:

3
int index = str.lastIndexOf("of", 25); 19
-1

Dept. of ISE System.out.println(index);


index = str.lastIndexOf("of", 10);
System.out.println(index);
Modifying a String
Dept. of ISE
Substring in Java

•Part of string is called substring.


•Substring is a subset of another string.
• In case of substring startIndex is inclusive
and endIndex is exclusive.
Dept. of ISE
Substring as two methods:

• public String substring(int startIndex)

• public String substring(int startIndex,

int endIndex)

Dept. of ISE
Example

String s="SachinTendulkar";
System.out.println(s.substring(6));
System.out.println(s.substring(0,6));

Dept. of ISE
Output:
Tendulkar
Sachin
String concat

•combines specified string at the end of


this string.
•It returns combined string.
•Like appending another string.
Dept. of ISE •Syntax
String concat(String anotherString)
Example

String s1="java string";


s1.concat("is immutable");
System.out.println(s1);
s1=s1.concat(" is immutable so assign it ex
plicitly");
System.out.println(s1);
Dept. of ISE

Output:
java string
j ava string is immutable so assign it
explicitly
Replace()

• R e t urns a st ri ng re pl ac i ng al l t he o l d c har o r
CharSequence to new char or CharSequence.
• There are two type of replace methods in java string.
i. public String replace(char oldChar, char newChar)
Dept. of ISE ii. public String replac e(C harSeq uenc e target,
CharSequence replacement)
Example

String s1=“AST is a very good college";


String replaceString=s1.replace(‘S',’I');
System.out.println(replaceString);

Dept. of ISE

Output:
AIT is very good college
Java String replace(CharSequence target,
CharSequence replacement)

String s1="my name is ABC my name is coll


ege";
String replaceString=s1.replace("is","was");
System.out.println(replaceString);
Dept. of ISE

Output:
my name was ABC my name was college
String trim

 Eliminates leading and trailing spaces.


 Syntax
public String trim()

Dept. of ISE
Example

String s1=" hello string ";


System.out.println(s1+"java");
System.out.println(s1.trim()+"java");

Dept. of ISE
Output:
hello string java
hello stringjava
Example

String s1 =" hello java string ";


System.out.println(s1.length());
System.out.println(s1); //Without trim()
String tr = s1.trim();
Dept. of ISE System.out.println(tr.length());
System.out.println(tr); //With trim()

Output:
22
hello java string
17
hello java string
ValueOf( ) method

the valueOf method is used to convert different types of data


into String objects.
It is a static method of the String class and provides a
convenient way to convert other types into strings.
Key Points:
Static Method: valueOf is a static method in the String class.
Dept. of ISE
Versatility: It can convert primitives, objects, and even null
values to their string representation.
Null Handling: If the argument is null, valueOf returns the strin
g "null".
Example

// Converting int to String

int num = 100;

String strNum = String.valueOf(num);

System.out.println("String representation of int: " + strNum);

// Converting double to String

double d = 123.45;
Dept. of ISE
String strDouble = String.valueOf(d);

System.out.println("String representation of double: " + strDouble);

// Converting boolean to String

boolean bool = true;

String strBoolean = String.valueOf(bool);

System.out.println("String representation of boolean: " + strBoolean);


Example

// Converting char to String

char ch = 'A';

String strChar = String.valueOf(ch);

System.out.println("String representation of char: " + strChar );

// Converting Object to String

Object obj = new Integer(789);


Dept. of ISE
String strObject = String.valueOf(obj);

System.out.println("String representation of Object: " + strObject);

// Converting null Object to String obj = null;

String strNullObject = String.valueOf(obj);

System.out.println("String representation of null Object: " + strNullObject);

}
Changing the case of character within a string

 String toLowerCase(): method returns the

string in lowercase letter.

 String toUpperCase(): method returns the string

Dept. of ISE in uppercase letter.


Example

String s1=“Acharya Institute of Technology";


String s1lower=s1.toLowerCase();
System.out.println(s1lower);
String s1upper=s1.toUpperCase();
Dept. of ISE System.out.println(s1upper);

Output:
acharya institute of technology
ACHARYA INSTITUTE OF TECHNOLOGY
Dept. of ISE
String Buffer
StringBuffer

 Used to create mutable (modif iable)


string. it C an be c hange d afte r
creation without creating new objects

Dept. of ISE  StringBuffer class in java is same as


String class except it is mutable i.e. it
can be changed.
Constructors of StringBuffer class

Constructor Description

StringBuffer() creates an empty string buffer with the initial


capacity of 16.
Dept. of ISE
StringBuffer(String creates a string buffer with the specif ie d
str) string.

StringB uf fe r( int creates an empty string buffer with the


capacity) specified capacity as length.
StringBuffer append() method

 Append() method concatenates the

given argument with this string.

It has several overloaded versions. Here

Dept. of ISE are a few of its forms:

• StringBuffer append(String str)

• StringBuffer append(int num)

• StringBuffer append(Object obj)


Example

StringBuffer sb=new StringBuffer("Hello ");


sb.append(“AIT");
System.out.println(sb);

Dept. of ISE
Output:
Hello AIT
Example

StringBuffer sb = new StringBuffer("Hello ");

sb.append("World ");
Output:
sb.append(2024); Hello World 2024

System.out.println(sb);`
Dept. of ISE
StringBuffer insert() method

 Used to insert text at the specif ie d


index position.
 These are a few of its forms:
• StringBuffer insert(int index,
Dept. of ISE String str)
• StringBuffer insert(int index,
char ch)
• StringBuffer insert(int index,
Object obj)
Example

StringBuffer sb=new StringBuffer("Hello ");


sb.insert(1,“AIT");
System.out.println(sb);
Dept. of ISE
Output:
HAITello
Example for insert().

class insertDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
Dept. of ISE System.out.println(sb);
Output:
} I like Java!
char[] c1 = new char[] {'Y','e','s'};
StringBuffer sb3 = new StringBuffer("Hello World");
sb3.insert(6,c1);
System.out.println(sb3);
Output:
float f = 2.0f; Hello Yes World
Hello 2.0 World
StringBuffer sb5 = new StringBuffer("Hello World"); Hello My World

sb5.insert(6,f);
Dept. of ISE
System.out.println(sb5);
Object obj = new String("My");
StringBuffer sb8 = new StringBuffer("Hello World");
sb8.insert(6,obj);
System.out.println(sb8);
StringBuffer replace() method

replace() method replaces the given

string from the specif ie d beginIndex and

endIndex.

Dept. of ISE Its signature is shown here:

StringBuffer replace(int startIndex, int

endIndex, String str)


Example

StringBuffer sb=new StringBuffer(" Hello


World ");
sb.replace( 6, 11, "java");
System.out.println(sb);
Dept. of ISE

Output:
Hellojavad
StringBuffer sb = new StringBuffer("progra
m compile time");
System.out.println("string: "+sb);
System.out.println("after replace: "
Dept. of ISE +sb.replace(8, 15, "run"));

Output:
string: program
compile time
after replace:
program run time
StringBuffer delete() method

 deletes the string from the specified

beginIndex to endIndex.

 These methods are shown here:

Dept. of ISE • StringBuffer delete(int startIndex, int

endIndex)
Example

StringBuffer sb=new StringBuffer("Hello");


sb.delete(1,3);
System.out.println(sb);

Dept. of ISE

Output:
Hlo
deleteCharAt( )

deleteCharAt( ) method deletes the

character at the index specified by loc.

StringBuffer deleteCharAt(int loc)

Dept. of ISE It returns the resulting StringBuffer object.


demonstrates the delete( ) and deleteCharAt( )
method

class deleteDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a
test.");
Dept. of ISE sb.delete(4, 7);
System.out.println("After delete: " + sb); Output:
After delete: This a
sb.deleteCharAt(0); test.
After deleteCharAt:
his a test.
System.out.println("After deleteCharAt: " +
sb);
}}
StringBuffer reverse() method

 re v e rse s t he c ha ra c t e rs w i t hi n a

StringBuffer object.

SringBuffer reverse( )

Dept. of ISE
Example

StringBuffer str = new StringBuffer("Hello");


str.reverse();
System.out.println(str);

Dept. of ISE
Output:
olleH
capacity()

 Returns the c urrent c apac ity of


StringBuffer object.

 Example:
StringBuffer str = new StringBuffer();
Dept. of ISE
System.out.println( str.capacity() );

Output:
16
ensureCapacity()

Used to ensure minimum capacity of StringBuffer


object.
If the argument of the ensureCapacity() method is
less than the existing capacity, then there will be no
change in existing capacity.
Dept. of ISE If the argument of the ensureCapacity() method is
greater than the existing capacity, then there will be
change in the current capacity using following rule:
newCapacity = (oldCapacity*2) + 2.
Example

StringBuffer str = new StringBuffer();


System.out.println( str.capacity());
str.ensureCapacity(30);
System.out.println( str.capacity());
Dept. of ISE

Output:
34
length( ) and capacity( ):

 Length of a StringBuffer can be found

by the length( ) method,

 the total allocated capacity can be

Dept. of ISE found by the capacity( ) method

 general forms:

• int length( )

• int capacity()
Example

StringBuffer s=new StringBuffer(“AIT");


int p=s.length();
int q=s.capacity();
System.out.println("Length of string AIT="+p);
System.out.println("Capacity of string AIT="+q);
Dept. of ISE

Output:
•Length of string AIT=3

• Capacity of string AIT=19 (because room for 16

additional character is automatically added)


charAt( ) and setCharAt( )

charAt() method returns a char value at


the given index number.
setCharAt() is used to set the specified
character at the given index.
Dept. of ISE • char charAt(int where)
• void setCharAt(int where, char
ch)
Demonstrate charAt() and setCharAt().

StringBuffer sb = new StringBuffer("Hello");


System.out.println("buffer before = " + sb);
Output:
System.out.println("charAt(1) before = " + buffer before = Hello
charAt(1) before = e
buffer after = Hi
sb.charAt(1)); charAt(1) after = i

Dept. of ISE sb.setCharAt(1, 'i');


sb.setLength(2);
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " +
sb.charAt(1));
StringBuilder class

 StringBuilder is identical to StringBuffer except


for one impor tant d ifferenc e that it is not
synchronized, which means it is not thread safe.

Dept. of ISE
Differences

String StringBuffer

The length of the String object is The length of the StringBuffer


fixed. can be increased.

String object is immutable. StringBuffer object is mutable.


Dept. of ISE
Performance is slower during Performance is faster during
concatenation. concatenation.

Consumes more memory. Consumes less memory.

Stores the strings in String Stores the strings in Heap


constant pool. Memory
Differences

StringBuffer StringBuilder

StringBuilder is non-
StringBuffer is synchronized i.e.
synchronized i.e. not thread safe.
thread safe. It means two
Dept. of ISE It means two threads can call
threads can't call the methods of
the methods of StringBuilder
StringBuffer simultaneously.
simultaneously.

StringBuffer is less efficient than StringBuilder is more efficient


StringBuilder. than StringBuffer
THANK YOU
Dept. of ISE
Dept. of ISE
Dept. of ISE
Dept. of ISE
Dept. of ISE
Dept. of ISE
Dept. of ISE
Dept. of ISE

You might also like