Strings and Object References in Java

Site: Saylor Academy
Course: CS101: Introduction to Computer Science I
Book: Strings and Object References in Java
Printed by: Guest user
Date: Friday, 25 April 2025, 5:31 AM

Description

The String class is used for text manipulation. As you read, you will learn different ways to create Strings, methods to manipulate Strings, the String concatenation operator '+', and about how Strings are immutable.

1. Strings and Object References

In previous chapters, methods were called with parameters that were primitive data types. This chapter discusses how to use object references as parameters. The class String is used in many examples.

Students taking the computer science Advanced Placement examination are expected to be familiar with the String class.

Chapter Topics:

      • String literals
      • The null value
      • More about garbage
      • The String class
      • String concatenation
      • Strings are immutable
      • Cascading methods
      • Some String methods
        • concat()
        • length()
        • trim()
        • substring()
        • toLowerCase()
        • startsWith()
        • charAt()

Question 1:

(Review:) What TWO things does the following statement do?

    String zeta = new String( "The last rose of summer" );

Source: Bradley Kjell, http://programmedlessons.org/Java9/chap44/ch44_01.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial 3.0 License.

2. Easy way to Construct Strings


Answer:

  1. A new String object is created, containing the characters between quote marks.
  2. A reference to the object is saved in the variable zeta.

Easy way to Construct Strings

String objects are very useful and are frequently used. To make life easier for programmers Java has a short-cut way of creating a String object:

String zeta = "The last rose of summer" ;

This creates a String object containing the characters between quote marks. A String created in this short-cut way is called a String literal.

Remember that if several statements in a program ask for literals containing the same characters only one object will actually be constructed (see chapter 41). Other classes do not have short-cuts like this. Objects of most classes are constructed by using the new operator.


Question 2:

Can a String reference be a parameter for a method?

3. String References as Parameters


Answer:

Yes, a String reference is often a parameter.

String References as Parameters

String stringA = "Random Jottings";
String stringB = "Lyrical Ballads"; if ( stringA.equals( stringB ) )
System.out.println("They are equal.");
else
System.out.println("They are different.");


Some methods require a parameter that is a reference to a String object. The example program shows this.

The picture that shows how the method call works. (Both objects have many methods, but only the equals() method of one object is pictured.)

The String object referred to by stringA has an equals() method. That method is called with a parameter, a reference to another String object, stringB. The method checks if both String objects contain identical sequences of characters, and if so, evaluates to true.

Careful:   The previous paragraph is correctly stated, but awkward. People often say "String" when they really mean "reference to a String". This is fine, but remember that a reference variable like stringA does not contain an object, but only a reference to an object. This may seem picky, but there is nothing quite as picky as a computer. Students who are not careful about this often run into problems.

equalsMethodCall


Annotation 2020-02-24 152747


Question 3:

(Review:) Examine the following snippet of code.
Answer the questions using careful words (like the above on the right).

String a;
Point  b;       
      • What is the data type of the variable a?
      • What is the data type of the variable b?
      • How many objects are there (so far)?

4. The null Value


Answer:

  • What is the data type of the variable a?
    • a is a reference to a String object.
  • What is the data type of the variable b?
    • b is a reference to a Point object.
  • How many objects are there (so far)?
    • So far, there are no objects, just variables that can reference objects, once there are some.

The null Value

A reference variable holds information about the location of an object. It does not hold the object itself. This code

String a;
Point b;

declares two reference variables but does not construct any objects. The following constructs objects and puts references in the variables:

a = "Elaine the fair" ;
b = new Point( 23, 491 );

null is a special value that means "no object." Set a reference variable to null when it is not referring to any object. Variables are often set to null when they are declared:

String a = null;
Point b = null;

Question 3:

(Thought Question:) Do you think that null can be assigned to reference variables of any type?
Click here for a 
.

5. Null Assigned to any Reference Variable


Answer:

Yes

Null Assigned to any Reference Variable

It would be awful if each class had its own special value to show that no object of that class was present. We need a universal value that means "nothing here". The value null works for this and can be assigned to any reference variable.

