0% found this document useful (0 votes)
91 views43 pages

CH07 Characters, Strings and StringBuilder

This document provides an overview of strings and string manipulation in Java. It discusses common problems that can occur when manipulating strings, such as comparing strings with ==. It also covers the String, Character, and StringBuilder/StringBuffer classes and their methods. Key methods include equals(), compareTo(), length(), indexOf(), and substring(). The document explains how to convert between strings and numeric types like Integer and Double. Finally, it introduces the StringBuilder and StringBuffer classes as alternatives to String for mutable string operations.

Uploaded by

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

CH07 Characters, Strings and StringBuilder

This document provides an overview of strings and string manipulation in Java. It discusses common problems that can occur when manipulating strings, such as comparing strings with ==. It also covers the String, Character, and StringBuilder/StringBuffer classes and their methods. Key methods include equals(), compareTo(), length(), indexOf(), and substring(). The document explains how to convert between strings and numeric types like Integer and Double. Finally, it introduces the StringBuilder and StringBuffer classes as alternatives to String for mutable string operations.

Uploaded by

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

Java Programming

Fifth Edition

Chapter 7
Characters, Strings, and the StringBuilder
Objectives

• Identify problems that can occur when you manipulat


e string data
• Manipulate characters
• Declare a String object
• Compare String values
• Use other String methods

Java Programming, Fifth Edition 2


Objectives (continued)
• Convert Strings to numbers
• Learn about the StringBuilder and StringBuff
er classes

Java Programming, Fifth Edition 3


Identifying Problems That Can Occur
When You Manipulate String Data
• Manipulating characters and groups of characters
– Provides some challenges for beginning Java progra
mmer
• String is a class
– Each created String class object
– String variable name not simple data type
– Reference
• Variable that holds memory address

Java Programming, Fifth Edition 4


Identifying Problems That Can Occur
When You Manipulate String Data (c
ontinued)
• Compare two Strings using the == operator
– Not comparing values
– Comparing computer memory locations
• Compare contents of memory locations more frequ
ently than memory locations themselves

Java Programming, Fifth Edition 5


Identifying Problems That Can Occur
When You Manipulate String Data (c
ontinued)

Java Programming, Fifth Edition 6


Identifying Problems That Can Occur
When You Manipulate String Data (c
ontinued)
• Classes to use when working with character data
– Character
• Instances hold single character value
• Defines methods that can manipulate or inspect single
-character data
– String
• Class for working with fixed-string data
– Unchanging data composed of multiple characters

Java Programming, Fifth Edition 7


Identifying Problems That Can Occur
When You Manipulate String Data (c
ontinued)
• Classes to use when working with character data (c
ontinued)
– StringBuilder and StringBuffer
• Class for storing and manipulating changeable data co
mposed of multiple characters

Java Programming, Fifth Edition 8


Manipulating Characters
• Character class
– Contains standard methods for testing values of char
acters
– Methods that begin with “is”
• Such as isUpperCase()
• Return Boolean value
• Can be used in comparison statements
– Methods that begin with “to”
• Such as toUpperCase()
• Return character that has been converted to stated for
mat
Java Programming, Fifth Edition 9
Manipulating Characters (continued)

Java Programming, Fifth Edition 10


Java Programming, Fifth Edition 11
Declaring a String Object

• Literal string
– Sequence of characters enclosed within double quot
ation marks
– Unnamed object, or anonymous object of String cl
ass
• String variable
– Named object of String class
• Class String
– Defined in java.lang.String
– Automatically imported into every program

Java Programming, Fifth Edition 12


Declaring a String Object (continued
)
• Declare String variable
– String itself is distinct from variable used to refer to
it
• Create String object
String aGreeting = new String("Hello");
String aGreeting = "Hello";
– Can create String object without:
• Using keyword new
• Explicitly calling class constructor

Java Programming, Fifth Edition 13


Comparing String Values

• String is a class
– Each created String is a class object
• String variable name
– Reference variable
– Refers to location in memory
• Rather than to particular value
• Assign new value to String
– Address held by String altered

Java Programming, Fifth Edition 14


Comparing String Values (continued
)

Java Programming, Fifth Edition 15


Comparing String Values (continued
)
• Immutable
– Objects that cannot be changed
– Such as String
• Making simple comparisons between Strings
– Often produces misleading results
– Compare Strings with == operator
• Compare memory addresses
• Not values

Java Programming, Fifth Edition 16


Comparing String Values (continued
)
• equals() method
– Evaluates contents of two String objects to determi
ne if they are equivalent
– Returns true if objects have identical contents
– public boolean equals(String s)
• equalsIgnoreCase() method
– Ignores case when determining if two Strings equi
valent
– Useful when users type responses to prompts in pro
grams

Java Programming, Fifth Edition 17


Comparing String Values (continued
)

Java Programming, Fifth Edition 18


Comparing String Values (continued
)
• compareTo() method
– Compares two Strings and returns:
• Zero
– Only if two Strings refer to same value
• Negative number
– If calling object “less than” argument
• Positive number
– If calling object “more than” argument
if (aWord.compareTo(anotherWord) < 0)

Java Programming, Fifth Edition 19


Using Other String Methods

• toUpperCase() and toLowerCase()


– Convert any String to uppercase or lowercase equi
valent
• length() method
– Returns length of String

