0% found this document useful (0 votes)
82 views

Strings 2023

Strings are a collection of characters enclosed in double quotes. In Java, strings are treated as objects and are immutable. There are two types of strings - immutable and mutable. Immutable strings cannot change value while mutable strings can. StringBuffer and StringBuilder classes are used to create mutable strings. Strings in Java are different than in C as C strings terminate with a null character and all are mutable.

Uploaded by

Suma Ph
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)
82 views

Strings 2023

Strings are a collection of characters enclosed in double quotes. In Java, strings are treated as objects and are immutable. There are two types of strings - immutable and mutable. Immutable strings cannot change value while mutable strings can. StringBuffer and StringBuilder classes are used to create mutable strings. Strings in Java are different than in C as C strings terminate with a null character and all are mutable.

Uploaded by

Suma Ph
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/ 70

Strings

What do you mean by Strings..??


•Strings is a collection of characters which will be
enclosed within a double quotes
•Strings are treated as objects in java.
•String in C is different from Strings in
Java.
•Strings in java will not be terminated with
null character
Types of Strings
2 Types of Strings

Immutable Mutable
Ex:Name Ex:Day
DOB Month
Gender Password
•Immutable Strings are those Strings whose
value cannot be changed.
•Mutable Strings are those Strings whose value
can be changed.
•For Creating Immutable Strings java has
provided String as a inbuilt class.
•For Creating Mutable Strings java has provided
StringBuffer and StringBuilder as a inbuilt
classes.
• Difference between Strings in C and Java
• Strings in C will be terminated with null(\0)
character whereas in java it will not be
terminated with null character.
• All the Strings in C will be mutable Strings
whereas in Java it will be of 2 types I,e
Mutable and Immutable.
• In C string is a data type where as in Java
String is a In-built class.
Immutable Strings:
3 ways of Creating Immutable Strings are:

1) String s=new String(“RAMA”);


2) String s=“RAMA”;
3) char name[]= {‘R’,’A’,’M’,’A’};
String s=new String(name); // This is not
frequently used
Why there are 2 different ways for creating
Immutable Strings..??
JRE is further divided into 4 areas namely,

Method/code Area contains the code or program in Intermediate level


Language.

Static Area includes static variables , static blocks and static


methods.

Stack Area includes local variables, reference variables and activation


records.

Heap Area includes instance variables and objects

JRE is region allocated on RAM which provides


the environment to execute the java program.
Different ways followed to create immutable
strings will allocate memory in different
areas…
1) String s=new String(“RAMA”);

Heap Area

Heap Area String Constant Pool

2) String s=“RAMA”;
If String is created using new keyword then
memory will be allocated on Heap Area directly.
If String is created without using new keyword
then memory will be allocated on String constant
pool area present within Heap Area.
Speciality of String Constant Pool:
•String Constant Pool is a region present inside
the Heap Area also called as non constant pool.
•Only String objects gets created inside this
region.
•Even if no one is refering to String object
in this region, the memory will never get
de-allocated from this region.
•Duplicates aren’t allowed in this region.
String s=new String(“RAMA”);

4000
s 4000 R A M A

Stack Area Heap Area


Different ways of comparision of
Strings
1) == : It is used to compare the
references(address) of two Strings.
2) equals(): It is used to compare the
values of two Strings.
3) compareTo(): It is used to compare the values of
two Strings character by character.
4) equalsIgnoreCase (): It will compare values of two
Strings by ignoring the case.
String Constant Pool

4000
s1 4000 R A M A

s2 4000

Stack Segment Heap