In most programs, objects come and objects go, depending on the data and on what is being computed. (Think of a computer game, where monsters show up, and monsters get killed).

A reference variable sometimes does and sometimes does not refer to an object, and can refer to different objects at different times. You need a way to say that a variable does not now refer to an object. You do this by assigning null to the variable.

Inspect the code below. Variables a and c are initialized to object references. Variable b is initialized to null.

class NullDemo1
{
  public static void main (String[] arg)
  {
    String a = "Random Jottings";
    String b = null;
    String c = "";

    if ( a != null ) 
      System.out.println( a );

    if ( b != null ) 
      System.out.println( b );

    if ( c != null ) 
      System.out.println( c );
  }
}   

Question 5:

What exactly is variable c initialized to? Click here for a .

6. The Empty String


Answer:

The code "" calls for a literal, which is a
String object. Although the object exists, it
contains no characters (since there are no
characters inside "").emptyString

The reference variable c is initialized to a
reference to this String object. This is most
certainly a different value than null.

The Empty String


class NullDemo1
{
  public static void main (String[] arg)
  {
    String a = "Random Jottings";   // 1.  an object is created; 
                                    //     variable a refers to it
    String b = null;                // 2.  variable b refers to no object.
    String c = "";                  // 3.  an object is created 
                                    //     (containing no characters); 
                                    //     variable c refers to it

    if ( a != null )                // 4.  ( a != null ) is true, so
       System.out.println( a );     // 5.  println( a ) executes.
                                              
    if ( b != null )                // 6.  ( b != null ) is false, so
       System.out.println( b );     // 7.  println( b ) is skipped.

    if ( c != null )                // 8.  ( c != null ) is true, so
       System.out.println( c );     // 9.  println( c ) executes.
                                    //     (but it has no characters to print.) 
  }
}    


String object that contains no characters is still an object. Such an object is called an empty string. It is similar to having a blank sheet of paper (different from having no paper at all). Overlooking this difference is one of the classic confusions of computer programming. It will happen to you. It happens to me. To prepare for future confusion, study the program, step-by-step.

The System.out.println() method expects a reference to a String object as a parameter. The example program tests that each variable contains a String reference before calling println() with it. (If println() gets a null parameter, it prints out "null" which would be OK. But some methods crash if they get a null parameter. Usually you should ensure that methods get the data they expect.)


Question 6:

Examine the following code snippet:

    String alpha = new String("Red Rose") ; alpha = null; . . .
    1. Where is an object constructed?
    2. What becomes of that object?

7. Garbage


Answer:

    String alpha = new String("Red Rose") ; alpha = null; . . .
  1. Where is an object constructed?
    • In the first statement.
  2. What becomes of that object?
    • It became garbage in the second statement.

Garbage

makingGarbage

The first statement does two things: (1) a String object is created, containing the characters "Red Rose". Then, (2) a reference to that object is saved in the reference variable alpha.

The second statement assigns the value null to alpha. When this happens, the reference to the object is lost. Since there is no reference to the object elsewhere, it is now garbage.

The line through the box in the second statement symbolizes the null value. The object still exists in memory. The memory it consists of will eventually be recycled by the garbage collector and will be made available for new objects.


Question 7:

Examine the following code snippet:

    String alpha = new String("Red Rose") ; alpha = null; . . .

  1. Where is an object created?
  2. What happens in the second statement?
  3. What becomes of that object?

8. Not Garbage


Answer:

String alpha =  new String("Red Rose");
String beta = alpha;
alpha = null;
  1. When was an object instantiated?       In the first statement.
  2. What happens in the second statement?       The reference to the object is copied to beta.
  3. What becomes of that object?       It remains "alive," because there is still a reference to it.

Not Garbage

notGarbage

This time, the object does not become garbage. This is because in the second statement a reference to the object is saved in a second variable, beta. Now when, in the third statement, alpha is set to null, there is still a reference to the object.

There can be many copies of the reference to an object. Only when there is no reference to an object anywhere does the object become garbage.


Question 8:

(Review:) How can you determine what an object of a particular class can do?

