[go: up one dir, main page]

0% found this document useful (0 votes)
41 views34 pages

String 1.1

The document discusses strings in Java, including how they are created and the methods available in the String, StringBuffer, and StringBuilder classes. It covers the differences between immutable and mutable strings, how to create string objects, and example methods for manipulating, comparing, and retrieving parts of strings.

Uploaded by

Akash Savaliya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views34 pages

String 1.1

The document discusses strings in Java, including how they are created and the methods available in the String, StringBuffer, and StringBuilder classes. It covers the differences between immutable and mutable strings, how to create string objects, and example methods for manipulating, comparing, and retrieving parts of strings.

Uploaded by

Akash Savaliya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

STRINGS IN JAVA

1
Agenda
• Basic Concepts
 Immutable and Mutable strings
 Two ways to create string objects
• String Class Methods (immutable)
• StringBuffer Constructors & Methods (mutable)
• StringBuilder Constructors &Methods (mutable)
• String class Vs StringBuffer class Vs
2
Basic Concepts

• A group of characters is referred to as a string

• An array of characters is the implementation model

• In Java, strings are considered as objects which are


different from character arrays

3
Basic Concepts
• Java supports two types of strings
1. Immutable String
• Once a string is created as an object, it requires explicit processing
for changes, implicit processing never changes the content
• Example
• String class is immutable (available in <java.lang.String>)
• String str1 = “Welcome to String Processing!”;
• System.out.println(str1); // displays <Welcome to String Processing>
• System.out.println(str1.concat(“ in Java”)); // Implicit processing, no changes
• // only displays, never updates <Welcome to String Processing in Java>
• str1 = str1.concat(“ in Java”); // Explicit assignment, changes str1
4
Basic Concepts
2. Mutable String
• It accepts changes in content even for implicit processing, so
no need of explicit notations
• Example – (1) StringBuffer Class
• StringBuffer class is mutable & synchronized <java.lang.StringBuffer>
• StringBuffer str1 = new StringBuffer(“Mutable String Processing!”);
• System.out.println(str1); // displays <Mutable String Processing!>
• System.out.println(str1.append(“ in Java”));
• // Implicit processing is enough for change
• // updates and displays < Mutable String Processing in Java>
5
Basic Concepts
2. Mutable String
• Example – (2) StringBuilder Class
• StringBuilder class is mutable & non-synchronized <java.lang.StringBuilder>
• StringBuilder str1 = new StringBuilder(“Mutable String Processing!”);
• System.out.println(str1); // displays <Mutable String Processing!>
• System.out.println(str1.append(“ in Java”));
• // Implicit processing is enough for change
• // updates and displays < Mutable String Processing in Java>

Demo Program
6
Basic Concepts
• Two ways to create string object
By string literal
char[] gr1 = {‘w’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’} ; // user-defined
char[] ca1 = {‘s’, ‘t’, ‘r’, ‘i’, ‘n’, ‘g’} ; // user-defined
String str = “Welcome to String!” // built-in
By new keyword
String gr2 = new String(gr1) ; // built-in
String ca2 = new String(ca1) ; // built-in
String gr3 = new String(“Hello World!”) ; // built-in
• Source Code with Output
7
Basic Concepts
• Why avoid String literal method for String object creation?
• Example
oString s1=“Welcome";
oString s2=“Welcome";
• Here the compiler will create only
a single String object which will
store the assigned literal
• If the object already exists in the memory then the new object of
String class will not be created instead the value will be assigned
to the existing object
8
Basic Concepts
• Why avoid String literal method for String object
creation?
• Using new operator
• Example
• String str1=new String ("Welcome");
• String str2=new String ("Welcome");
• Here the two different String objects str1 and str2 will
have the same value as “Welcome” and it will be stored
in the memory.
9
String Class Methods (java.lang.String)
• String class supports the following methods
1. length (final variable for char array and method for string object)
2. concat 9. format 16. indexOf 23. getBytes
3. trim 10. charAt 17. contains 24. getChars
4. valueOf 11. substring 18. join 25. compareTo
5. toLowerCase 12. isEmpty 19. startsWith 26. lastIndexOf
6. toUpperCase 13. replace 20. endsWith
7. equals 14. replaceAll 21. intern
8. equalsIgnoreCase 15. split 22. toCharArray
Output/Return
Method Purpose Example
value

