Yet Another Predefined Class Strings - PowerPoint PPT Presentation

1 / 41
About This Presentation
Title:

Yet Another Predefined Class Strings

Description:

Java uses the double quotation mark to delimit strings. ... Screen shot of BlueJ running the StringEquality program. 37. Why Is It So? ... – PowerPoint PPT presentation

Number of Views:44
Avg rating:3.0/5.0
Slides: 42
Provided by: uwo6
Category:

less

Transcript and Presenter's Notes

Title: Yet Another Predefined Class Strings


1
Yet Another Predefined Class - Strings
2
Topics to Cover
  • Modeling Strings
  • Objects of type String
  • The Empty String
  • A String Example
  • String Methods
  • Method Prototypes
  • Variable Names and Objects
  • More String Methods
  • Conversions Numbers ? Strings
  • Strings and Equality

3
Modeling Strings
  • A string is any sequence of characters (letters,
    digits, punctuation marks, spaces, and so on)
  • Consider a string object
  • What attributes would it have?
  • Sequence of characters
  • What behaviours would it have?
  • Get length,

4
Modeling Strings
  • We have seen String constants as actual
    parameters to the methods print and println.
  • For exampleSystem.out.print("Welcome to
    Java")System.out.println(" and to CS026!)
  • Java uses the double quotation mark to delimit
    strings.
  • Remember the quotation marks are not part of the
    String
  • Java has a predefined class, String, which models
    a string of characters

5
Modeling Strings
  • Note the Java String class has subtle
    differences in usage from other predefined
    classes
  • Why? Because Strings are used so often, they are
    designed to save space
  • The differences will be pointed out as we go
    along watch for them!

6
Objects of Type String
  • Recall the steps we have seen so far to acquire
    an object
  • Declare a reference variable of the class type
    from which we want an object
  • Use the keyword new to create the object and to
    invoke the constructor
  • The String class is different!
  • We can have String constants (i.e. we can have a
    String object without having a reference
    variable)
  • Example"Welcome to Java" is a constant
    (literal) String object

System.out.println("Welcome to Java")
7
Objects of Type String
  • The keyword new is not typically required (and,
    usually, should not be used) to create a String
    object
  • The previous example demonstrated this with a
    String constant
  • Moreover, the keyword new is not required when we
    create a reference to a string with a reference
    variable, e.g
  • Remember because the variable welcomeMessage
    refers (points) to a String object, it is called
    a reference variable

String welcomeMessagewelcomeMessage "Welcome
to Java"System.out.println(welcomeMessage)
8
Objects of Type String
  • Discussion Points
  • Considering the previous example,what does a
    trace look like after each statement is executed?

9
Objects of Type String
  • The keyword new can be used to create String
    objects and invoke the String constructor
    however, the keyword new may cause more memory
    than is really necessary to be required (more on
    this in a moment )
  • The previous example could be written as
  • How do the two differences discussed make using
    String objects easier?
  • How do reference variables differ from simple
    variables?

String welcomeMessagewelcomeMessage
new String("Welcome to Java")System.out.printl
n(welcomeMessage)
10
The Empty String
  • The empty string
  • Sometimes we want to initialize a String variable
    to nothing, that is, to contain no characters
    at all
  • Examples
  • String message new String()
  • or
  • String message ""
  • When might one want to initialize a string to the
    empty string?

11
Example
String firstName, lastName, usualNamefirstName
"Donald"lastName "Duck"usualName
firstName
  • To what does the variable firstName refer?
  • To what does the variable lastName refer?
  • To what does the variable usualName refer?
  • Recall What happens when there is a variable
    name on the right hand side of the assignment
    operator?
  • Show what a trace would like after each statement

12
String Methods
  • What can we do with String objects? In other
    words, what behaviours do they have?
  • Where do we find information about predefined
    classes?

13
String Methods
  • Example toUpperCase is a predefined method of
    the String class
  • What kind of method is toUpperCase static or
    instance?
  • Are there any parameters required by the method
    toUpperCase?
  • What happens when the first println is executed?

String wordword "java"System.out.println(wor
d)System.out.println(word.toUpperCase())
14
String Methods
  • What happens when the method toUpperCase is
    executed?
  • It does not change the variable word itself
  • Instead, it creates a new String object with
    attributes "JAVA"
  • It then returns the new String object
  • What is printed on the screen?
  • What happens if the following statements are
    executed after the previous code segment?
  • All instance methods in the String class are
    accessor methods therefore, String objects are
    said to be immutable that is, unchangeable