9. Class String


Answer:

The variables and methods of a class will be documented somewhere.

Class String

Use Google or another search engine to find documentation for class String. Search for Java String.

Here is a short version of the documentation for String.


 // Constructors
    public String(); 
    public String(String  value); 

    // Methods
    public char charAt(int  index);
    public String concat(String  str); 
    public boolean endsWith(String  suffix); 
    public boolean equals(Object  anObject); 
    public boolean equalsIgnoreCase(String  anotherString); 
    public int indexOf(int  ch); 
    public int indexOf(String  str); 
                       
    public int length(); 
    public boolean startsWith(String  prefix); 
    public String substring(int  beginIndex ); 
    public String substring(int  beginIndex, int endIndex); 
    public String toLowerCase(); 
    public String toUpperCase(); 
    public String trim();              
The documentation first lists constructors. Then it describes the methods. For example,

public String concat(String  str); 
--+--- --+---  --+--  ----+----
  |      |       |        |
  |      |       |        |
  |      |       |        +---- says that the method requires a
  |      |       |              String reference parameter
  |      |       |
  |      |       +----- the name of the method
  |      |
  |      +----- the method returns a reference 
  |             to a new String object
  |
  +----- anywhere you have a String object, 
         you can use this method

public will be explained in greater detail in another chapter.



Question 9:

Is the following code correct?

    String first = "Red " ; String last = "Rose" ; String name = first.concat( last );

You don't have to know what concat() does (yet); look at the documentation and see
if all the types are correct.

10. The concat() Method


Answer:

Yes.

The parts of the statement match the documentation correctly:

String name = first.concat( last ); 
 ----+----    --+-- --+--  --+--
     |          |     |      |
     |          |     |      |
     |          |     |      +---- a String reference parameter
     |          |     |
     |          |     +----- the name of the method
     |          |
     |          +----- dot notation used to call an object's method.
     |
     +----- the method returns a reference to a new String object

The concat() Method

concatMethodCall

The concat method performs String concatenation. A new String is constructed using the data from two other Strings. In the example, the first two Strings (referenced by first and last) supply the data that concat() uses to construct a third String (referenced by name.)

String first = "Red " ;
String last = "Rose" ;
String name = first.concat( last );

The first two Strings are NOT changed by the action of concat(). A new String is constructed that contains the characters "Red Rose".

The picture shows the operation of the concat() method before the reference to the new object has been assigned to name.


Question 10:

(Review:) Have you seen String concatenation before?

11. + Operator


Answer:

Yes: in output statements like this:

System.out.println( "Result is:" + result );

The + operator is a short way of asking for concatenation. (If result is a number,
it is first converted into characters before the concatenation is done.)

+ Operator

stringConcat

Here the + operator is used instead of using the concat() method:

String first = "Red " ;
String last = "Rose" ;
String name = first + last ;

String concatenation, done by concat() or by +, always constructs a new object based on data in other objects. Those objects are not altered at all.

When the operands on either side of + are numbers, then + means "addition". If one or both of the operands is a String reference, then String concatenation is performed. When an operator such as + changes meaning depending on its arguments, it is said to be overloaded.


Question 11:

Say that the following statement is added after the others:

    String reversed = last + first;
Does it change firstlast, or name?

12. Strings are Forever


Answer:

No. It uses the data in last and in first to construct a new object. No objects are altered.

Strings are Forever

Java was designed after programmers had about 15 years of experience with object oriented programming. One of the lessons learned in those years is that it is safer to construct a new object rather than to modify an old one. (This is because many places in the program might refer to the old object, and it is hard to be sure that they will all work correctly when the object is changed.)

Objects of some Java classes cannot be altered after construction. The class String is one of these.

Sometimes immutable objects are called write-once objects. Once a String object has been constructed, the characters it contains will always be the same. None of its methods will change those characters, and there is no other way to change them. The characters can be used for various purposes (such as in constructing new String objects), and can be inspected. But never altered.

string objects

bug Confusion Alert!! This is a place where it is important to distinguish between reference variables and their objects. A reference variable referring to a String can be altered (it can be made to point to a different String object.) The String object it refers to cannot be altered.


