SlideShare a Scribd company logo
6
Strings in Java
• Strings are implemented as two classes in Java
• java.lang.String provides an unchangeable
String object
• java.lang.StringBuffer provides a String object
that can be amended
Most read
17
More on StringBuffer Class
• StringBuffer objects are mutable and capacity
& length affect performance
• If the StringBuffer object needs to be
expanded during an append or insert, a new
array is created and the old data copied to it
• Use capacity() and ensureCapacity(int)
methods to minimize expansions
Most read
19
Length v. Capacity con’t
• Examples of length() and capacity() methods
StringBuffer buf = new StringBuffer(25);// creates
StringBuffer with length 25
buf.append("13 Characters"); // appends 13
characters
int len = buf.length(); // length() returns 13
int cap = buf.capacity(); // capacity returns 25
Most read
Packages
Creating package
• include a package command as the first statement
in a Java source file.
– the classes declared within that file will belong to the
specified package.
• The package statement defines a name space in
which classes are stored.
– the class names are put into the default package, which
has no name.
package pkg;
package pkg1[.pkg2[.pkg3]];
e.g., package java.awt.image;
Access Protection
Strings
Strings
• Strings are fundamental part of all computing
languages.
• At the basic level, they are just a data structure
that can hold a series of characters
• However, strings are not implemented as a
character array in Java as in other languages.
Strings in Java
• Strings are implemented as two classes in Java
• java.lang.String provides an unchangeable
String object
• java.lang.StringBuffer provides a String object
that can be amended
Basic String Methods
• length() returns the length of the string
• toLowerCase() converts the string to lower
case
• toUpperCase() converts the string to upper
case
• replace(char, char) replaces occurrences of
one character with another character
Basic Strings continued
• Basic strings are not meant to change
frequently so there are no add or append
methods
• However the concat(String) method does
allow two strings to be concatenated together
Basic Strings continued
• Substrings of a String object can also be
accessed
• A portion of String object can be copied to a
character array using the getChars() method
• The substring() method can return substring
beginning at a specified offset
Searching a string
• Methods for searching strings
– indexOf(x) searches for the first occurrence of x
– indexOf(x, y) searches for the first occurrence of x
after the offset of y
– lastIndexOf(x) searches backwards for the first
occurrence of x
– lastIndexOf(x, y) searches backwards for the first
occurrence of x after the offset of y
Example of string search
• indexOf(x) and indexOf(x, y) can find all occurrences of a
character(s) in a string
public void paint(Graphics g) {
String str = new String("Wish You Were Here");
int count = 0;
int fromIndex = 0;
while(fromIndex != -1) {
fromIndex = str.indexOf("er", fromIndex);
if (fromIndex != -1) {
count++;
fromIndex++;
}
}
g.drawString(String.valueOf(count), 10, 10); }
Strings In OOP(Object oriented programming)
Parsing Strings
• Strings can be parsed with the StringTokenizer class
• The default delimiters (space, tab, newline and carriage
return) can be used for parsing sentences
• By specifying different delimiters, a wide variety of
strings may be parsed
Parsing Strings continued
• Different default constructors are provided
– Tokenize the string based on the default
delimiters
– Tokenize the string based on a specified set of
delimiters
– Tokenize the string based on a specified set of
delimiters with a boolean flag to specify whether
the delimiters should also be returned as tokens
StringBuffer class
• The StringBuffer class is provided for strings
that need may need to be changed
• The StringBuffer class contains methods for
both inserting and appending text
• An object created as a StringBuffer can easily
be converted to an object of the String class if
needed
More on StringBuffer Class
• Conversion may be needed because many Java
library methods expect a string
• The toString() method is used for converting a
StringBuffer object to a String object
• Example of converting a StringBuffer to a String:
public void paint(Graphics g) {
StringBuffer buf = new StringBuffer("Hello, World");
g.drawString(buf.toString(), 10, 10);
}
More on StringBuffer Class
• StringBuffer objects are mutable and capacity
& length affect performance
• If the StringBuffer object needs to be
expanded during an append or insert, a new
array is created and the old data copied to it
• Use capacity() and ensureCapacity(int)
methods to minimize expansions
Length v. Capacity
• The length() method returns the length of the string
in the StringBuffer
• The capacity() method returns the total “space” in a
StringBuffer
• The ensureCapacity(int) method insures the
StringBuffer has at least the specified amount of
capacity remaining
Length v. Capacity con’t
• Examples of length() and capacity() methods
StringBuffer buf = new StringBuffer(25);// creates
StringBuffer with length 25
buf.append("13 Characters"); // appends 13
characters
int len = buf.length(); // length() returns 13
int cap = buf.capacity(); // capacity returns 25
Bibliography
• http://www.eimc.brad.ac.uk/java/tutorial/Pro
ject/4/string.htm
• http://www.scism.sbu.ac.uk/jfl/Appa/appa5.h
tml
• http://docs.rinet.ru:8080/WebJPP/contents.ht
m
• http://www.javaworld.com/javaworld/jw-10-
2002/jw-1004-java101guide.html