word word.toUpperCase() String anotherWord
word.toUpperCase()
15
Reference Variables and Objects
  • A reference variable refers to exactly one
    object
  • An object can be referred to by many reference
    variables
  • Example
  • The variable names firstName and usualName both
    refer to the same String object (what is it?)
  • Show a trace after each statement

String firstName, usualNamefirstName
"Donald"usualName firstName
16
Reference Variables and Objects
  • What happens if we now make firstName refer to a
    different String object?
  • What happens to usualName?Nothing, it still
    refers to the same String object "Donald"
  • Perform a trace to clearly show the contents of
    the variables

firstName "Ronald"
17
More String Methods
  • We can manipulate String objects in many ways,
    using other predefined String methods e.g.
    method concat
  • Concatenation means joining together
  • What object is concatenated with lastName?
  • What is the return type of the method concat ?
  • What will be printed in the above example? (Be
    careful!)

String firstName, lastName, fullName firstName
"Donald"lastName "Duck"fullName
firstName.concat(lastName) System.out.println(ful
lName)
18
More String Methods
  • We have seen the term concatenation in class
    before.
  • Java has the concatenation operator which
    can be used instead (in fact, its easier to
    use!)
  • Rewrite the previous example using the
    concatenation operator
  • Draw diagrams of main memory (i.e. perform a
    trace)

19
More String Methods
  • Method substring
  • The character positions in a string are numbered
    from left to right, starting at 0
  • In the string "Donald", what character is at
    position 0?
  • At what position is the last character in the
    string?
  • Example 1

String shortNameshortName firstName.substring(
0,3)System.out.println(shortName)
20
More String Methods
  • substring is an overloaded method it has two
    versions, depending on the number and type of
    parameters!
  • The two-parameter version specifies position1 and
    position2
  • The substring will consist of all characters
    starting at position1, up to but not including
    the character at position2
  • What is the return type of the method substring?
  • What will be printed in Example 1?
  • Rewrite Example 1 as a single statement

21
More String Methods
  • Example 2
  • The one-parameter version specifies a starting
    position
  • The substring will consist of all characters
    starting at the given position, up to the end of
    the string
  • What is the operator in this context?
  • What will be printed in Example 2?
  • Rewrite example 2 as a single statement

String letter, newNameletter "R"newName
letter firstName.substring(1)System.out.printl
n(newName)
22
More String Methods
  • Recall String objects are immutable once they
    are created, they do not change
  • Therefore the String methods toUpperCase,
    concat, and substring return a new String object
  • They do not change the existing String object

23
More String Methods
  • Method length
  • length returns the number of characters in the
    string
  • What is the return type of length?
  • What would be output by this statement?

firstName "Bob" System.out.println(firstName.l
ength())
24
Conversions Numbers ?? Strings
  • int to String We have seen this before
  • How are the numbers 1983, 6, and 20 represented
    in main memory?
  • What parameter type is required by println?
  • Each integer value is converted to a String
    object with the use of the concatenation operator
    ()

int birthYear 1983int birthMonth 6int
birthDay 20 System.out.println(birthYear "-"
birthMonth "-" birthDay)
25
Conversions Numbers ?? Strings
  • Observe using the concatenation operator causes
    the conversion, for example
  • What is ""?
  • Recall it is the empty string
  • What are the differences between birthYear and
    birthYearString?

String birthYearString "" birthYear
26
Conversions Numbers ?? Strings
  • Now suppose we want to create a string called
    birthDate of the form 20-6-1983
  • Each number is converted to a String object
  • Then what?
  • Now suppose we want birthDate to be of the form
    20-6-83 (fill in the blank)String birthDate

String birthDate birthDay "-"
birthMonth "-" birthYear
27
Conversions Numbers ?? Strings
  • Conversion String to int
  • We have seen this before too!
  • Use the static method parseInt from the Integer
    class
  • Example (fill in the blank)int birthYear
    Integer.parseInt (birthDate.substring(
    ))

28
Conversions Numbers ?? Strings
  • Conversion String to double
  • Similar to String to int
  • Use the static method parseDouble from the Double
    class
  • Example (fill in the blank)String priceString
    "49.99"double price Double.parseDouble
    (priceString.substring( ))