Question 12:

Inspect the following code:

    String ring = "One ring to rule them all, " String find = "One ring to find them." ring = ring + find;

Does the last statement violate the rule that Strings are immutable?

13. The Length of a String


Answer:

No. The String objects don't change. The reference variable ring is changed in the third
statement to refer to a different String than originally. (Its original String becomes garbage,
which is collected by the garbage collector.)

The Length of a String

The length of a string is the number of characters it contains, including space characters and punctuation.

An empty string has length zero. The length() method of a String returns its length:

public int length(); 

The method takes no parameters, but the () is needed when it is used.

String
length
"element"
7
"x"
1
""
0
"Look Homeward"
13
" Look Out "
13


Question 13:

Inspect the following code:

    String stringA = "Alphabet " ; String stringB = "Soup" ; String stringC = stringA + stringB; System.out.println( stringC.length() ) ;

What does the code print?

14. The trim() Method


Answer:

13

Don't forget to count the space.

The trim() Method

Here is a line of the documentation for the String class.

public String trim();

The trim() method of a String object creates a new String that is the same as the original except that any leading or trailing space is trimmed off (removed).


Question 14:

Examine the following code:

    String userData = " 745 "; String fixed; fixed = userData.trim();

Has the trim() method been used correctly? How many objects have been created?

15. trim() with Input data


Answer:

  • Has the trim() method been used correctly?     Yes
  • How many objects have been created?     2 --- the first literal and the new String created by trim()

trim() with Input data

The trim() method creates a new String. The new String contains the same characters as the old one but has whitespace characters (blanks, tabs, and several other non-printing characters) removed from both ends (but not from the middle). So, for example, after the last statement

String userData = "     745   ";
String fixed;

fixed = userData.trim();

the new String referenced by fixed will contain the characters "745" without any surrounding spaces.

(Usage Note:) This method is often useful. Extraneous spaces on either end of user input is a common problem.


Question 15:

Inspect the following:

    String dryden = " None but the brave deserves the fair. " ; System.out.println( "|" + dryden.trim() + "|" );

What is printed out?

16. charAt()


Answer:

|None but the brave deserves the fair.|

charAt()

The charAt(int index) method returns a single character at the specified index. If the index is negative, or greater than length()-1, an IndexOutOfBoundsException is thrown (and for now your program stops running).

The value returned by charAt(int index) is a char, not a String containing a single character. A char is a primitive data type, consisting of two bytes that encode a single character.

Expression Result
String source = "Subscription"; "Subscription"
source.charAt(0) 'S'
source.charAt(1) 'u'
source.charAt(5) 'r'
source.charAt(source.length()-1) 'n'
source.charAt(12) IndexOutOfBoundsException


Question 16:

What is output by the following fragment:

    System.out.println( ("Orange " + "Soda").charAt( 7 ) );

17. Column Checker


Answer:

S

System.out.println( ("Orange " + "Soda").charAt( 7 ) );

A temporary String object is created by the concatenation operator. The charAt() method of
that object is invoked which returns the 7th character. The temporary object then becomes garbage.

Column Checker

import java.util.Scanner;
import java.io.*;

class ColumnCheck
{
  public static void main (String[] arg)
  {
    final int colNum = 10;
    int counter = 0;
    String line = null;
    Scanner scan = new Scanner( System.in );
   
    while ( scan.hasNext() )
    {    
      line = scan.nextLine() ;
      counter = counter +1;
      if ( line.length() > colNum && line.charAt( colNum ) != ' ' )
        System.out.println( counter + ":\t" + line );
    }    
  }
}      

Here is a program that checks that every line of a text file has a space character in column 10. This might be used to verify the correct formatting of columnar data or of assembly language source programs.

The program is used with redirection:

C:\>javac ColumnCheck.java

C:\>java ColumnCheck < datafile.txt

With input redirection, the operating system sends characters to the program from a file, not from the keyboard. Now when the program is running nextLine() reads one line from the file.

An improved program might ask the user for several column numbers to check.