More Related Content

What's hot (20)

Java package
Java packageJava package
Java package
CS_GDRCST
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-thread
javaicon
 
Presentations on web database
Presentations on web databasePresentations on web database
Presentations on web database
District Administration
 
Packages in java
Packages in javaPackages in java
Packages in java
Elizabeth alexander
 
Html forms
Html formsHtml forms
Html forms
eShikshak
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
Farooq Baloch
 
Transmission media (data communication)
Transmission media (data communication)Transmission media (data communication)
Transmission media (data communication)
Pritom Chaki
 
Css types internal, external and inline (1)
Css types internal, external and inline (1)Css types internal, external and inline (1)
Css types internal, external and inline (1)
Webtech Learning
 
Guided Transmission Media
Guided Transmission MediaGuided Transmission Media
Guided Transmission Media
asrabatool
 
Packages in java
Packages in javaPackages in java
Packages in java
jamunaashok
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
Ravinder Kamboj
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQL
Pooja Dixit
 
Sgml
SgmlSgml
Sgml
rahul kundu
 
Guided And Unguided Media
Guided And Unguided MediaGuided And Unguided Media
Guided And Unguided Media
Rajesh Yadav
 
Isam
IsamIsam
Isam
Javed Khan
 
Html text and formatting
Html text and formattingHtml text and formatting
Html text and formatting
eShikshak
 
Method overloading
Method overloadingMethod overloading
Method overloading
Lovely Professional University
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
Anurag
 
Method overriding
Method overridingMethod overriding
Method overriding
Azaz Maverick
 

Similar to Strings In OOP(Object oriented programming) (20)

Java string handling
Java string handlingJava string handling
Java string handling
Salman Khan
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string class
fedcoordinator
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
Abhilash Nair
 
STRING CLASS AND STRING BUFFER CLASS CONCEPTS IN JAVA
STRING CLASS AND STRING BUFFER CLASS CONCEPTS IN JAVASTRING CLASS AND STRING BUFFER CLASS CONCEPTS IN JAVA
STRING CLASS AND STRING BUFFER CLASS CONCEPTS IN JAVA
pkavithascs
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
teach4uin
 
Java Strings
Java StringsJava Strings
Java Strings
RaBiya Chaudhry
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and Interfaces
Prabu U
 
Java String
Java String Java String
Java String
SATYAM SHRIVASTAV
 
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
 
Day_5.1.pptx
Day_5.1.pptxDay_5.1.pptx
Day_5.1.pptx
ishasharma835109
 
Java Strings methods and operations.ppt
Java Strings  methods and operations.pptJava Strings  methods and operations.ppt
Java Strings methods and operations.ppt
JyothiAmpally
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
Shahjahan Samoon
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
Shahjahan Samoon
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
String.ppt
String.pptString.ppt
String.ppt
ajeela mushtaq
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper classJava string , string buffer and wrapper class
Java string , string buffer and wrapper class
SimoniShah6
 
Strings
StringsStrings
Strings
naslin prestilda
 
Java string handling
Java string handlingJava string handling
Java string handling
GaneshKumarKanthiah
 
Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdf
learnEnglish51
 
STRING FUNCTIONS IN JAVA BY N SARATH KUMAR
STRING FUNCTIONS IN JAVA BY N SARATH KUMARSTRING FUNCTIONS IN JAVA BY N SARATH KUMAR
STRING FUNCTIONS IN JAVA BY N SARATH KUMAR
Sarathkumar Narsupalli
 
Java string handling
Java string handlingJava string handling
Java string handling
Salman Khan
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string class
fedcoordinator
 
STRING CLASS AND STRING BUFFER CLASS CONCEPTS IN JAVA
STRING CLASS AND STRING BUFFER CLASS CONCEPTS IN JAVASTRING CLASS AND STRING BUFFER CLASS CONCEPTS IN JAVA
STRING CLASS AND STRING BUFFER CLASS CONCEPTS IN JAVA
pkavithascs
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
teach4uin
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and Interfaces
Prabu U
 
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
 
Java Strings methods and operations.ppt
Java Strings  methods and operations.pptJava Strings  methods and operations.ppt
Java Strings methods and operations.ppt
JyothiAmpally
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
Shahjahan Samoon
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
Shahjahan Samoon
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper classJava string , string buffer and wrapper class
Java string , string buffer and wrapper class
SimoniShah6
 
Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdf
learnEnglish51
 
STRING FUNCTIONS IN JAVA BY N SARATH KUMAR
STRING FUNCTIONS IN JAVA BY N SARATH KUMARSTRING FUNCTIONS IN JAVA BY N SARATH KUMAR
STRING FUNCTIONS IN JAVA BY N SARATH KUMAR
Sarathkumar Narsupalli
 
