Prefix 1 matches. Prefix 2 fails. Prefix 3 fails. Prefix 4 matches.
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 list of the | startsWith() method | now has 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 if causes the true-branch to execute
Ordinarily, programmers 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. Look again at the above statement and practice thinking about it at several levels of detail.