Question 17:

Will the program crash if a line has fewer than 10 characters? Inspect the statement

    if ( line.length() > colNum && line.charAt( colNum ) != ' ' ) System.out.println( counter + ":\t" + line );

How is the short-circuit nature of && used here?

18. Substrings


Answer:

if ( line.length() > colNum && line.charAt( colNum ) != ' ' )
  System.out.println( counter + ":\t" + line );

The short-circuit operation of && means that line.length() > colNum is tested first.
If this result is false, then the next part of the condition is not tested (since the result of AND will be false 
regardless of its result). So line.charAt( colNum ) is only performed when it is certain that the line contains a character at index colNum.

Substrings

substring of a string is a sequence of characters from the original string. The characters are in the same order as in the original string and no characters are skipped. For example, the following are all substrings of the string "applecart":

apple
cart
pple
e
lecar

You have previously seen (in chapter 11) the substring() method of String objects:

public String substring(int beginIndex )

This method creates a new substring that consists of the characters from character number beginIndex to the end of the string. For example

"applecart".substring(5)

contains the characters "cart" .

bug Remember: character numbering starts with zero. The leftmost character of a string is character zero. The rightmost character is character length-1.


Question 18:

What is printed by the following code:

    String source = "applecart"; String sub = source.substring(6); System.out.println( sub ); System.out.println( source );

19. Tricky Rules


Answer:

art
applecart

Tricky Rules

The method

public String substring(int beginIndex )

creates a new string. The original string is not changed. There are two tricky rules:

  1. If beginIndex is exactly equal to the length of the original string, a substring is created, but it contains no characters (it is an empty string)
  2. If beginIndex is greater than the length of the original string, or a negative value, an IndexOutOfBoundsException is thrown (and for now, your program crashes).


Question 19:

What string is formed by the following expressions? (click on the button when you have decided)

    ExpressionNew StringComment
    String snake = "Rattlesnake";
    snake.substring(6)
    snake.substring(0)
    snake.substring(10)
    snake.substring(11)
    snake.substring(12)

20. Another substring()


Answer:

ExpressionSubstringComment
String snake = "Rattlesnake";"Rattlesnake"Create original String
snake.substring(6)"snake"Characters starting at character 6 to the end
snake.substring(0)"Rattlesnake"The new substring contains all the characters of the original string
snake.substring(10)"e"Character 10 is the last one
snake.substring(11)""If beginIndex==length, an empty substring is created.
snake.substring(12) If beginIndex is greater than length, a
IndexOutOfBoundsException is thrown.

Another substring()

Expression Result
String source = "Subscription"; "Subscription"
source.substring(0,3) "Sub"
source.substring(3,9) "script"
source.substring(0,0) ""
source.substring(0,1) "S"
source.substring(0,source.length()) "Subscription"

Here is another method of String objects:

substring(int beginIndex, int endIndex)

This method creates a new String containing characters from the original string starting at beginIndex and ending at endIndex-1.

bugWarning: the character at endIndex is not included.

The length of the resulting substring is endIndex-beginIndex.

Here is a picture that shows the character numbering. The 'n' is character 11.

subscription

Question 20:

What does this code write?

    String stars = "*****" ; int j = 1; while ( j <= stars.length() ) { System.out.println( stars.substring(0,j) ); j = j+1; }

21. More Tricky Rules


Answer:

*
**
***
****
*****

More Tricky Rules

As with the other substring method, this one

public String substring(int beginIndex, int endIndex )

creates a new string. The original string is not changed. Here are some more rules. Essentially, the rules say that if the indexes make no sense, a IndexOutOfBoundsException is thrown.


  1. If beginIndex is negative value, an IndexOutOfBoundsException is thrown.
  2. If beginIndex is larger than endIndex, an IndexOutOfBoundsException is thrown.
  3. If endIndex is larger than the length, an IndexOutOfBoundsException is thrown.
  4. If beginIndex equals endIndex, and both are within range, then an empty string is returned.

Usually, when an exception is thrown your program halts. Future chapters discuss how to deal with exceptions


Question 21:

