SlideShare a Scribd company logo
1 of 22
DAY 5
String,StringBuffer
1. Unlike C and C++, String in Java doesn't terminate with null character. Instead
String are Object in Java and backed by character array. You can get the character
array used to represent String in Java by calling toCharArray() method
of java.lang.String class of JDK.
2. Strings are immutable in Java it means once created you cannot modify content of
String. If you modify it by using toLowerCase(), toUpperCase() or any other
method, It always result in new String. Since String is final there is no way anyone
can extend String or override any of String functionality.
3. String is special class in Java and all String literal e.g. "abc" (anything which is
inside double quotes are String literal in Java) are maintained in a separate String
pool, special memory location inside Java memory. Any time you create a new
String object using String literal, JVM first checks String pool and if an object with
similar content available, than it returns that and doesn't create a new object. JVM
doesn't perform String pool check if you create object using new operator.
What is so SPECIAL about Strings in JAVA?
Char array vs String Declaration
String is an array of characters, represented as:
//String is an array of characters
char[] arrSample = {'R', 'O', 'S', 'E’};
String strSample_1 = new String (arrSample);
In technical terms, the String is defined as follows in the above example-
= new (argument);
Now we always cannot write our strings as arrays; hence we can define the String in Java
//Representation of String
String strSample_2 = "ROSE";
In JAVA strings are class objects and
implemented using two classes:-
String
StringBuffer.
Immutability
1. In java, string objects are immutable. Immutable simply means
unmodifiable or unchangeable. Once string object is created its data or
state can't be changed but a new string object is created.
eg: Suppose there are 5 reference variables, all refers to one
object "sachin".If one reference variable changes the value of the object,
it will be affected to all the reference variables. That is why string
objects are immutable in java.
2. Once string object is created its data or state can't be changed but a
new string object is created.
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutabl
e objects
}
} Here Sachin is not changed but a new object is created with
sachintendulkar. That is why string is known as immutable.
Disadvantages of Immutability
Less efficient — you need to create a new string and throw away the old one even for
small changes.
Example: class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not
modified.
• There are two ways to create String object:
1) By string literal. 2)By new keyword.
1) By string literal: no new object will be created.
For Example: String s1=“welcome";
String s2=“welcome”;
2) By new keyword:- create two objects and one reference variable
For Example: String s=new String(“Sachin");
String s=new String(“SachinTendulkar");//.
Does Java create 2 String objects internally?
Without “new” operator for String creation:
– Java looks into a String pool (collection of String objects).
– Try to find objects with same string value.
– If object exists new variable points to existing object.
– If object does not exist new object is created.
Efficiency reasons – to limit object creation
String greeting1 = “Hello Utah!”
String greeting2 = “Hello Utah!”
Concept of String pooling
greeting2
“Hello Utah!”
greeting1
Local Variable Table Pool of String Objects
w/o new operator both the objects point to same variable in string pool.
greeting2
greeting1
“Hello Utah!”
“Hello Utah!”
Using new operator
With new operator a memory will be allocated for every object .
Example – String methods
public class StringAll {
public static void main(String args[]) {
String str = "Java";
System.out.println(str.replace('v','V'));
System.out.println(str.length());
System.out.println(str.charAt(2));
System.out.println(str.equalsIgnoreCase("JAVA"));
System.out.println(str.toLowerCase());
System.out.println(str.toUpperCase());
System.out.println(str.trim());
String[] strArray = str.split("a");
for(String eachString:strArray){
System.out.println(eachString);
}
System.out.println(str.startsWith("co"));
System.out.println(str.indexOf("v"));
String str1 = "GodBlessUAll";
System.out.println(str1.substring(4));
}
}
String Methods
Method Description
char charAt(int index) returns char value for the particular
index
int length() returns string length
static String format(String format, Object... args) returns a formatted string.
String substring(int beginIndex) returns substring for given begin
index.
String substring(int beginIndex, int endIndex) returns substring for given begin
index and end index.
boolean contains(CharSequence s) returns true or false after matching
the sequence of char value.
boolean isEmpty() checks if string is empty.
String concat(String str) concatenates the specified string.
String replace(char old, char new) replaces all occurrences of the
specified char value.
String replace(CharSequence old, CharSequence new) replaces all occurrences of the
specified CharSequence.
static String equalsIgnoreCase(String another) compares another string. It doesn't check case.
String[] split(String regex) returns a split string matching regex.
String[] split(String regex, int limit) returns a split string matching regex and limit.
int indexOf(int ch) returns the specified char value index.
int indexOf(int ch, int fromIndex) returns the specified char value index starting
with given index.
int indexOf(String substring) returns the specified substring index.
int indexOf(String substring, int fromIndex) returns the specified substring index starting with
given index.
String toLowerCase() returns a string in lowercase.
String toLowerCase(Locale l) returns a string in lowercase using specified
locale.
String toUpperCase() returns a string in uppercase.
String trim() removes beginning and ending spaces of this
string.
static String valueOf(int value) converts given type into string. It is an overloaded
method.
String word1 = “re”;
String word2 = “think”;
String word3 = “ing”;
How to combine and make “rethinking” ?
Method 1: Plus “+” operator
String str = word1 + word2;
concatenates word1 and word2 “rethink”
Method 2: Use String’s “concat” method
String str = word1.concat (word2);
Now str has value “rethink”, how to make “rethinking”?
String word3 = “ing”;
Method 3: Shorthand
str += word3; //results in “rethinking” (same as method1)
What if we wanted to combine String values?
CompareString
String s1 = "ABCD”;
String s2 = "ABCD”;
if(s1 == s2)
System.out.println("Equal");
else
System.out.println("NOT Equal");
In Java, when the“==” operator is used to
compare2 objects, it checks to see if the
objects refer to the same place in memory.
To check if strings have same data, use equals
String s1 = new String("ABCD");
String s2 = new String("ABCD");
if(s1.equals(s2))
System.out.println("Equal");
else
System.out.println("NOT Equal");
What is mutable string?
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
STRINGBUFFER class creates strings flexible length that can be modified in terms of both length
and content.
STRINGBUFFER may have characters and substrings inserted in the middle or appended to the
end.
STRINGBUFFER automatically grows to make room for such additions.
StringBuffer
String Buffer():- Reserves room for 16 characters without reallocation
StringBuffer(int size):- Accepts an integer argunent that explicilty sets the size of
the buffer
StringBuffer(String str):- Accepts STRING argument that sets the initial contents
of the STRINGBUFFER and allocated room for 16 additional characters.
STRINGBUFFER
CONSTRUCTORS
Example - Methods
public class StringBuff {
public static void main(String args[]) {
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
sb.delete(1,3);
System.out.println(sb);//prints Hlo
sb.reverse();
System.out.println(sb);//prints olleH
sb.append("java is my favourite language");
System.out.println(sb.capacity());
sb.ensureCapacity(10);
System.out.println(sb.capacity());
sb.ensureCapacity(50);
System.out.println(sb.capacity());
}
}
Modifier and Type Method Description
public synchronized StringBuffer append(String s) is used to append the specified string
with this string. The append() method
is overloaded like append(char),
append(boolean), append(int),
append(float), append(double) etc.
public synchronized StringBuffer insert(int offset, String s) is used to insert the specified string
with this string at 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 synchronized StringBuffer replace(int startIndex, int endIndex, String str) is used to replace the string from
specified startIndex and endIndex.
public synchronized StringBuffer delete(int startIndex, int endIndex) is used to delete the string from
specified startIndex and endIndex.
public synchronized StringBuffer reverse() is used to reverse the string.
public int capacity() is used to return the current capacity.
public void ensureCapacity(int minimumCapacity) is used to ensure the capacity at least
equal to the given minimum.
public char charAt(int index) is used to return the character at the
specified position.
public int length() is used to return the length of the
string i.e. total number of characters.
public String substring(int beginIndex) is used to return the substring from the
specified beginIndex.
public String substring(int beginIndex, int endIndex) is used to return the substring from the
specified beginIndex and endIndex.
String Buffer Methods
Discussion Questions
Question 1: What is the use of ensureCapacity()?
Question 2: Explain the scenarios to choose between String and StringBuffer ?
Question 3: In how many ways you can create string objects in java?
Choose the correct Option
Q 1. If two strings are same, then method public int compareTo returns:
a)Null
b) Positive
c) Negative
d) Zero
Q 2. All operands are appended by calling toString method, if needed:
a) True
b) False
c) None of these
THANK YOU

