O'Reilly logo

Special Edition Using Java 2 Standard Edition by Geoff Friesen, Chuck Cavaness, Brian Keeton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Getting Information About a String Object

After you have your String object constructed, you can call upon the methods in the String class to obtain information about the string. To get the length of the string, for example, you can call the length method, like this:

String str = "This is a string";
int len = str.length();

The value of the len variable should be 16, which is the length of the string (including spaces, of course).

If you want to know whether a string starts with a certain prefix, you can call the startsWith method, like this:

String str = "This is a string";
boolean result = str.startsWith("This");

Here, the boolean variable result is equal to true, because str does indeed start with This. In the following example, result ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required