Decide on what string is formed by the following expressions:

ExpressionNew StringComment
String snake = "Rattlesnake";
snake.substring(0,6)
snake.substring(0,11)
snake.substring(10,11)
snake.substring(6,6)
snake.substring(5,3)
snake.substring(5,12)

22. Control Characters inside String Objects


Answer:

ExpressionNew StringComment
String snake = "Rattlesnake";"Rattlesnake"Create original String
snake.substring(0,6)"Rattle"Characters starting at character 0 to character 6-1
snake.substring(0,11)"Rattlesnake"0 to length includes all the characters of the original string
snake.substring(10, 11)"e"Character 10 is the last one
snake.substring(6,6)""If beginIndex==endIndex, an empty substring is created.
snake.substring(5,3) If beginIndex is greater than endIndex, an exception is thrown.
snake.substring(5,12) if endIndex is greater than length, an exception is thrown.

Control Characters inside String Objects

class BeautyShock
{
  public static void main (String[] arg)
  {
    String line1 = "Only to the wanderer comes\n";
    String line2 = "Ever new this shock of beauty\n";

    String poem  = line1 + line2;

    System.out.print( poem );
  }
} 

Recall that control characters are bit patterns that indicate such things as the end of a line or page separations. Other control characters represent the mechanical activities of old communications equipment. The characters that a String object contains can include control characters. Examine the program.

The sequence \n represents the control character that ends a line. This control character is embedded in the data of the strings. The object referenced by poem has two of them. The program writes to the monitor:

Only to the wanderer comes
Ever new this shock of beauty

Although you do not see them in the output, the control characters are part of the data in the String.

Here is another method from the String class:

public String toLowerCase();

This method constructs a new String object containing all lower case letters. There is also a method that produces a new String object containing all upper case letters:

public String toUpperCase();


Question 22:

Here are some lines of code. Which ones are correct?

Line of code:
Correct or Not?
String line = "The Sky was like a WaterDrop" ;
String a = line.toLowerCase();
String b = toLowerCase( line );
String c = toLowerCase( "IN THE SHADOW OF A THORN");
String d = "Clear, Tranquil, Beautiful".toLowerCase();
System.out.println( "Dark, forlorn...".toLowerCase() );

23. Temporary Objects


Answer:

Line of code:
Correct or Not?
String line = "The Sky was like a WaterDrop" ;
correct
String a = line.toLowerCase();
correct
String b = toLowerCase( line );
NOT correct
String c = toLowerCase( "IN THE SHADOW OF A THORN");
NOT correct
String d = "Clear, Tranquil, Beautiful".toLowerCase();
correct
System.out.println( "Dark, forlorn...".toLowerCase() );
correct


The "correct" answer for the last two lines might surprise you, but those
lines are correct (although perhaps not very sensible.) Here is why:

Temporary Objects

String d     =  "Clear, Tranquil, Beautiful".toLowerCase();
                 ---------------+-----------     ---+---
   |                            |                   |
   |                            |                   |
   |             First:  a temporary String         |
   |                     object is created          |
   |                     containing these           |
   |                     these characters.          |
   |                                                |
   |                                               Next: the toLowerCase() method of
   |                                                     the temporary object is
Finally:  the reference to the second                    called. It creates a second 
          object is assigned to the                      object, containing all lower
          reference variable, d.                         case characters.

The temporary object is used to construct a second object. The reference to the second object is assigned to d. Now look at the last statement:

System.out.println( "Dark, forlorn...".toLowerCase() );

String is constructed. Then a second String is constructed (by the toLowerCase() method). A reference to the second String is used as a parameter for println(). Both String objects are temporary. After println() finishes, both Strings are garbage.

(There is nothing special about temporary objects. What makes them temporary is how the program uses them. The objects in the above statement are temporary because the program saves no reference to them. The garbage collector will soon recycle them.)


Question 23:

Review:

  • Can an object reference variable exist without referring to an object?
  • Can an object exist without an object reference variable that refers to it?

24. The startswith () Method


