Output Using Strings

Though this will be explained in more detail later, a String is an object. Objects can have methods which are actions that can be used with that object.

For instance, lets say we declare the following strings:

String firstName = "Dale"; String lastName = "Reed";

We can retrieve a String's length by calling the length() method for that string. This can be done to any string:

int n = firstName.length(); int x = "antidisestablishmentarianism".length(); System.out.println("Length of firstName is: " + n + ", and length of long word is: " + x); System.out.println("Length of \"seven\" is: " + "seven".length() );

A String's length() method returns a value, which can be stored or used in place.

The equals() method is also needed to compare strings, E.g.:

String secretPassword = "BigSecret"; String bogusGuess = "rosebud"; if (secretPassword.equals( bogusGuess)) { System.out.println("Correct. You now have top-secret clearance.") } else { System.out.println("NOT correct. Even as you read this they are coming for you.") }

(But we're getting a bit ahead of ourselves here, as we haven't studied the "if" statement yet.)

There are String methods to get the length, compare strings, change case, eliminate spaces, and search for substrings or characters. For more information see the String examples in CFX, or see Sun's documentation (Find "String" in the lower-left pane, then click on "methods" to see the various options.)