29
Conversions Numbers ?? Strings
  • When might it be useful to convert from a String
    to a number?
  • Hint In what form is all input from the
    keyboard?

30
Strings and Equality
  • Recall identity vs. state equality
  • Recall strings are different! (e.g. they are
    immutable)
  • Consider StringEquality.java

/ StringEquality.java CS026 Lecture Notes
Example Task demonstrates that String
equality is different than equality of
other objects/ import
java.io.import java.awt.Rectangle
31
Strings and Equality
public class StringEquality public static
void main(String args) throws Exception
BufferedReader keyboard new BufferedReader
(new InputStreamReader(System.in),1)
/ dimensions for rectangle objects
/ final int WIDTH 5 final int
HEIGHT 10 / first, compare objects to
themselves / System.out.println("COMPARE
OBJECTS TO THEMSELVES ") String name1
"UWO" compare("Compare a string object to
itself", name1, name1) Rectangle shape1
new Rectangle(0, 0, WIDTH, HEIGHT)
compare("Compare a rectangle object to itself ",
shape1, shape1)
keyboard.readLine()
32
Strings and Equality
/ second, compare objects to other objects with
different states / System.out.println("COM
PARE DIFFERENT OBJECTS "
"WITH DIFFERENT STATES ") String
name2 "London" compare("Compare a
string to another string composed of different
characters ", name1, name2) Rectangle
shape2 new Rectangle(1, 1, WIDTH2, HEIGHT2)
compare("Compare a rectangle object with
another rectangle in a different position of a
different size ", shape1, shape2)
keyboard.readLine()
33
Strings and Equality
/ third, compare objects to other objects with
the same states / System.out.println("COMP
ARE DIFFERENT OBJECTS WITH "
"THE SAME STATES ") String name3
"UWO" compare("Compare a string to
another string " "composed of
the same characters ", name1,
name3) Rectangle shape3 new
Rectangle(0, 0, WIDTH, HEIGHT)
compare("Compare a rectangle to another rectangle
" "with the same
characteristics ", shape1,
shape3)
34
Strings and Equality
public static void compare( String message,
Rectangle r1, Rectangle r2)
System.out.println(message)   if (r1
r2) System.out.println(" identity
equality") else
System.out.println(" identity inequality")  
if (r1.equals(r2))
System.out.println(" state equality")
else System.out.println(" state
inequality")   System.out.println()
35
Strings and Equality
public static void compare( String message,
String s1, String s2) System.out.println(m
essage) if (s1 s2)
System.out.println(" identity equality")
else System.out.println(" identity
inequality")   if (s1.equals(s2))
System.out.println(" state equality")
else System.out.println(" state
inequality")   System.out.println()

36
Strings and Equality
Screen shot of BlueJ running the StringEquality
program
37
Why Is It So???
  • Because Java strings are said to be interned
  • Recall strings are immutable
  • Therefore, when multiple strings have the same
    state, it makes sense to have them refer to
    exactly the same object. For example
  • The two objects are equivalent with respect to
    both state and identity. That is

String name1 "UWO"String name2 "UWO"
38
Why Is It So???
if (name1 name2) System.out.println("identity
equivalence")if (name1.equals(name2)) System.ou
t.println("state equivalence")
  • will result in the output
  • This referred to as interning of the strings,
    which is done to avoid duplicates (therefore,
    saving memory and making equality checks faster)

identity equivalencestate equivalence
39
Why Is It So???
  • Observe if one has the following
  • then the objects are only equivalent with
    respect to state, that is,will result in the
    output

String name1 new String("UWO")String name2
new String("UWO")
if (name1 name2) System.out.println("identity
equivalence")if (name1.equals(name2)) System.ou
t.println("state equivalence")
state equivalence
40
Why Is It So???
  • In other words, to avoid the interning of
    strings, one can create strings with the keyword
    new
  • It might not be as efficient to do this however
  • Think of a situation where one would want to
    avoid the interning

41
Further Reading
  • The following sections from the Java 5.0 Program
    Design text supplement these notes nicely
  • Section 7.6 (omit Listings 7.7, 7.8, 7.9,  7.10
    and discussions thereof)
Write a Comment
User Comments (0)
About PowerShow.com