SlideShare a Scribd company logo
1 of 31
Strings
"Chapter 10"
Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
Java Methods
Object-Oriented Programming
and Data Structures
Maria Litvin ● Gary Litvin
2nd AP edition  with GridWorld
10-2
Objectives:
• Learn about literal strings
• Learn about String constructors and
commonly used methods
• Understand immutability of strings
• Learn to format numbers into strings and
extract numbers from strings
• Learn several useful methods of the
Character class
• Learn about the StringBuffer class
10-3
The String class
• An object of the String class represents a
string of characters.
• The String class belongs to the java.lang
package, which is built into Java.
• Like other classes, String has constructors
and methods.
• Unlike other classes, String has two
operators, + and += (used for concatenation).
10-4
Literal Strings
• Literal strings are anonymous constant
objects of the String class that are defined as
text in double quotes.
• Literal strings don’t have to be constructed:
they are “just there.”
10-5
Literal Strings (cont’d)
• can be assigned to String variables.
• can be passed to methods and constructors
as parameters.
• have methods you can call:
String fileName = "fish.dat";
button = new JButton("Next slide");
if ("Start".equals(cmd)) ...
10-6
Literal Strings (cont’d)
• The string text may include “escape”
characters (described in Section 6.5).
For example:
  stands for 
 n stands for newline
