Section 2.2. Using String Objects


[Page 64 (continued)]

2.2. Using String Objects

A Java program is a collection of interacting objects, where each object is a module that encapsulates a portion of the program's attributes and actions. Objects belong to classes, which serve as templates, or blueprints, for creating objects. Think again of the cookie-cutter analogy. A class is like a cookie cutter. Just as a cookie cutter is used to shape and create individual cookies, a class definition is used to shape and create individual objects.

Programming in Java is primarily a matter of designing and defining class definitions, which are then used to construct objects. The objects perform the program's desired actions. To push the cookie-cutter analogy a little further, designing and defining a class is like building a cookie cutter. Obviously, very few of us would bake cookies if we first had to design and build the cookie cutters. We'd be better off using a pre-built cookie cutter. By the same token, rather than designing our own classes, it will be easier to get into "baking" programs if we begin by using some predefined Java classes.

The Java library contains many predefined classes that we will use in our programs. So let's begin our study of programming by using two of these classes, the String and Graphics classes.

2.2.1. Creating and Combining Strings

Strings are very useful objects in Java and in all computer programs. They are used for inputting and outputting all types of data. Therefore, it essential that we learn how to create and use String objects.

Figure 2.1 provides an overview of a very small part of Java's String class. In addition to the two String() constructor methods, which are used to create strings, it lists several useful instance methods that can be used to manipulate strings. The String class also has two instance variables. One stores the String's value, which is a string of characters such as "Hello98," and the other stores the String's count, which is the number of characters in its string value.


[Page 65]

Figure 2.1. A partial representation of the String class.
(This item is displayed on page 64 in the print version)


Recall from Chapter 0 that in order to get things done in a program we send messages to objects. The messages must correspond to the object's instance methods. Sending a message to an object is a matter of calling one of its instance methods. In effect, we use an object's methods to get the object to perform certain actions for us. For example, if we have a String, named str and we want to find out how many characters it contains, we can call its length() method, using the expression str.length(). If we want to print str's length, we can embed this expression in a print statement:

System.out.println(str.length()); // Print str's length 


In general, to use an object's instance method, we refer to the method in dot notation by first naming the object and then the method:

objectName.methodName();

Dot notation


The objectName refers to a particular object, and the methodName() refers to one of its instance methods.

As this example makes clear, instance methods belong to objects, and in order to use a method, you must first have an object that has that method. Thus, to use one of the String methods in a program, we must first create a String object.

To create a String object in a program, we first declare a String variable.

String str; // Declare a String variable named str 


We then create a String object by using the new keyword in conjunction with one of the String() constructors. We assign the new object to the variable we declared:

str = new String("Hello"); // Create a String object 


This example will create a String that contains, as its value, the word "Hello" that is passed in by the constructor. The String object that this creates is shown in Figure 2.2.

Figure 2.2. A String object stores a sequence of characters and a count giving the number of characters.



[Page 66]

We can also use a constructor with an empty parameter list. Note that in this case we combine the variable declaration and the object creation into one statement:

String str2 = new String(); // Create a String 


This example will create a String object that contains the empty string as its value. The empty string has the literal value ""that is, a pair of double quotes that contain no characters. Because the empty string has no characters, the count variable stores a zero (Fig. 2.3).

Figure 2.3. The empty string has a value of "" and its length is 0.


Note that we use a constructor to assign an initial value to a variable of type String (or of a type equal to any other class). This differs from how we assign an initial value to variables of primitive type, for which we use a simple assignment operator. This difference is related to an important difference in the way Java treats these two types of variables. Variables of primitive type are names for memory locations where values of primitive type are stored. As soon as they are declared they are assigned a default value of that primitive type. The default value for int is 0, and the default value for boolean is false. On the other hand, variables declared to be of a type equal to a class name are designed to store a reference to an object of that type. (A reference is also called a pointer because it points to the memory address where the object itself is stored.) A constructor creates an object somewhere in memory and supplies a reference to it that is stored in the variable. For this reason, variables that are declared as a type equal to a class name are said to be variables of reference type, or reference variables. Reference variables have a special default value called null after they are declared and before they are assigned a reference. It is possible to check whether or not a reference variable contains a reference to an actual object by checking whether or not it contains this null pointer.

Once you have constructed a String object, you can use any of the methods shown in Figure 2.1 on it. As we have already seen, we use dot notation to call one of the methods. Thus, we first mention the name of the object followed by a period (dot), followed by the name of the method. For example, the following statements print the lengths of our two strings:

System.out.println(str.length()); System.out.println(str2.length()); 


Another useful String method is the concat(String) method which can be used to concatenate two strings. This method takes a String argument. It returns a String that combines the String argument to the String that the method is called on. Consider this example:

String s1 = new String("George "); String s2 = new String("Washington"); System.out.println(s1.concat(s2)); 



[Page 67]

In this case, the concat() method adds the String s2 to the end of the String s1. The result, which gets printed, will be the String "George Washington."

Because strings are so important, Java allows a number of shortcuts to be used when creating and concatenating strings. For example, you don't have to use new String() when creating a new string object. The following code will also work:

String s1 = "George "; String s2 = "Washington"; 


Similarly, an easier way to concatenate two String objects is to use the plus sign (+), which serves as a concatenation operator in Java:

System.out.println(s1 + s2); 


Another useful String method is the equals() method. This is a boolean method that is used to compare two Strings. If both Strings have the same characters, in the same order, it will return true. Otherwise it will return false. For example, consider the following code segment:

String s1 = "Hello"; String s2 = "Hello"; String s3 = "hello"; 


In this case, the expression s1.equals(s2) will be true, but s1.equals(s3) will be false.

It is important to note that the empty string is not the same as a String variable that contains null. Executing the statements:

String s1; String s2 = ""; System.out.println(s1.equals(s2)); 


will not only not print out true; it will cause the program to terminate abnormally. It is an error to use the method of a String variable, or any other variable whose type is a class, before it has been assigned an object. When the preceding code is executed, it will report a null pointer exception, one of the most common runtime errors. When you see that error message, it means that some method was executed on a variable that does not refer to an object. On the other hand, the empty string is a perfectly good String object which just happens to contain zero characters.

Figure 2.4 on the next page shows a program that uses string concatenation to create some silly sentences. The program declares a number of string variables, named s, s1, and so on, and it instantiates a String object for each variable to refer to. It then prints out a top-five list using the concatenation operator to combine strings. Can you figure out what it prints without running it?


[Page 68]

Figure 2.4. A program that prints silly string puns.

public class StringPuns {   public static void main(String args[])   { String s = new String("string");     String s1 = s.concat(" puns.");     System.out.println("Here are the top 5 " + s1);     String s2 = "5. Hey baby, wanna ";     String s3 = s + " along with me.";     System.out.println(s2 + s3);     System.out.println("4. I've got the world on a " + s + ".");     String s4 = new String("two");     String s5 = ". You have more class than a ";     System.out.print(s4.length());     System.out.println(s5 + s + " of pearls.");     System.out.print("2. It is ");     System.out.print(s.equals("string"));     System.out.println(" that I am no " + s + " bean.");     String s6 = " quintet.";     System.out.println("1. These puns form a " + s + s6);   } // main() } // StringPuns class 

Self-Study Exercises

Exercise 2.1

What is the output to the console window when the following Java code fragment is executed:

String s = "ing"; System.out.println("The s" + s + s + " k" + s + "."); 





Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net