5
length() To find the numbers of characters in a String name=“KUMAR”;
string name.length() ; Demo Program

To combine/append specified string at String s1=“NEW” ; NEWDELHI


concat() the end of this string s1=s1.concat(“DELHI”); Demo Program

To eliminate leading and trailing spaces String t1=“ Hai “; Hai


trim()
(doesn't omits middle spaces) t1.trim(); Demo Program

12
valueOf() To convert different types of values int a = 12;
into string String.valueOf(a); Demo Program
11
Output /
Method Purpose Example Return
value

String s=“GOOD”; good


toLowerCase() To convert the string into lowercase s.toLowerCase(); Demo Program

String s=“best”; BEST


toUpperCase() To convert the string into uppercase s.toUpperCase();
Demo Program

To compare the two given strings based on the true


content of the string. String s1=“abc”; false
equals() If any character is not matched, it returns false. s1.equals(“abc”);
If all characters are matched, it returns true s1.equals(“ABC”); Demo Program

To compare the two given strings based on the true


content of the string irrespective of case String s2=“abc”; true
equalsIgnoreCase() If any character is not matched, it returns false. s2.equals(“abc”);
If all characters are matched, it returns true s2.equals(“ABC”); 12
Demo Program
Output /
Method Purpose Example Return
value
To align/beautify display values of any data bbbbb bbbb5
It is like sprintf() function in C language and int a=5;
format() printf() method of Java language String.format(“%10d”,a);
General formats Date & Time formats Demo Program

String s1=“Good”; G
charAt() To extract a character at the given index s1.charAt(0);
Demo Program

To extract a part of the string at the given range String s2=“Nice Day”; Day
substring() or at the given index to the end s2.substring(5);
Demo Program

To check if this string is empty or not String s3=“”; true


isEmpty() It returns true, if length of string is 0 s3.isEmpty();
otherwise false Demo 13Program
Output /
Method Purpose Example Return
value

To change a character/substring in the given String s1=“abcabc”; *bc*bc


replace() character/string for all occurrences s1.replace(‘a’, ‘*’); // char
respectively Demo Program

To change a substring in the given string for String s2=“abcabc”; *bc*bc


replaceAll() all occurrences s2.replaceAll(“a”, “*”); //str Demo Program

Good
To separate the given string into individual String s3=“Good Day!”; Day!
split() words by using a delimiter String[] s4=s3.split(“\\s”);
// delimiter is blank space Demo Program

String s5=“Good Day!”; Good Day!


split(,) Similar to split() but limiting the output array String[] s6=s5.split(“\\s”,1);
// 1 array as output Demo 14Program
Output /
Method Purpose Example Return
value

String s1=“Testing…”; 2
indexOf (char) To know the position of a character s1.indexOf(‘s’); // char
Demo Program

To know the position of a character String s2=“Testing…”; -1


indexOf (char, from) starting from given location s2.indexOf(‘s’,5); Demo Program

String s3=“Testing…”; 2
indexOf (str) To know the position of a string s3.indexOf(“s”); // str
Demo Program

To know the position of a string String s4=“Testing…”; -1


indexOf (str, from) beginning from given location s4.indexOf(“s”,5);
Demo 15Program
Method Purpose Example

To check the presence of the given String s1=“Good Day!”;


substring in another string s1.contains(“Good”);  true
contains()
s1.contains(“Day”);  true
Demo Program s1.contains(“Hai”);  false

To connect individual words into a


join() sentence through a delimiter String.join(“:”, ”10”, ”10”);  10:10
Demo Program String.join((“/”, ”25”, ”12”, ”2018”)  25/12/2018

To check the starting letters of a String regno=“18CSE0001” ;


startsWith() string regno.startsWith(“18”);  true
startsWith(,) Demo Program regno.startsWith(“17”);  false

To check the ending letters of a String name=“Ram Kumar” ;


endsWith() string name.endsWith(“ar”);  true
Demo Program name.endsWith(“sh”);  false 16
Method Purpose Example

String s1=“Hai”;
String s2=new String(“Hai”);
String s3=s1.intern(); // s3=pool value of s1
To create a duplicate copy String s4=s2.intern(); // s4=pool value of s2
of an existing string which
if (s1==s2)  false
is in string constant pool
intern() if (s1==s3)  true

if (s1==s4)  true
Demo Program
if (s2==s3)  false

if (s2==s4)  false

if (s3==s4)  true
17
Method Purpose Example

To convert the given string object into a


char array String s=“Welcome”; // s is string object
toCharArray() char[] ca=s.toCharArray();
Demo Program // content is copied but ca is an array

To convert the given string object into a String s=“Aa”;


getBytes() byte array (ASCII values)
byte[] ba=s.getBytes();  65,97
Demo Program
To convert the given string object into a String str=“Bye”;
getChars() char array with a given range char[] ca=new ca[str.length()];
str.getChars(0, 1, ca, 0);
Demo Program // ca contains <By>
String s1=“ABC”;
To compare two string objects String s2=“ABC”;
(similar to strcmp() in C, returns +1, -1, 0) String s3=“aBC”;
compareTo() s1.compareTo(s2)  0 18
Method Purpose Example

String str=“this is my string”;


To find the last occurrence of the given
lastIndexOf (char) str.lastIndexOf(‘s’);  11
character in a string (default is L  R)
str.lastIndexOf(‘i’);  14

To find the last occurrence of the given


lastIndexOf (char, from) character from given position in reverse str.lastIndexOf(‘s’,0);  -1
direction (R  L) str.lastIndexOf(‘s’,5);  3

To find the last occurrence of the given sub- str.lastIndexOf(“s”);  11


lastIndexOf (str) str.lastIndexOf(“i”);  14
string in a string (default is L  R)
str.lastIndexOf(“is”);  5

To find the last occurrence of the given sub- str.lastIndexOf(“s”,0);  -1


string from given position in reverse
lastIndexOf (str, from) str.lastIndexOf(“i”,5);  5
direction (R  L)
Demo Program str.lastIndexOf(“is”,5); 195
StringBuffer Class (java.lang.StringBuffer)
• StringBuffer class is used to manipulate modifiable strings
• String Vs StringBuffer classes
• String class is immutable where as StringBuffer class is mutable
• Remaining are the same
• StringBuffer class is thread-safe, follows an order
• There are 3 constructors in StringBuffer class
• Supports 7 methods

20
StringBuffer Class Constructors
Constructor Purpose Example

StringBuffer sb1=new StringBuffer();


StringBuffer() To create an empty string buffer // creates an empty string buffer of size 0

StringBuffer(String str) To create a string buffer with the StringBuffer sb2=new StringBuffer(“Hai”);
given string // creates a string buffer with <Hai>

To create an empty string buffer StringBuffer sb3=new StringBuffer(25);


StringBuffer(int size) // creates an empty string buffer of size 0
Demo Program
StringBuffer Class Methods
1. append - to add string at end

2. insert - to insert a substring at given index

3. replace - to substitute a substring at given index

4. delete - to remove the characters at given index

5. reverse - to change the content in reverse order

6. capacity- to check the allocated buffer size (not length of content)

7. ensureCapacity – to confirm the allocated buffer size


Method Purpose Example

StringBuffer sb=new StringBuffer(“Hai”);


append (str) To add a new string at the end sb.append(“, Welcome!”);  Hai, Welcome!
Demo Program

StringBuffer sb=new StringBuffer(“How R U?”);


insert (pos, str) To add a new string at any given sb.insert(0, “Hai,”);  Hai, How R U?
position
Demo Program

To change the content of an StringBuffer sb=new StringBuffer(“Hai!”);


replace (startIndex, existing string with given start and sb.replace(1,sb.length(),”ello!”);  Hello!
endIndex, newStr) end index values
(buffer length adjusted by default) Demo Program

StringBuffer sb=new StringBuffer(“Good Day!”);


To remove letters from an existing
delete (startIndex, string by using start and end index sb.delete(4, sb.length());  Good
endIndex) values
Demo Program
Method Purpose Example
StringBuffer sb = new StringBuffer(“ABC”);
reverse() To change the given string into sb.reverse();  CBA
reverse order
Demo Program
StringBuffer sb=new StringBuffer(“”);
To check the size of the allocated
capacity() buffer. Automatic expansion would sb.capacity();  16
be done by using (oldSize*2)+2
Demo Program
StringBuffer sb=new StringBuffer(“Welcome”);
To confirm the allocated buffer size. sb.capacity();  16
ensureCapacity (int) Automatic expansion would be sb.ensureCapacity(20);  34
done by using (oldSize*2)+2
Demo Program
StringBuffer sb=new StringBuffer(“Hello!”);
setLength(int) To customize buffer size sb.length() ; 6
sb.setLength(2);
sb.length();  2 Demo Program
StringBuilder Class
(java.lang.StringBuilder)
• StringBuilder class is used to manipulate modifiable strings
• StringBuilder class is non-synchronized
• String Vs StringBuilder classes
• String class is immutable where as StringBuilder class is mutable
• Remaining are the same
• StringBuilder Vs StringBuilder classes
• StringBuilder class is non-synchronized where as StringBuffer class is
synchronized
• Both classes are mutable
• Remaining are the same
• There are 3 constructors in StringBuilder class
• Supports 7 methods 25
StringBuilder Class Constructors
Constructor Purpose Example

StringBuilder sb1=new StringBuilder();


StringBuilder() To create an empty string builder // creates an empty string builder of size 0

StringBuilder(String str) To create a string builder with the StringBuilder sb2=new StringBuilder(“Hai”);
given string // creates a string builder with <Hai>

To create an empty string builder StringBuilder sb3=new StringBuilder(25);


StringBuilder(int size) // creates an empty string builder of size 0
Demo Program
StringBuilder Class Methods
1. append - to add string at end

2. insert - to insert a substring at given index

3. replace - to substitute a substring at given index

4. delete - to remove the characters at given index

5. reverse - to change the content in reverse order

6. capacity- to check the allocated builder size (not length of content)

7. ensureCapacity – to confirm the allocated builder size


Method Purpose Example
StringBuilder sb=new StringBuilder(“Hai”);
append (str) To add a new string at the end sb.append(“, Welcome!”);  Hai, Welcome!
Demo Program
StringBuilder sb=new StringBuilder(“How R U?”);
insert (pos, str) To add a new string at any given sb.insert(0, “Hai,”);  Hai, How R U?
position
Demo Program
To change the content of an StringBuilder sb=new StringBuilder(“Hai!”);
existing string with given start
replace (startIndex, and end index values sb.replace(1,sb.length(),”ello!”);  Hello!
endIndex, newStr) (builder length adjusted by
default) Demo Program

StringBuilder sb=new StringBuilder(“Good Day!”);


delete (startIndex, To remove letters from an
existing string by using start sb.delete(4, sb.length());  Good
endIndex)
and end index values
Demo Program
Method Purpose Example
StringBuilder sb = new StringBuilder(“ABC”);
reverse() To chang=e the given string into sb.reverse();  CBA
reverse order
Demo Program

To check the size of the allocated StringBuilder sb=new StringBuilder(“”);


builder. Automatic expansion sb.capacity();  16
capacity() would be done by using
(oldSize*2)+2 Demo Program

StringBuilder sb=new StringBuilder(“Welcome”);


To confirm the allocated builder sb.capacity();  16
ensureCapacity (int) size. Automatic expansion would sb.ensureCapacity(20);  34
be done by using (oldSize*2)+2
Demo Program
StringBuilder sb=new StringBuilder(“Hello!”);
setLength(int) To customize StringBuilder size sb.length() ; 6
sb.setLength(2);
sb.length();  2 Demo Program
String Class
Vs
StringBuffer Class
Vs
StringBuilder Class
30
String class StringBuffer class

Immutable Mutable
(if we try to change, a new object gets created) (allows changes)

Slow and consumes more memory


Fast and consumes less memory
(because every time it creates new instance)

Overrides the equals() of Object class Doesn’t override the equals() of Object class
(which allows us to compare strings) (so we cannot compare strings)

The length of the string object is fixed The length of the StringBuffer can be increased

Stores in string constant pool Stores in heap memory


StringBuffer class StringBuilder class

Synchronized (thread safe)


Non-synchronized (not-thread safe)
(two threads can’t call the methods of
(two threads can call the methods of
StringBuffer simultaneously OR all method
StringBuilder simultaneously)
which modifies the internal datas is
synchronized)

Less efficient More efficient

Very slow Very fast

We can convert a StringBuffer into string


by calling toString() We can’t
String class StringBuilder class
Immutable Mutable

Slow Very fast

Thread safe Non-tread safe

Storage is constant string pool Storage is heap

We can use equals() to compare strings


We can’t (doesn’t override equals())
(because overrides equals())

Length is fixed Length is adjustable

We can create a String object without


using a new operator Requires new operator to create objects
Thank You

34

You might also like