next up previous
Next: Loopage! Up: Part One Previous: Part One

Mess around with Strings and their methods

1.
Create a new project named Name, and make it an application. Personally, I have stopped putting a $\pi$ at the end of my project names, since it seems to cause more problems than it's worth. So my folder, project, and class are all named Name.
2.
In main, create a variable named name with type String and initialize it with a String literal that contains your name. Notice that unlike most other Object types, you can initialize Strings with literals. You don't have to use the keyword new to create a new String.

3.
Print the String.

One of the methods you can invoke on Strings is length(). The way you invoke a method on an Object is similar to the way you extract a field from an object; you use dot notation. For example:

     int len = name.length();
     System.out.println (len);

Notice the parentheses after length. They indicate that length is a method that takes no arguments, as opposed to a field named length. That probably (but not necessarily) indicates that length calculates the length of the String when you invoke it, as opposed to keeping the value in memory along with the String. All the methods you can invoke on Strings are described on page 326.

4.
Type in and test the preceding code.

Another method you can invoke on a String is toUpperCase. This method returns a new String that is the same as the old String except that all the lower case letters are converted to upper case. It does not modify the existing String. In fact, nothing you do can modify an existing String--they are immutable.

5.
Invoke toUpperCase and toLowerCase on your String and print the results. You can print the results directly or store them in an intermediate variable.


next up previous
Next: Loopage! Up: Part One Previous: Part One
Allen B. Downey
3/11/1998