More Related Content

Similar to Day_5.1.pptx

3.7_StringBuilder.pdf
3.7_StringBuilder.pdf3.7_StringBuilder.pdf
3.7_StringBuilder.pdfAnanthi68
 
Fileoperations.pptx
Fileoperations.pptxFileoperations.pptx
Fileoperations.pptxVeenaNaik23
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Text processing
Text processingText processing
Text processingIcancode
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanKavita Ganesan
 
Java Presentation on the topic of string
Java Presentation  on the topic of stringJava Presentation  on the topic of string
Java Presentation on the topic of stringRajTangadi
 
In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...Indu32
 
OCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsOCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsİbrahim Kürce
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesPrabu U
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................suchitrapoojari984
 

Similar to Day_5.1.pptx (20)

package
packagepackage
package
 
8. String
8. String8. String
8. String
 
3.7_StringBuilder.pdf
3.7_StringBuilder.pdf3.7_StringBuilder.pdf
3.7_StringBuilder.pdf
 
Strings
StringsStrings
Strings
 
Strings in java
Strings in javaStrings in java
Strings in java
 
Fileoperations.pptx
Fileoperations.pptxFileoperations.pptx
Fileoperations.pptx
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Text processing
Text processingText processing
Text processing
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
String handling
String handlingString handling
String handling
 
