Prefix 1 matches. Prefix 2 fails. Prefix 3 fails. Prefix 4 matches.
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.
What does the toLowerCase()
method of class String
do?