The startsWith() Method

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

  • Can an object reference variable exist that 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

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, study it carefully.)

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." );
  }
}

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

QUESTION 24:

What does the program write to the monitor?