Ad

Recently uploaded (20)

Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
Coleoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptxColeoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptx
Arshad Shaikh
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
How to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRMHow to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRM
Celine George
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..
faizanaltaf231
 
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
National Information Standards Organization (NISO)
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
Search Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website SuccessSearch Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website Success
Muneeb Rana
 
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfForestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
ChalaKelbessa
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
Coleoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptxColeoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptx
Arshad Shaikh
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
How to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRMHow to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRM
Celine George
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..
faizanaltaf231
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
Search Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website SuccessSearch Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website Success
Muneeb Rana
 
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfForestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
ChalaKelbessa
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
Ad

Strings In OOP(Object oriented programming)

  • 2. Creating package • include a package command as the first statement in a Java source file. – the classes declared within that file will belong to the specified package. • The package statement defines a name space in which classes are stored. – the class names are put into the default package, which has no name. package pkg; package pkg1[.pkg2[.pkg3]]; e.g., package java.awt.image;
  • 5. Strings • Strings are fundamental part of all computing languages. • At the basic level, they are just a data structure that can hold a series of characters • However, strings are not implemented as a character array in Java as in other languages.
  • 6. Strings in Java • Strings are implemented as two classes in Java • java.lang.String provides an unchangeable String object • java.lang.StringBuffer provides a String object that can be amended
  • 7. Basic String Methods • length() returns the length of the string • toLowerCase() converts the string to lower case • toUpperCase() converts the string to upper case • replace(char, char) replaces occurrences of one character with another character
  • 8. Basic Strings continued • Basic strings are not meant to change frequently so there are no add or append methods • However the concat(String) method does allow two strings to be concatenated together
  • 9. Basic Strings continued • Substrings of a String object can also be accessed • A portion of String object can be copied to a character array using the getChars() method • The substring() method can return substring beginning at a specified offset
  • 10. Searching a string • Methods for searching strings – indexOf(x) searches for the first occurrence of x – indexOf(x, y) searches for the first occurrence of x after the offset of y – lastIndexOf(x) searches backwards for the first occurrence of x – lastIndexOf(x, y) searches backwards for the first occurrence of x after the offset of y
  • 11. Example of string search • indexOf(x) and indexOf(x, y) can find all occurrences of a character(s) in a string public void paint(Graphics g) { String str = new String("Wish You Were Here"); int count = 0; int fromIndex = 0; while(fromIndex != -1) { fromIndex = str.indexOf("er", fromIndex); if (fromIndex != -1) { count++; fromIndex++; } } g.drawString(String.valueOf(count), 10, 10); }
  • 13. Parsing Strings • Strings can be parsed with the StringTokenizer class • The default delimiters (space, tab, newline and carriage return) can be used for parsing sentences • By specifying different delimiters, a wide variety of strings may be parsed
  • 14. Parsing Strings continued • Different default constructors are provided – Tokenize the string based on the default delimiters – Tokenize the string based on a specified set of delimiters – Tokenize the string based on a specified set of delimiters with a boolean flag to specify whether the delimiters should also be returned as tokens
  • 15. StringBuffer class • The StringBuffer class is provided for strings that need may need to be changed • The StringBuffer class contains methods for both inserting and appending text • An object created as a StringBuffer can easily be converted to an object of the String class if needed
  • 16. More on StringBuffer Class • Conversion may be needed because many Java library methods expect a string • The toString() method is used for converting a StringBuffer object to a String object • Example of converting a StringBuffer to a String: public void paint(Graphics g) { StringBuffer buf = new StringBuffer("Hello, World"); g.drawString(buf.toString(), 10, 10); }
  • 17. More on StringBuffer Class • StringBuffer objects are mutable and capacity & length affect performance • If the StringBuffer object needs to be expanded during an append or insert, a new array is created and the old data copied to it • Use capacity() and ensureCapacity(int) methods to minimize expansions
  • 18. Length v. Capacity • The length() method returns the length of the string in the StringBuffer • The capacity() method returns the total “space” in a StringBuffer • The ensureCapacity(int) method insures the StringBuffer has at least the specified amount of capacity remaining
  • 19. Length v. Capacity con’t • Examples of length() and capacity() methods StringBuffer buf = new StringBuffer(25);// creates StringBuffer with length 25 buf.append("13 Characters"); // appends 13 characters int len = buf.length(); // length() returns 13 int cap = buf.capacity(); // capacity returns 25
  • 20. Bibliography • http://www.eimc.brad.ac.uk/java/tutorial/Pro ject/4/string.htm • http://www.scism.sbu.ac.uk/jfl/Appa/appa5.h tml • http://docs.rinet.ru:8080/WebJPP/contents.ht m • http://www.javaworld.com/javaworld/jw-10- 2002/jw-1004-java101guide.html