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 ...

Get Special Edition Using Java 2 Standard Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.