Java Programming, Fifth Edition 20


Using Other String Methods (continu
ed)
• indexOf() method
– Determines whether specific character occurs within
String
– Returns position of character
– First position of String begins with zero
– Return value is –1
• If character does not exist in String

Java Programming, Fifth Edition 21


Using Other String Methods (continu
ed)
• charAt() method
– Requires integer argument
– Indicates position of character that method returns
• endsWith() method and startsWith() method
– Take String argument
– Return true or false if String object does or doe
s not end or start with specified argument

Java Programming, Fifth Edition 22


Using Other String Methods (continu
ed)
• replace() method
– Replace all occurrences of some character within St
ring
• toString() method
– Not part of String class
– Converts any object to String
– Converts primitive data types to Strings
String theString;
int someInt = 4;
theString = Integer.toString(someInt);

Java Programming, Fifth Edition 23


Using Other String Methods (continu
ed)
• Concatenation
– Join simple variable to String
String aString = "My age is " + myAge;
– Plus sign (+)

Java Programming, Fifth Edition 24


Using Other String Methods (continu
ed)
• substring() method
– Extract part of String
– Takes two integer arguments
• Start position
• End position
– Length of extracted substring
• Difference between second integer and first integer

Java Programming, Fifth Edition 25


Java Programming, Fifth Edition 26
Converting Strings to Numbers

• Integer class
– Part of java.lang
– Automatically imported into programs
– Convert String to integer
– parseInt() method
• Takes String argument
• Returns its integer value
• Wrapper
– Class or object “wrapped around” simpler element

Java Programming, Fifth Edition 27


Converting Strings to Numbers (cont
inued)
• Integer class valueOf() method
– Convert String to Integer class object
• Integer class intValue() method
– Extract simple integer from wrapper class
• Double class
– Wrapper class
– Imported into programs automatically
– parseDouble() method
• Takes String argument
• Returns its double value
Java Programming, Fifth Edition 28
Converting Strings to Numbers (cont
inued)

Java Programming, Fifth Edition 29


Learning About the StringBuilder
and StringBuffer Classes

• Value of String fixed


– After String created is immutable
• StringBuilder, StringBuffer classes
– Alternative to String class
– When String will be modified
– Can use anywhere you would use String
– Part of java.lang package
– Automatically imported into every program

Java Programming, Fifth Edition 30


Learning About the StringBuilder
and StringBuffer Classes (continu
ed)
• StringBuilder
– More efficient
• StringBuffer
– Thread safe
– Use in multithreaded programs

Java Programming, Fifth Edition 31


Learning About the StringBuilder
and StringBuffer Classes (continu
ed)
• Create StringBuilder object
StringBuilder eventString = new Stri
ngBuilder ("Hello there");
– Must use:
• Keyword new
• Constructor name
• Initializing value between constructor’s parentheses

Java Programming, Fifth Edition 32


Learning About the StringBuilder
and StringBuffer Classes (continu
ed)
• Buffer
– Memory block
– Might or might not contain String
– String might not occupy entire buffer
• Length of String can be different from length of buffe
r
– Capacity
• Actual length of buffer

Java Programming, Fifth Edition 33


Learning About the StringBuilder
and StringBuffer Classes (continu
ed)
• setLength() method
– Change length of String in StringBuilder objec
t
• length property
– Attribute of StringBuilder class
– Identifies number of characters in String contained
in StringBuilder
• capacity() method
– Find capacity of StringBuilder object

Java Programming, Fifth Edition 34


Java Programming, Fifth Edition 35
Learning About the StringBuilder
and StringBuffer Classes (continu
ed)
• Using StringBuilder objects
– Provides improved computer performance over Str
ing objects
– Can insert or append new contents into StringBui
lder
• StringBuilder constructors
public StringBuilder ()
public StringBuilder (int capacity)
public StringBuilder (String s)

Java Programming, Fifth Edition 36


Learning About the StringBuilder
and StringBuffer Classes (continu
ed)
• append() method
– Adds characters to end of StringBuilder object
• insert() method
– Adds characters at specific location within StringB
uilder object
• setCharAt() method
– Changes character at specified position within Stri
ngBuilder object

Java Programming, Fifth Edition 37


Learning About the StringBuilder
and StringBuffer Classes (continu
ed)
• charAt() method
– Accepts argument that is offset of character position
from beginning of String
– Returns character at that position

Java Programming, Fifth Edition 38


Java Programming, Fifth Edition 39
You Do It
• Using String class methods
• Converting a String to an integer
• Using StringBuilder methods

Java Programming, Fifth Edition 40


Don’t Do It
• Don’t attempt to compare Strings using the stand
ard comparison operators
• Don’t forget to use the new operator and the constr
uctor when declaring initialized StringBuilder o
bjects

Java Programming, Fifth Edition 41


Summary
• String variables
– References
• Character class
– Instances can hold single character value
• Each String class object
– Immutable
– equals() method
• toString() method
– Converts any object to String

Java Programming, Fifth Edition 42


Summary (continued)
• Integer.parseInt() method
– Takes String argument
– Returns integer value
• Double.parseDouble() method
– Takes String argument
– Returns double value
• StringBuilder class
– Improves performance when string’s contents must c
hange

Java Programming, Fifth Edition 43

You might also like