String s1 = "Biology”;
String s2 = "C:jdk1.4docs";
String s3 = "Hellon";
10-7
Immutability
• Once created, a string cannot be changed:
none of its methods can change the string.
• Such objects are called immutable.
• Immutable objects are convenient because
several references can point to the same
object safely: there is no danger of changing
an object through one reference without the
others being aware of the change.
10-8
Immutability (cont’d)
• Advantage: more efficient, no need to copy.
String s1 = "Sun";
String s2 = s1;
String s1 = "Sun";
String s2 = new String(s1);
s1
s2
s1
s2
OK Less efficient:
wastes memory
"Sun"
"Sun"
"Sun"
10-9
Immutability (cont’d)
• Disadvantage: less efficient — you need to
create a new string and throw away the old
one for every small change.
String s = "sun";
char ch = Character.toUpperCase(s.charAt (0));
s = ch + s.substring (1);
s "sun"
"Sun"
10-10
Empty Strings
• An empty string has no characters; its
length is 0.
• Not to be confused with an uninitialized
string:
String s1 = "";
String s2 = new String();
private String errorMsg; errorMsg
is null
Empty strings
10-11
Constructors
• String’s no-args and copy constructors are
not used much.
• Other constructors convert arrays
(Chapter 12) into strings
String s1 = new String ();
String s2 = new String (s1);
String s1 = "";
String s2 = s1;
10-12
Methods — length, charAt
int length ();
char charAt (k);
• Returns the number of
characters in the string
• Returns the k-th char
6
'n'
”Flower".length();
”Wind".charAt (2);
Returns:
Character positions in strings
are numbered starting from 0
10-13
Methods — substring
String s2 = s.substring (i, j);
returns the substring of chars in
positions from i to j-1
String s2 = s.substring (i);
returns the substring from the i-th
char to the end
"raw"
"happy"
"" (empty string)
”strawberry".substring (2,5);
"unhappy".substring (2);
"emptiness".substring (9);
Returns:
strawberry
i j
strawberry
i
10-14
Methods — Concatenation
String result = s1 + s2;
concatenates s1 and s2
String result = s1.concat (s2);
the same as s1 + s2
result += s3;
concatenates s3 to result
result += num;
converts num to String and concatenates it to
result
10-15
Methods — Find (indexOf)
String date ="July 5, 2012 1:28:19 PM";
date.indexOf ('J'); 0
date.indexOf ('2'); 8
date.indexOf ("2012"); 8
date.indexOf ('2', 9); 11
date.indexOf ("2020"); -1
date.lastIndexOf ('2'); 15
Returns:
(not found)
(starts searching
at position 9)
0 8 11 15
10-16
Methods — Comparisons
boolean b = s1.equals(s2);
returns true if the string s1 is equal to s2
boolean b = s1.equalsIgnoreCase(s2);
returns true if the string s1 matches s2, case-blind
int diff = s1.compareTo(s2);
returns the “difference” s1 - s2
int diff = s1.compareToIgnoreCase(s2);
returns the “difference” s1 - s2, case-blind
10-17
Methods — Replacements
String s2 = s1.trim ();
returns a new string formed from s1 by
removing white space at both ends
String s2 = s1.replace(oldCh, newCh);
returns a new string formed from s1 by
replacing all occurrences of oldCh with newCh
String s2 = s1.toUpperCase();
String s2 = s1.toLowerCase();
returns a new string formed from s1 by
converting its characters to upper (lower) case
10-18
Replacements (cont’d)
• Example: how to convert s1 to upper case
• A common bug:
s1 = s1.toUpperCase();
s1.toUpperCase();
s1 remains
unchanged
10-19
Numbers to Strings
• Three ways to convert a number into a
string:
1.
String s = "" + n;
2.
String s = Integer.toString (n);
String s = Double.toString (x);
3.
String s = String.valueOf (n);
Integer and Double
are “wrapper” classes
from java.lang that
represent numbers as
objects. They also
provide useful static
methods.
10-20
Numbers to Strings (cont’d)
• The DecimalFormat class can be used for
formatting numbers into strings.
import java.text.DecimalFormat;
...
DecimalFormat money =
new DecimalFormat("0.00");
...
double amt = 56.7381;
...
String s = money.format (amt);
56.7381
"56.74"
10-21
Numbers to Strings (cont’d)
• Java 5.0 added printf and format methods:
int m = 5, d = 19, y = 2007;
double amt = 123.5;
System.out.printf (
"Date: %02d/%02d/%d Amount = %7.2fn", m, d, y, amt);
String s = String. format(
"Date: %02d/%02d/%d Amount = %7.2fn", m, d, y, amt);
Displays,
sets s to:
"Date: 05/19/2007 Amount 123.50"
10-22
Numbers from Strings
• These methods throw a
NumberFormatException if s does not
represent a valid number (integer, real
number, respectively).
String s1 = "-123", s2 = "123.45";
int n = Integer.parseInt(s1);
double x = Double.parseDouble(s2);
10-23
Numbers from Strings (cont’d)
• A safer way:
int n;
do {
try
{
n = Integer.parseInt(s);
}
catch (NumberFormatException ex)
{
System.out.println("Invalid input, reenter");
}
} while (...);
10-24
Character Methods
• java.lang.Character is a “wrapper” class that
represents characters as objects.
• Character has several useful static methods
that determine the type of a character (letter,
digit, etc.).
• Character also has methods that convert a
letter to the upper or lower case.
10-25
Character Methods (cont’d)
if (Character.isDigit (ch)) ...
.isLetter...
.isLetterOrDigit...
.isUpperCase...
.isLowerCase...
.isWhitespace...
return true if ch belongs to the corresponding
category
Whitespace is
space, tab,
newline, etc.
10-26
Character methods (cont’d)
char ch2 = Character.toUpperCase (ch1);
.toLowerCase (ch1);
if ch1 is a letter, returns its upper (lower) case;
otherwise returns ch1
int d = Character.digit (ch, radix);
returns the int value of the digit ch in the given
int radix
char ch = Character.forDigit (d, radix);
returns a char that represents int d in a given
int radix
10-27
The StringBuffer Class
• Represents a string of characters as a
mutable object
• Constructors:
StringBuffer() // empty StringBuffer of the default capacity
StringBuffer(n) // empty StringBuffer of a given capacity
StringBuffer(str) // converts str into a StringBuffer
• Adds setCharAt, insert, append, and delete
methods
• The toString method converts this
StringBuffer into a String
10-28
Review:
• What makes the String class unusual?
• How can you include a double quote
character into a literal string?
• Is "length".length() allowed syntax? If so,
what is the returned value?
• Define immutable objects.
• Does immutability of Strings make Java more
efficient or less efficient?
10-29
Review (cont’d):
• How do you declare an empty string?
• Why are String constructors not used very
often?
• If the value of String city is "Boston", what is
returned by city.charAt (2)? By
city.substring(2, 4)?
• How come String doesn’t have a setCharAt
method?
• Is s1 += s2 the same as s1 = s1 + s2 for
strings?
10-30
Review (cont’d):
• What do the indexOf methods do? Name a
few overloaded versions.
• What is more efficient for strings: == and
other relational operators or equals and
compareTo methods?
• What does the trim method do?
• What does s.toUpperCase() do to s?
• What does the toString method return for a
String object?
10-31
Review (cont’d):
• Name a simple way to convert a number into
a string.
• Which class has a method for converting a
String into an int?
• Name a few Character methods that help
identify the category to which a given
character belongs.
• What is the difference between the String and
StringBuffer classes?

More Related Content

Similar to String Method.pptx

DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NETRasan Samarasinghe
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#Rasan Samarasinghe
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdfssusere19c741
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objectsHarkamal Singh
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsJamesChristianGadian
 
Character Arrays and strings in c language
Character Arrays and strings in c languageCharacter Arrays and strings in c language
Character Arrays and strings in c languagemallikavin
 
Class XII Computer Science Study Material
Class XII Computer Science Study MaterialClass XII Computer Science Study Material
Class XII Computer Science Study MaterialFellowBuddy.com
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulationShahjahan Samoon
 
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...AntareepMajumder
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++NUST Stuff
 
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
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation xShahjahan Samoon
 

Similar to String Method.pptx (20)

DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
 
