String myString;
null
.startsWith()
MethodHere 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, as usual,
the following example is too short to show a real-world situation.
Trust me. This method is one to know.)
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.