class Demo1
class Demo1
{
{
public static void main(String[] args)
public static void main(String[] args)
{
{
String s1="RAMA";
String s1="RAMA";
String s2="RAMA";
String s2="RAMA";
if(s1.equals(s2))
if(s1==s2)
System.out.println("both the strings are
System.out.println(“string references are equal");
equal");
else
else
System.out.println(“String references are unequal");
System.out.println("Both the strings are
}
unequal");
}
}
}

Output
Output
Both the strings are equal
String references are equal
String s1=new String(“RAMA”);
• Whenever new keyword is associated while
creating a string object it creates the String
object in the heap area outside the String
constant pool and returns the address of it.

• A copy of same object will also be created


inside the String constant pool.
String Constant Pool

600
R A M A

4000
s1 4000 R A M A

5000
s2 5000 R A M A

Stack Segment Heap


class Demo1
class Demo1
{
{
public static void main(String[] args)
public static void main(String[] args)
{
{
String s1=new String("RAMA“);
String s1=new String("RAMA“);
String s2=new String("RAMA“);
String s2=new String("RAMA“);
if(s1.equals(s2))
if(s1==s2)
System.out.println("both the strings are
System.out.println(“string references are equal");
equal");
else
else
System.out.println(“String references are unequal");
System.out.println("Both the strings are
}
unequal");
}
}
}

Output
Output
Both the strings are equal
String references are unequal
Concatenation of Strings
1+1 = 2 1+1+1 = 3
“1”+1 = “11” “1”+1 +1=“111”

1+”1”= “11” 1+1+”1”=“21”

“1”+”1”= “11” 1+“1”+1=“111”

”1”+“1”+”1”= “111”
String Constant Pool

4000
s1 4000 R A M A

5000

s2 5000 r a m a

Stack Segment Heap


class Demo1
class Demo1
{
{
public static void main(String[] args)
public static void main(String[] args)
{
{
String s1=“RAMA”;
String s1=“RAMA”;
String s2=“rama”;
String s2=“rama”;
if(s1.equals(s2))
if(s1==s2)
System.out.println("both the strings are
System.out.println(“string references are equal");
equal");
else
else
System.out.println(“String references are unequal");
System.out.println("Both the strings are
}
unequal");
}
}
}

Output
Output
Both the strings are unequal
String references are unequal
class Demo1
{
public static void main(String[] args)
{
String s1=“RAMA”;
String s2=“rama”;
if(s1.equalsIgnoreCase(s2))
System.out.println("both the strings are equal");
else
System.out.println("Both the strings are unequal");
}
}

Output
Both the strings are equal
String Constant Pool
4000
s1 4000 R A M A

5000

s2 5000 S I T A
700
R A M A S I T A
6000
s3 6000 R A M A S I T A
7000
s4 7000 R A M A S I T A

5000
Stack Segment Heap
class Demo1
class Demo1
{
{
public static void main(String[] args)
public static void main(String[] args)
{
{
String s1=“RAMA”;
String s1=“RAMA”;
String s2=“SITA”;
String s2=“SITA”;
String s3=s1+s2;
String s3=s1+s2;
String s4=s1+s2;
String s4=s1+s2;
if(s3.equals(s4))
if(s3==s4)
System.out.println("both the strings are
System.out.println(“string references are equal");
equal");
else
else
System.out.println(“String references are unequal");
System.out.println("Both the strings are
}
unequal");
}
}
}

Output
Output
Both the strings are equal
String references are unequal
• During concatenation, if any String variable is
involved which is already created, the resultant
String object will be created inside Non constant
pool and a copy of it will be present inside string
constant pool and returns the address of string
object which is outside String constant pool.
• During concatenation if no String variable is
involved the resultant String object will be
created only inside String constant pool.
class Demo1
class Demo1
{
{
public static void main(String[] args)
public static void main(String[] args)
{
{
String s1=“RAMA”;
String s1=“RAMA”;
String s2=“SITA”;
String s2=“SITA”;
String s3=“RAMA”+s2;
String s3=“RAMA”+s2;
String s4=s1+”SITA”;
String s4=s1+”SITA”;
if(s3.equals(s4))
if(s3==s4)
System.out.println("both the strings are
System.out.println(“string references are equal");
equal");
else
else
System.out.println(“String references are unequal");
System.out.println("Both the strings are
}
unequal");
}
}
}

Output
Output
Both the strings are equal
String references are unequal
String Constant Pool
4000
s1 4000 R A M A

5000

s2 5000 S I T A
700
R A M A S I T A
6000
s3 6000 R A M A S I T A
7000
s4 7000 R A M A S I T A

5000
Stack Segment Heap
• Even if we are using one string reference
variable which is already created to create
another string then the resultant string will be
present in non constant pool
class Demo1
class Demo1
{
{
public static void main(String[] args)
public static void main(String[] args)
{
{
String s1=“RAMA”;
String s1=“RAMA”;
String s2=“SITA”;
String s2=“SITA”;
String s3=“RAMA”+”SITA”;
String s3=“RAMA”+”SITA”;
String s4=“RAMA”+”SITA”;
String s4=“RAMA”+”SITA”;
if(s3.equals(s4))
if(s3==s4)
System.out.println("both the strings are
System.out.println(“string references are equal");
equal");
else
else
System.out.println(“String references are unequal");
System.out.println("Both the strings are
}
unequal");
}
}
}

Output
Output
Both the strings are equal
String references are equal
String Constant Pool
4000
s1 4000 R A M A

5000

s2 5000 S I T A
700

s3 700 R A M A S I T A

s4 700

5000
Stack Segment Heap
• In the above program as we are concatinating
both the values directly, one single copy of
resultant string will be created on string
constant pool and both the string reference
variable s1 and s2 will be referring to same
copy.
• Single copy is shared among s3 and s4 as
duplicates are not allowed in string constant
pool
compareTo()
• There can be 3 possible results or cases of
compareTo() method as shown.
S A C H I N S A U R A V S A C H I N

S A U R A V S A C H I N S A C H I N

-ve value as +ve value as 0(zero) as s1 is equal to


s2>s1 s1>s2 s2(s1=s2)
class Demo1
{
public static void main(String[] args)
{
String s1="SACHIN";
String s2="SAURAV";
if(s1.compareTo(s2)>0)
System.out.println("First string is greater than second string "+s1.compareTo(s2));
else if(s1.compareTo(s2)<0)
System.out.println("Second string is greater than first string "+s1.compareTo(s2));
else
System.out.println("both the strings are equal "+s1.compareTo(s2));
}
}

Output
Second string is greater than first string
-18
• In the above slide the first program gives the output
which is negative number as the UNICODE of character
in second string is greater than the UNICODE of
character in first string.
• Also the integer number that is getting displayed is
nothing but the difference between the UNICODE of
different characters encountered.
EX( in s1(SACHIN) and s2(SAURAV) the different
characters occurred first time is U(85) and C(67) and
the difference among them is 18 along with minus(-) as
the character in second string is greater.
class Demo1
{
public static void main(String[] args)
{
String s1=" SAURAV";
String s2=" SACHIN";
if(s1.compareTo(s2)>0)
System.out.println("First string is greater than second string "+s1.compareTo(s2));
else if(s1.compareTo(s2)<0)
System.out.println("Second string is greater than first string "+s1.compareTo(s2));
else
System.out.println("both the strings are equal "+s1.compareTo(s2));
}
}

Output
First string is greater than Second string
18
• In the above slide the second program gives the output
which is positive number as the UNICODE of character
in First string is greater than the UNICODE of character
in Second string.
• Also the integer number that is getting displayed is
nothing but the difference between the UNICODE of
different characters encountered.
EX( in s1(SAURAV) and s2(SACHIN) the different
characters occurred first time is C(67) and U(85) and
the difference among them is 18 along with PLUS(+) as
the character in First String is greater.
class Demo1
{
public static void main(String[] args)
{
String s1=" SACHIN";
String s2=" SACHIN";
if(s1.compareTo(s2)>0)
System.out.println("First string is greater than second string "+s1.compareTo(s2));
else if(s1.compareTo(s2)<0)
System.out.println("Second string is greater than first string "+s1.compareTo(s2));
else
System.out.println("both the strings are equal "+s1.compareTo(s2));
}
}

Output
Both the strings are equal 0(ZERO)
• When all the characters of both the strings
being compared are same then the compareTo
method will return the int number I,e zero(0)
without any sign(neither + nor -);
class Demo1
{
public static void main(String[] args)
{
String s1=“SITA”;
System.out.println(s1);
S1.concat(“RAVANA”);
System.out.println(s1);
}
}
Output
SITA
SITA
• In the above program Both the times we print
the value of s1 we will get the same output I,e
SITA and not SITARAVANA .
• the reason behind this is that above string s1
is created by using String inbuilt class which
will make it as IMMUTABLE string which
means whose value cannot be modified.
However to overcome this problem we can
make use of Mutable Strings.
Mutable Strings
s1
Capacity=16
Length=0

s1 S A C H I N I S G R E A T

Capacity=16
Length=16
New size=oldsize*2+2 => Newsize=16*2+2=>34

s1 S A C H I N I S A G R E A T B A T S MA N . H E I S F R
Capacity=34
Length=34
New size=oldsize*2+2 => Newsize=34*2+2=>70
class Demo2
{
public static void main(String[] args)
{
Output
StringBuffer s1=new StringBuffer(); 16
System.out.println(s1.capacity()); 0
16
System.out.println(s1.length());
7
s1.append("sachin "); 34
System.out.println(s1.capacity()); 26
70
System.out.println(s1.length());
43
s1.append("is a great batsman.");
System.out.println(s1.capacity());
System.out.println(s1.length());
s1.append("he is from India.");
System.out.println(s1.capacity());
System.out.println(s1.length());
}
}
class Demo2
{
public static void main(String[] args)
{
Output
StringBuilder s1=new StringBuilder (); 16
System.out.println(s1.capacity()); 0
16
System.out.println(s1.length());
7
s1.append("sachin "); 34
System.out.println(s1.capacity()); 26
70
System.out.println(s1.length());
43
s1.append("is a great batsman.");
System.out.println(s1.capacity());
System.out.println(s1.length());
s1.append("he is from India.");
System.out.println(s1.capacity());
System.out.println(s1.length());
}
}
For both the programs ie using stringbuffer and
stringbuilder classes will give the same output
however there are few differences and few
similarities as shown below.
String Buffer StringBuilder
• Initial capacity is 16 • Initial capacity is 16
• Used for creating mutable • Used for creating mutable
strings strings
• Race condition doesn’t occur
• Race condition occurs
• It is threadsafe
• It is less efficient than • It is not threadsafe
StringBuilder • It is more efficient than StringBuffe
• It is slow • It is fast
Example to show the performance of
StringBuffer and StringBuilder
class Demo1
{ long st2=System.currentTimeMillis();
for(int i=1;i<=10000;i++)
public static void main(String[] args)
{
{ sbd.append("bjshub");
StringBuffer sbf=new StringBuffer(); }
StringBuilder sbd=new StringBuilder(); System.out.println("STRING BUilder "+
long st1=System.currentTimeMillis(); (System.currentTimeMillis()-st2));
}
for(int i=1;i<=10000;i++)
}
{ Ouput
sbf.append("bjshub");
STRING BUFFER 16
}
System.out.println("STRING BUFFER
******************
"+(System.currentTimeMillis()-st1)); STRING BUilder 0
System.out.println("******************");
Which Shows StringBuilder
is FAST
Few important inbuilt methods of String
Class
class Demo2
{
public static void main(String[] args)
{ System.out.println(s1.startsWith("Raja"));
String s1="RajaRamMohanRoy"; System.out.println(s1.startsWith("Roy"));
System.out.println(s1.endsWith("Roy"));
System.out.println(s1.toUpperCase());
System.out.println(s1.endsWith("Boy"));
System.out.println(s1.toLowerCase()); System.out.println(s1.indexOf('a'));
System.out.println(s1.charAt(5)); System.out.println(s1.substring(4));
System.out.println(s1.substring(4,6));
System.out.println(s1.length());
}
char arr[]=s1.toCharArray(); }
for(int i=0;i<=arr.length-1;i++){
System.out.print(arr[i]);}
System.out.println(s1.contains("a"));
System.out.println(s1.contains("Ram"));
System.out.println(s1.contains("Man"));
Output of previous Program I,e Inbuilt methods of
String class
RAJARAMMOHANROY
rajarammohanroy
a
15
RajaRamMohanRoytrue
true
false
true
false
true
false
1
RamMohanRoy
Ra
Enter the String to reverse..
i i i i i Step 1:find the length of original String by using
length() method.
s h e l l o
0 1 2 3 4 Step 2:create an reference named i at end of
original String.

Step 3:Create one more String without assigning


rev o l l e h any values with the name as rev.
0 1 2 3 4
Step 4:initially rev String will not be having any
Length of s=5,but Strings index will
value in it . wherever i is pointing in original Strin
Always starts with index 0 so it should
Concate that value to rev String.
be length-1;

Step 5:decrement the value of i and again repeat


the same that is I,e wherever i is pointing copy
that value and concate it with rev String.
i

s H E L L O

String rev; rev

String rev=rev+charAt(i); rev + O

System.out.println(rev) rev O

s H E L L O

String rev=rev+charAt(i);
rev O + L

System.out.println(rev) rev O L
i

s H E L L O

String rev=rev+charAt(i); rev O L + L

System.out.println(rev) rev O L L

s H E L L O

String rev=rev+charAt(i);
rev O L L + L

System.out.println(rev) rev O L L E
i

s H E L L O

String rev=rev+charAt(i); rev O L L E + H

System.out.println(rev) rev O L L E H
Palindrome
i j Step 1:find the length of String by using
length() method.
s m a d a m
0 1 2 3 4 Step 2:create an reference named i at beginning
of String.
i j
Step 3:Create one more reference named j at
M M the end of string.

Step 4:now consider both values I,e wherever


i j i is pointing and j is pointing consider both
Values and compare.
M A A M

Length of s=5,but Strings index will Step 5:if they aren’t same return false, if they are
Always starts with index 0 so it should Same decrement j and increment I and also
be length-1; return true.
i j

s M A L A Y A L A M

i j
If(s.charAt(i)==s.charAt(j))
return true s M M

i j
decrement i and increment j
s M A L A Y A L A M

i j

If(s.charAt(i)==s.charAt(j)) s M A A M
return true

i j

decrement i and increment j


s M A L A Y A L A M
i j

s M A L A Y A L A M

i j
If(s.charAt(i)==s.charAt(j))
return true s M A L A A L A M

i j
decrement i and increment j
s M A L A Y A L A M
Unicode values
A B C D E F G H I J K L M
65 66 67 68 69 70 71 72 73 74 75 76 77

N O P Q R S T U V W X Y Z
78 79 80 81 82 83 84 85 86 87 88 89 90

a b c d e f g h i j k l m
97 98 99 100 101 102 103 104 105 106 107 108 109

n o p q r s t u v w x y z
110 111 112 113 114 115 116 117 118 119 120 121 122
i
Case swap
s N a V e E n
0 1 2 3 4 5

String res;
res

N=78
If(charAt(i)>=65 & charAt(i)<90) + 78+32
res
res=res+charAt(i)+32
78+32=110

res n
Removing the spaces from a String
i Step1:accept the string.

s H E L L O A B C
Step2: find the length of the String.
0 1 2 3 4 5 6 7 8

Step3:create a reference with the name


as i in the beginning of the original
rem string.
Step4:create one more string with the
name as rem which will be empty
initially.

Step5:try to concate whatever the


values present in original string to rem
The length of the string is 9.However
string character by character if
index value ranges from 0-8.
character is not equal to space(“ “);
i

s H E L L O A B C
0 1 2 3 4 5 6 7 8

String rem; rem

If(charAt(i)!=“ ”) rem + H
res=res+charAt(i);

System.out.println(rem); rem H
i

s H E L L O A B C
0 1 2 3 4 5 6 7 8

String rem; rem H

If(charAt(i)!=“ ”) rem H + E
res=res+charAt(i);

System.out.println(rem); rem H E
i

s H E L L O A B C
0 1 2 3 4 5 6 7 8

String rem; rem H E

If(charAt(i)!=“ ”) rem H E + L
res=res+charAt(i);

System.out.println(rem); rem H E L
i

s H E L L O A B C
0 1 2 3 4 5 6 7 8

String rem; rem H E L

If(charAt(i)!=“ ”) rem H E L + L
res=res+charAt(i);

System.out.println(rem); rem H E L L
i

s H E L L O A B C
0 1 2 3 4 5 6 7 8

String rem; rem H E L L

If(charAt(i)!=“ ”) rem H E L L + O
res=res+charAt(i);

System.out.println(rem); rem H E L L O
i

s H E L L O A B C
0 1 2 3 4 5 6 7 8

String rem; rem H E L L O

If(charAt(i)!=“ ”)
res=res+charAt(i);//condition
fails

System.out.println(rem); rem H E L L O
i

s H E L L O A B C
0 1 2 3 4 5 6 7 8

String rem; rem H E L L O

If(charAt(i)!=“ ”) rem H E L L O + A
res=res+charAt(i);

System.out.println(rem); rem H E L L O A
Removing extra spaces from String

i si

s _ _ A B C _ _ F O R _ _
0 1 2 3 4 5 6 7 8 9 10 11
Accept the String and find the
length of the string.
The length of the String is 12
Create a reference at the
beginning of the String I,e i.Keep
incrementing i till you encounter
character other then space.

As soon as you encounter


character apart from space one
can create another reference with
the name as si.
i si ei i

s _ _ A B C _ _ F O R _ _
0 1 2 3 4 5 6 7 8 9 10 11

Create a reference at the ending of


the String I,e i.Keep decrementing
i till you encounter character other
then space.

As soon as you encounter


character apart from space create
another reference with the name
as ei.
Reversing complete String
INPUT s T H I S _ I S _ M Y _ C L A S S
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

OUTPUT
ar[] CLASS MY IS THIS

ar[] THIS IS MY CLASS


0 1 2 3
i i i i
String to String type array

s T H I S _ I S _ M Y _ C L A S S
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Accept the String and find the length of
The length of the String is 16 .index value
the String S.
ranges from 0-15
The size of an array should be mentioned.

Find the number of spaces , if spaces are 3


then words would be 3+1 i,e 4.
ar[]
0 1 2 3

Create an array with the name ar[] with


specified size.
Create an reference with the name as I i i i i i
for original String at the beginning of the
String. s T H I S _ I S _ M Y _ C L A S S
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

We have to Copy word by word from s to


ar[].
To achieve above expectation make use
of temp variable.
String temp temp
0 1 2 3 4

Wherever I is pointing in String s


concate that value to temp String
,increment value of I concate till
temp T H I S
0 1 2 3 4
you encounter space.

Create a reference j with value 0 being


assigned and Whatever is there in temp
copy that to an array ar[] in 0th position
j j
and inc value of j.
ar[] THIS
0 1 2 3
Continue doing it till last character
of String s.however once each word
is copied from s→temp and from
temp→ar[] clear temp so that you
can store next string.
temp T H I S I S

ERROR 0 1 2 3 4 5 6
j j
ar[] THIS THIS IS
0 1 2 3

j j
ar[] THIS IS MY CLASS
0 1 2 3
Reversing complete String with
characters also being reversed
INPUT s T H I S _ I S _ M Y _ C L A S S
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

OUTPUT
ar[] SSALC YM SI SHIT

OR

OUTPUT ar[] SHIT SI YM SSALC

ar[] SSALC YM SI SHIT


0 1 2 3
i i i i
String to String type array

s T H I S _ I S _ M Y _ C L A S S
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Accept the String and find the length of
The length of the String is 16 .index value
the String S.
ranges from 0-15
The size of an array should be mentioned.

Find the number of spaces , if spaces are 3


then words would be 3+1 i,e 4.
ar[]
0 1 2 3

Create an array with the name ar[] with


specified size.
Create an reference with the name as I i i i i i
for original String at the ending of the
String. s T H I S _ I S _ M Y _ C L A S S
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

We have to Copy word by word from s to


ar[].
To achieve above expectation make use
of temp variable.
String temp temp
0 1 2 3 4

Wherever I is pointing in String s


concate that value to temp String
,decrement value of I concate till
temp S S A L C
0 1 2 3 4
you encounter space.

Create a reference j with value 0 being


assigned and Whatever is there in temp
copy that to an array ar[] in 0th position
j j
and inc value of j.
ar[] SSALC
0 1 2 3

You might also like