Computer programming 2 Lesson 10
Computer programming 2  Lesson 10Computer programming 2  Lesson 10
Computer programming 2 Lesson 10
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf
 
PPS_Unit 4.ppt
PPS_Unit 4.pptPPS_Unit 4.ppt
PPS_Unit 4.ppt
 
Python
PythonPython
Python
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objects
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming Lessons
 
Character Arrays and strings in c language
Character Arrays and strings in c languageCharacter Arrays and strings in c language
Character Arrays and strings in c language
 
Class XII Computer Science Study Material
Class XII Computer Science Study MaterialClass XII Computer Science Study Material
Class XII Computer Science Study Material
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
 
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
 
Ocs752 unit 3
Ocs752   unit 3Ocs752   unit 3
Ocs752 unit 3
 
Java Strings
Java StringsJava Strings
Java Strings
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
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
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
 
C# overview part 1
C# overview part 1C# overview part 1
C# overview part 1
 

Recently uploaded

BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 

Recently uploaded (20)

Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

String Method.pptx

  • 1. Strings "Chapter 10" Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Java Methods Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin 2nd AP edition  with GridWorld
  • 2. 10-2 Objectives: • Learn about literal strings • Learn about String constructors and commonly used methods • Understand immutability of strings • Learn to format numbers into strings and extract numbers from strings • Learn several useful methods of the Character class • Learn about the StringBuffer class
  • 3. 10-3 The String class • An object of the String class represents a string of characters. • The String class belongs to the java.lang package, which is built into Java. • Like other classes, String has constructors and methods. • Unlike other classes, String has two operators, + and += (used for concatenation).
  • 4. 10-4 Literal Strings • Literal strings are anonymous constant objects of the String class that are defined as text in double quotes. • Literal strings don’t have to be constructed: they are “just there.”
  • 5. 10-5 Literal Strings (cont’d) • can be assigned to String variables. • can be passed to methods and constructors as parameters. • have methods you can call: String fileName = "fish.dat"; button = new JButton("Next slide"); if ("Start".equals(cmd)) ...
  • 6. 10-6 Literal Strings (cont’d) • The string text may include “escape” characters (described in Section 6.5). For example:  stands for  n stands for newline String s1 = "Biology”; String s2 = "C:jdk1.4docs"; String s3 = "Hellon";
  • 7. 10-7 Immutability • Once created, a string cannot be changed: none of its methods can change the string. • Such objects are called immutable. • Immutable objects are convenient because several references can point to the same object safely: there is no danger of changing an object through one reference without the others being aware of the change.
  • 8. 10-8 Immutability (cont’d) • Advantage: more efficient, no need to copy. String s1 = "Sun"; String s2 = s1; String s1 = "Sun"; String s2 = new String(s1); s1 s2 s1 s2 OK Less efficient: wastes memory "Sun" "Sun" "Sun"
  • 9. 10-9 Immutability (cont’d) • Disadvantage: less efficient — you need to create a new string and throw away the old one for every small change. String s = "sun"; char ch = Character.toUpperCase(s.charAt (0)); s = ch + s.substring (1); s "sun" "Sun"
  • 10. 10-10 Empty Strings • An empty string has no characters; its length is 0. • Not to be confused with an uninitialized string: String s1 = ""; String s2 = new String(); private String errorMsg; errorMsg is null Empty strings
  • 11. 10-11 Constructors • String’s no-args and copy constructors are not used much. • Other constructors convert arrays (Chapter 12) into strings String s1 = new String (); String s2 = new String (s1); String s1 = ""; String s2 = s1;
  • 12. 10-12 Methods — length, charAt int length (); char charAt (k); • Returns the number of characters in the string • Returns the k-th char 6 'n' ”Flower".length(); ”Wind".charAt (2); Returns: Character positions in strings are numbered starting from 0
  • 13. 10-13 Methods — substring String s2 = s.substring (i, j); returns the substring of chars in positions from i to j-1 String s2 = s.substring (i); returns the substring from the i-th char to the end "raw" "happy" "" (empty string) ”strawberry".substring (2,5); "unhappy".substring (2); "emptiness".substring (9); Returns: strawberry i j strawberry i
  • 14. 10-14 Methods — Concatenation String result = s1 + s2; concatenates s1 and s2 String result = s1.concat (s2); the same as s1 + s2 result += s3; concatenates s3 to result result += num; converts num to String and concatenates it to result
  • 15. 10-15 Methods — Find (indexOf) String date ="July 5, 2012 1:28:19 PM"; date.indexOf ('J'); 0 date.indexOf ('2'); 8 date.indexOf ("2012"); 8 date.indexOf ('2', 9); 11 date.indexOf ("2020"); -1 date.lastIndexOf ('2'); 15 Returns: (not found) (starts searching at position 9) 0 8 11 15
  • 16. 10-16 Methods — Comparisons boolean b = s1.equals(s2); returns true if the string s1 is equal to s2 boolean b = s1.equalsIgnoreCase(s2); returns true if the string s1 matches s2, case-blind int diff = s1.compareTo(s2); returns the “difference” s1 - s2 int diff = s1.compareToIgnoreCase(s2); returns the “difference” s1 - s2, case-blind
  • 17. 10-17 Methods — Replacements String s2 = s1.trim (); returns a new string formed from s1 by removing white space at both ends String s2 = s1.replace(oldCh, newCh); returns a new string formed from s1 by replacing all occurrences of oldCh with newCh String s2 = s1.toUpperCase(); String s2 = s1.toLowerCase(); returns a new string formed from s1 by converting its characters to upper (lower) case
  • 18. 10-18 Replacements (cont’d) • Example: how to convert s1 to upper case • A common bug: s1 = s1.toUpperCase(); s1.toUpperCase(); s1 remains unchanged
  • 19. 10-19 Numbers to Strings • Three ways to convert a number into a string: 1. String s = "" + n; 2. String s = Integer.toString (n); String s = Double.toString (x); 3. String s = String.valueOf (n); Integer and Double are “wrapper” classes from java.lang that represent numbers as objects. They also provide useful static methods.
  • 20. 10-20 Numbers to Strings (cont’d) • The DecimalFormat class can be used for formatting numbers into strings. import java.text.DecimalFormat; ... DecimalFormat money = new DecimalFormat("0.00"); ... double amt = 56.7381; ... String s = money.format (amt); 56.7381 "56.74"
  • 21. 10-21 Numbers to Strings (cont’d) • Java 5.0 added printf and format methods: int m = 5, d = 19, y = 2007; double amt = 123.5; System.out.printf ( "Date: %02d/%02d/%d Amount = %7.2fn", m, d, y, amt); String s = String. format( "Date: %02d/%02d/%d Amount = %7.2fn", m, d, y, amt); Displays, sets s to: "Date: 05/19/2007 Amount 123.50"
  • 22. 10-22 Numbers from Strings • These methods throw a NumberFormatException if s does not represent a valid number (integer, real number, respectively). String s1 = "-123", s2 = "123.45"; int n = Integer.parseInt(s1); double x = Double.parseDouble(s2);
  • 23. 10-23 Numbers from Strings (cont’d) • A safer way: int n; do { try { n = Integer.parseInt(s); } catch (NumberFormatException ex) { System.out.println("Invalid input, reenter"); } } while (...);
  • 24. 10-24 Character Methods • java.lang.Character is a “wrapper” class that represents characters as objects. • Character has several useful static methods that determine the type of a character (letter, digit, etc.). • Character also has methods that convert a letter to the upper or lower case.
  • 25. 10-25 Character Methods (cont’d) if (Character.isDigit (ch)) ... .isLetter... .isLetterOrDigit... .isUpperCase... .isLowerCase... .isWhitespace... return true if ch belongs to the corresponding category Whitespace is space, tab, newline, etc.
  • 26. 10-26 Character methods (cont’d) char ch2 = Character.toUpperCase (ch1); .toLowerCase (ch1); if ch1 is a letter, returns its upper (lower) case; otherwise returns ch1 int d = Character.digit (ch, radix); returns the int value of the digit ch in the given int radix char ch = Character.forDigit (d, radix); returns a char that represents int d in a given int radix
  • 27. 10-27 The StringBuffer Class • Represents a string of characters as a mutable object • Constructors: StringBuffer() // empty StringBuffer of the default capacity StringBuffer(n) // empty StringBuffer of a given capacity StringBuffer(str) // converts str into a StringBuffer • Adds setCharAt, insert, append, and delete methods • The toString method converts this StringBuffer into a String
  • 28. 10-28 Review: • What makes the String class unusual? • How can you include a double quote character into a literal string? • Is "length".length() allowed syntax? If so, what is the returned value? • Define immutable objects. • Does immutability of Strings make Java more efficient or less efficient?
  • 29. 10-29 Review (cont’d): • How do you declare an empty string? • Why are String constructors not used very often? • If the value of String city is "Boston", what is returned by city.charAt (2)? By city.substring(2, 4)? • How come String doesn’t have a setCharAt method? • Is s1 += s2 the same as s1 = s1 + s2 for strings?
  • 30. 10-30 Review (cont’d): • What do the indexOf methods do? Name a few overloaded versions. • What is more efficient for strings: == and other relational operators or equals and compareTo methods? • What does the trim method do? • What does s.toUpperCase() do to s? • What does the toString method return for a String object?
  • 31. 10-31 Review (cont’d): • Name a simple way to convert a number into a string. • Which class has a method for converting a String into an int? • Name a few Character methods that help identify the category to which a given character belongs. • What is the difference between the String and StringBuffer classes?