Answer:

  • Can an object reference variable exist without referring to an object?
    • Yes, a reference variable can be declared without initialization:
      String myString;
    • Also, a reference can be set to null.
  • Can an object exist without an object reference variable that refers to it?
    • Yes, as seen in the previous example. Such objects are temporary.

The startsWith() Method

class PrefixTest
{
  public static void main ( String args[] )
  {
     String burns = "My love is like a red, red rose.";

     if ( burns.startsWith( "My love" ) )
       System.out.println( "Prefix 1 matches." );
     else
       System.out.println( "Prefix 1 fails." );

     if ( burns.startsWith( "my love" ) )
       System.out.println( "Prefix 2 matches." );
     else
       System.out.println( "Prefix 2 fails." );

     if ( burns.startsWith( "  My love" ) )
       System.out.println( "Prefix 3 matches." );
     else
       System.out.println( "Prefix 3 fails." );

     if ( burns.startsWith( "  My love".trim() ) )
       System.out.println( "Prefix 4 matches." );
     else
       System.out.println( "Prefix 4 fails." );
  }
}


Here is another method of the String class:

    public boolean startsWith(String  prefix); 

The startsWith() method tests if one String is the prefix of another. This is frequently needed in programs. (Although this example is too short to show a real-world situation.)

Notice how trim() is used in the last if statement.


Question 24:

What does the program write?

25. More String Operations


Answer:

Prefix 1 matches.
Prefix 2 fails.
Prefix 3 fails.
Prefix 4 matches.

More String Operations

Here is how the last if of the program worked:


                
String burns = "My love is like a red, red rose.";

. . . . . .

if ( burns.startsWith( "  My love".trim() ) )
  System.out.println( "Prefix 4 matches." );  <-- this branch executes
else
  System.out.println( "Prefix 4 fails." );  


The string " My love" starts with two spaces, so it does not match the start of the string referenced by burns. However, its trim() method is called, which creates a new String without those leading spaces:

if ( burns.startsWith( "  My love".trim() ) )
           -----+----  -----+-----
                |           |
                |           |
                |           +------- 1.  A temporary String object 
                |                        is constructed.
                |                        This temporary object 
                |                        contains "  My love"
                |
                |                    2.  The trim() method of the 
                |                        temp object is called.
                |
                |                    3.  The trim() method returns 
                |                        a reference to a SECOND
                |                        temporary String object 
                |                        which it has constructed.
                |                        This second temporary 
                |                        object contains "My love"
                |
                |                    4.  The parameter of the 
                |                        startsWith() method
                |                        now is a reference to 
                |                        a String, as required.
                |
                +---- 5. The startsWith() method of 
                         the object referenced by  
                         burns is called.
                         
                      6.  The startsWith() method 
                          returns true

                      7.  The true-branch of the 
                          if-statement executes. 

Programmers usually do not think about what happens in such detail. Usually, a programmer thinks: "trim the spaces of one String and see if it is the prefix of another." But sometimes, you need to analyze a statement carefully to be sure it does what you want.

Question 25:

What does the toLowerCase() method of class String do?

26. Cascaded String Operations


Answer:

It creates a new String which is a lowercase version of the original string.

Cascaded String Operations

Sometimes a method of a String creates another String, and then a method of that second String is invoked to create a third String (and so on). This is sometimes called a cascade. Usually a cascade involves intermediate temporary objects. Look at these lines of code:

   String burns = "My love is like a red, red rose.";

     . . . . . .

     if ( burns.toLowerCase().startsWith( "  MY LOVE".trim().toLowerCase() ) )
       System.out.println( "Both start with the same letters." ); 
     else
       System.out.println( "Prefix fails." );  


What is printed? Decide what string owns the startsWith method, and then decide what parameter it is called with.


Question 26:

What does the above write to the monitor?

27. End of the Chapter


Answer:

Both start with the same letters.

" MY LOVE".trim().toLowerCase() creates the temporary string "my love" .

"burns.toLower() creates the temporary string "my love is like a red, red rose."

Both strings start out the same.

End of the Chapter

That was a complicated question. I hope you rose to the occasion. If you got burned, review the example. You may wish to review the following.