String in java
String in javaString in java
String in java
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 
Java Presentation on the topic of string
Java Presentation  on the topic of stringJava Presentation  on the topic of string
Java Presentation on the topic of string
 
In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...
 
OCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsOCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIs
 
Strings.ppt
Strings.pptStrings.ppt
Strings.ppt
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and Interfaces
 
07slide
07slide07slide
07slide
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................
 

Recently uploaded

INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 

Recently uploaded (20)

INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 

Day_5.1.pptx

  • 2. 1. Unlike C and C++, String in Java doesn't terminate with null character. Instead String are Object in Java and backed by character array. You can get the character array used to represent String in Java by calling toCharArray() method of java.lang.String class of JDK. 2. Strings are immutable in Java it means once created you cannot modify content of String. If you modify it by using toLowerCase(), toUpperCase() or any other method, It always result in new String. Since String is final there is no way anyone can extend String or override any of String functionality. 3. String is special class in Java and all String literal e.g. "abc" (anything which is inside double quotes are String literal in Java) are maintained in a separate String pool, special memory location inside Java memory. Any time you create a new String object using String literal, JVM first checks String pool and if an object with similar content available, than it returns that and doesn't create a new object. JVM doesn't perform String pool check if you create object using new operator. What is so SPECIAL about Strings in JAVA?
  • 3. Char array vs String Declaration String is an array of characters, represented as: //String is an array of characters char[] arrSample = {'R', 'O', 'S', 'E’}; String strSample_1 = new String (arrSample); In technical terms, the String is defined as follows in the above example- = new (argument); Now we always cannot write our strings as arrays; hence we can define the String in Java //Representation of String String strSample_2 = "ROSE"; In JAVA strings are class objects and implemented using two classes:- String StringBuffer.
  • 4. Immutability 1. In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable. Once string object is created its data or state can't be changed but a new string object is created. eg: Suppose there are 5 reference variables, all refers to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java. 2. Once string object is created its data or state can't be changed but a new string object is created. class Testimmutablestring{ public static void main(String args[]){ String s="Sachin"; s.concat(" Tendulkar");//concat() method appends the string at the end System.out.println(s);//will print Sachin because strings are immutabl e objects } } Here Sachin is not changed but a new object is created with sachintendulkar. That is why string is known as immutable.
  • 5. Disadvantages of Immutability Less efficient — you need to create a new string and throw away the old one even for small changes. Example: class Testimmutablestring1{ public static void main(String args[]){ String s="Sachin"; s=s.concat(" Tendulkar"); System.out.println(s); } } In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not modified.
  • 6. • There are two ways to create String object: 1) By string literal. 2)By new keyword. 1) By string literal: no new object will be created. For Example: String s1=“welcome"; String s2=“welcome”;
  • 7. 2) By new keyword:- create two objects and one reference variable For Example: String s=new String(“Sachin"); String s=new String(“SachinTendulkar");//.
  • 8. Does Java create 2 String objects internally? Without “new” operator for String creation: – Java looks into a String pool (collection of String objects). – Try to find objects with same string value. – If object exists new variable points to existing object. – If object does not exist new object is created. Efficiency reasons – to limit object creation String greeting1 = “Hello Utah!” String greeting2 = “Hello Utah!”
  • 9. Concept of String pooling greeting2 “Hello Utah!” greeting1 Local Variable Table Pool of String Objects w/o new operator both the objects point to same variable in string pool.
  • 10. greeting2 greeting1 “Hello Utah!” “Hello Utah!” Using new operator With new operator a memory will be allocated for every object .
  • 11. Example – String methods public class StringAll { public static void main(String args[]) { String str = "Java"; System.out.println(str.replace('v','V')); System.out.println(str.length()); System.out.println(str.charAt(2)); System.out.println(str.equalsIgnoreCase("JAVA")); System.out.println(str.toLowerCase()); System.out.println(str.toUpperCase()); System.out.println(str.trim()); String[] strArray = str.split("a"); for(String eachString:strArray){ System.out.println(eachString); } System.out.println(str.startsWith("co")); System.out.println(str.indexOf("v")); String str1 = "GodBlessUAll"; System.out.println(str1.substring(4)); } }
  • 12. String Methods Method Description char charAt(int index) returns char value for the particular index int length() returns string length static String format(String format, Object... args) returns a formatted string. String substring(int beginIndex) returns substring for given begin index. String substring(int beginIndex, int endIndex) returns substring for given begin index and end index. boolean contains(CharSequence s) returns true or false after matching the sequence of char value. boolean isEmpty() checks if string is empty. String concat(String str) concatenates the specified string. String replace(char old, char new) replaces all occurrences of the specified char value. String replace(CharSequence old, CharSequence new) replaces all occurrences of the specified CharSequence.
  • 13. static String equalsIgnoreCase(String another) compares another string. It doesn't check case. String[] split(String regex) returns a split string matching regex. String[] split(String regex, int limit) returns a split string matching regex and limit. int indexOf(int ch) returns the specified char value index. int indexOf(int ch, int fromIndex) returns the specified char value index starting with given index. int indexOf(String substring) returns the specified substring index. int indexOf(String substring, int fromIndex) returns the specified substring index starting with given index. String toLowerCase() returns a string in lowercase. String toLowerCase(Locale l) returns a string in lowercase using specified locale. String toUpperCase() returns a string in uppercase. String trim() removes beginning and ending spaces of this string. static String valueOf(int value) converts given type into string. It is an overloaded method.
  • 14. String word1 = “re”; String word2 = “think”; String word3 = “ing”; How to combine and make “rethinking” ? Method 1: Plus “+” operator String str = word1 + word2; concatenates word1 and word2 “rethink” Method 2: Use String’s “concat” method String str = word1.concat (word2); Now str has value “rethink”, how to make “rethinking”? String word3 = “ing”; Method 3: Shorthand str += word3; //results in “rethinking” (same as method1) What if we wanted to combine String values?
  • 15. CompareString String s1 = "ABCD”; String s2 = "ABCD”; if(s1 == s2) System.out.println("Equal"); else System.out.println("NOT Equal"); In Java, when the“==” operator is used to compare2 objects, it checks to see if the objects refer to the same place in memory. To check if strings have same data, use equals String s1 = new String("ABCD"); String s2 = new String("ABCD"); if(s1.equals(s2)) System.out.println("Equal"); else System.out.println("NOT Equal");
  • 16. What is mutable string? A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string. STRINGBUFFER class creates strings flexible length that can be modified in terms of both length and content. STRINGBUFFER may have characters and substrings inserted in the middle or appended to the end. STRINGBUFFER automatically grows to make room for such additions. StringBuffer
  • 17. String Buffer():- Reserves room for 16 characters without reallocation StringBuffer(int size):- Accepts an integer argunent that explicilty sets the size of the buffer StringBuffer(String str):- Accepts STRING argument that sets the initial contents of the STRINGBUFFER and allocated room for 16 additional characters. STRINGBUFFER CONSTRUCTORS
  • 18. Example - Methods public class StringBuff { public static void main(String args[]) { StringBuffer sb=new StringBuffer("Hello "); sb.append("Java");//now original string is changed System.out.println(sb);//prints Hello Java sb.insert(1,"Java");//now original string is changed System.out.println(sb);//prints HJavaello sb.replace(1,3,"Java"); System.out.println(sb);//prints HJavalo sb.delete(1,3); System.out.println(sb);//prints Hlo sb.reverse(); System.out.println(sb);//prints olleH sb.append("java is my favourite language"); System.out.println(sb.capacity()); sb.ensureCapacity(10); System.out.println(sb.capacity()); sb.ensureCapacity(50); System.out.println(sb.capacity()); } }
  • 19. Modifier and Type Method Description public synchronized StringBuffer append(String s) is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc. public synchronized StringBuffer insert(int offset, String s) is used to insert the specified string with this string at 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 synchronized StringBuffer replace(int startIndex, int endIndex, String str) is used to replace the string from specified startIndex and endIndex. public synchronized StringBuffer delete(int startIndex, int endIndex) is used to delete the string from specified startIndex and endIndex. public synchronized StringBuffer reverse() is used to reverse the string. public int capacity() is used to return the current capacity. public void ensureCapacity(int minimumCapacity) is used to ensure the capacity at least equal to the given minimum. public char charAt(int index) is used to return the character at the specified position. public int length() is used to return the length of the string i.e. total number of characters. public String substring(int beginIndex) is used to return the substring from the specified beginIndex. public String substring(int beginIndex, int endIndex) is used to return the substring from the specified beginIndex and endIndex. String Buffer Methods
  • 20. Discussion Questions Question 1: What is the use of ensureCapacity()? Question 2: Explain the scenarios to choose between String and StringBuffer ? Question 3: In how many ways you can create string objects in java?
  • 21. Choose the correct Option Q 1. If two strings are same, then method public int compareTo returns: a)Null b) Positive c) Negative d) Zero Q 2. All operands are appended by calling toString method, if needed: a) True b) False c) None of these