Review Exercises
2.1 The First Java Program
I n t r o d u c t i o n
e will describe the basic structure of simple Java programs in this chapter. We will also describe the steps you follow to run Java programs. We expect you to actually run these sample programs to verify that your computer (either your own or the one at the school’s computer center) is set up properly to run the sample programs presented in the book. It is important to verify this now. Otherwise, if you encounter a problem later, you won’t be able to determine whether the problem is the result of a bad program or a bad setup. Please check Appendix A for information on how to run the textbook’s sample programs.
We will develop a sample application program in Section 2.4 following the design, coding, and testing phases of the software life cycle. We stress here again that our objective in this book is to teach object-oriented programming and how to apply object-oriented thinking in program development. The Java language is merely a means to implement a design into an executable program. We chose Java for this book because Java is a much easier language than other object-oriented pro- gramming languages to use to translate a design into an actual code. Beginning stu- dents often get lost in the language details and forget the main objective of learning the development process, but the use of Java should minimize this problem.
W
An object-oriented program uses objects.
pixel
Those of you who have some experience in programming, whether object- oriented or non-object-oriented, will probably find many similarities between Java and the programming languages you already know. This similarity may ac- celerate your learning process, but in many cases what seems to be similar at first may turn out to be quite different. So please do not jump to any conclusions about similarity prematurely.
Closing the frame window of the Ch2Sample1 program does not terminate the program itself. Most common Java development tools provide a simple way, such as clicking a toolbar button, to terminate a running program. If you are using a Java development tool that does not let you stop a running program easily, then insert the statement
myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
It may sound too obvious, but let’s begin our study of object-oriented programming with this obvious notion. Here’s the program code:
Figure 2.1 Result of running the Ch2Sample1program. The window size is 300 by 200 pixels and has the title My First Java Program.
/*
Chapter 2 Sample Program: Displaying a Window File: Ch2Sample1.java
*/
import javax.swing.*;
class Ch2Sample1 {
public static void main(String[] args) { JFrame myWindow;
myWindow = new JFrame();
myWindow.setSize(300, 200);
myWindow.setTitle("My First Java Program");
myWindow.setVisible(true);
} }
after
myWindow.setVisible(true);
so the program terminates automatically when the frame window is closed. Please read Appendix A for more information.
This program declares one class called Ch2Sample1, and the class includes one method called main. From this mainmethod, the Ch2Sample1class creates and uses a JFrame object named myWindow by sending the three messages setSize, setTitle, and setVisibleto the object. The JFrameclass is one of many classes that come with the Java system. An instance of this JFrameclass is used to represent a single window on the computer screen. To differentiate the classes that program- mers define, including ourselves, and the predefined classes that come with the Java system, we will call the first programmer-defined classesand the latter Java stan- dard classes, or simply, standard classes. We also use the term system classes to refer to the standard classes.
Expressing this program visually results in the program diagram shown in Figure 2.2. In this diagram, we draw individual messages, but doing so would eas- ily clutter a diagram when we have more than a handful of messages. Instead of drawing messages individually, we can draw one arrow to represent a dependency relationship. For this program, we say the Ch2Sample1class is dependent on the services provided by a JFrame object, because the Ch2Sample1 class sends mes- sages to the MyWindow object. We draw a dotted arrow from Ch2Sample1 to myWindowto indicate the dependency relationship, as shown in Figure 2.3
programmer- defined classes standard classes program diagram dependency relationship
myWindow : JFrame Ch2Sample1
setTitle(“My First Java Program”) setSize(300, 200)
setVisible(true)
Figure 2.2 The program diagram for the Ch2Sample1program.
Ch2Sample1
myWindow : JFrame
Figure 2.3 The program diagram for the Ch2Sample1program that shows the dependency relationship.
We begin the explanation of the program from the following core five lines of code:
JFrame myWindow;
myWindow = new JFrame();
myWindow.setSize(300, 200);
myWindow.setTitle("My First Java Program");
myWindow.setVisible(true);
We will explain the rest of the program in Section 2.2. These five lines of code represent the crux of the program, namely, an object-oriented program that uses objects. The rule to remember in using objects is as follows:
To use an object in a program, first we declare and create an object, and then we send messages to it.
In the remainder of this section, we will describe how to declare an object, create an object, and use an object by sending messages to the object.
Object Declaration
Every object we use in a program must be declared. An object declaration desig- nates the name of an object and the class to which the object belongs. Its syntax is
<class name> <object names> ;
where <object names> is a sequence of object names separated by commas and
<class name>is the name of a class to which these objects belong. Here’s how the general syntax is matched to the object declaration of the program:
Class Name Object Names
The class must be One object is
defined beforehand. declared here.
JFrame myWindow;
Here are more examples:
Account checking;
Customer john, jack, jill;
The first declaration declares an Accountobject named checking, and the second declaration declares three Customerobjects.
object declaration syntax
Table 2.2 in the Summary section summarizes the naming convention.
To declare an object as an instance of some class, the class must be defined already. First we will study how to use objects from system classes. Later in the book, we will show you how to define your own classes, from which you can create instances.
When we declare an object, we must give it a name. Any valid identifier that is not reserved for other uses can be used as an object name. A Java identifieris a sequence of letters, digits, underscores (_), and dollar signs ($) with the first one being a nondigit. We use an identifier to name a class, object, method, and others.
The following words are all valid identifiers:
MyFirstApplication _age
FunTime Hello$World
ComputeArea x123
DEFAULT_VALUE velocity
Upper- and lowercase letters are distinguished, so the following four identi- fiers are distinct:
myWindow mywindow MYwindow MYWINDOW
No spaces are allowed in an identifier, and therefore, the three lines Sample Program
My First Application Program FunTime are all invalid identifiers.
Since upper- and lowercase letters are distinguished, you can use robotas the name for an object of the class Robot. We name objects in this manner whenever possible in this book so we can easily tell to which class the object belongs. We fol- low the Java standard naming conventionof using an uppercase letter for the first letter of the class names and a lowercase letter for the first letter of the object names in this book. It is important to follow the standard naming convention so others who read your program can easily distinguish the purposes of identifiers. Programs that follow the standard naming convention are easier to read than those that do not. And remember that software maintenance is easier with easy-to-understand programs.
When an identifier consists of multiple words, the Java naming convention dictates the first letter from every word will be capitalized, except the first word if the identifier is an object name. For example, we write MyMainWindow and myMainWindowfor the class and object name, respectively.
standard naming convention identifier
Follow the standard naming convention in writing your Java programs to make them easier to read.
Instead of writing statements for object declaration and creation separately, we can combine them into one statement. We can write, for example,
Student john = new Student();
instead of
Student john;
john = new Student();
Object Creation
No objects are actually created by the declaration. An object declaration simply declares the name (identifier) that we use to refer to an object. For example, the declaration
JFrame myWindow;
designates that the name myWindow is used to refer to a JFrame object, but the actual JFrame object is not yet created. We create an object by invoking the new operator. The syntax for newis
<object name> = new <class name> ( <arguments> ) ;
where <object name>is the name of a declared object, <class name>is the name of the class to which the object belongs, and <arguments> is a sequence of values passed to the newoperation. Let’s match the syntax to the actual statement in the sample program:
Object Name Class Name
Name of the object An instance of this
we are creating class is created.
myWindow = new JFrame ( ) ;
Argument No arguments are used here.
Figure 2.4 shows the distinction between object declaration and creation.
Figure 2.5 shows the relationship between the UML-based program diagram and the state-of-memory diagram. The state-of-memory diagram borrows the notation from UML for consistency, but it is not a true UML diagram because it uses sym- bols and notations not found in UML.
Now, consider the following object declaration and two statements of object creation:
Customer customer;
customer = new Customer( );
customer = new Customer( );
What do you think will happen? An error? No. It is permissible to use the same name to refer to different objects of the same class at different times. Figure 2.6
newoperator
object creation syntax
shows the state-of-memory diagram after the second newis executed. Since there is no reference to the first Customerobject anymore, eventually it will be erased and returned to the system. Remember that when an object is created, a certain amount of memory space is allocated for storing this object. If this allocated but unused space is not returned to the system for other uses, the space gets wasted. This
State-of-Memory Notation
Program Diagram Notation account : Account account
:Account
The state-of-memory diagram uses the same UML notation, but it also includes symbols and notations not found in UML.
Figure 2.5 Relationship between the state-of-memory diagram and the program diagram notation.
State of Memory
Account account;
account = new Account( );
A Account account;
B account = new Account( );
after is A executed account
after is B executed The identifier account is
declared and space is allocated in memory.
An Account object is created and the identifier account is set to refer to it.
account
:Account
Figure 2.4 Distinction between object declaration and object creation.
returning of space to the system is called deallocation, and the mechanism to deal- locate unused space is called garbage collection.
Message Sending
After the object is created, we can start sending messages to it. The syntax for send- ing a message to an object is
<object name> . <method name> ( <arguments> ) ;
where <object name>is an object name, <method name>is the name of a method of the object, and <arguments>is a sequence of values passed to the method. In the sample program, we send the setVisible message with the argument true to themainWindowobject to make it appear on the screen. Once again, let’s match the components in the general syntax to the actual statement:
Object Name Method Name
Name of the object to which The name of the message
we are sending a message we are sending
myWindow . setVisible ( true ) ; Argument
The argument we are passing with the message
Figure 2.7 shows the correspondence between message sending as repre- sented in the program diagram and in the Java statement. Because the object that receives a message must possess a corresponding method, we often substitute the expression sending a message with calling a method. We will use these expressions interchangeably.
customer
:Customer :Customer
The first Customer object will be deallocated eventually because there are no references to it anymore.
Created with the second new.
Created with the first new.
Customer customer;
customer = new Customer();
customer = new Customer();
Figure 2.6 The state after two newcommands are executed.
garbage collection
message- sending syntax
Notice the argument for the setVisiblemessage does not include double quotes as did the one for the setTitlemessage in the example shown on page 32. The argu- ment trueis one of the two possible logical values (the other is false) used in Java programs. We will study more about the use of logical values later in the book, start- ing from Chapter 5. For now, it suffices to remember that there are two logical values— trueand false—used for certain specific purposes.
Passing truein the setVisiblemessage makes the receiving object appear on the screen. Passing falsemakes the object disappear from the screen. So, for exam- ple, if we write
myWindow.setVisible(true);
myWindow.setVisible(false);
myWindow.setVisible(true);
thenmyWindowwill appear once, disappear, and then appear on the screen again.
(Note: Because the computer will execute these statements so quickly, you may not notice any difference from the original program. See Exercise 25 on page 80.)
The word true(and false) is called a reserved word. It is an identifier that is used for a specific purpose and cannot be used for any other purpose, such as for the name of an object.
myWindow:JFrame setVisible(true) Program
Diagram
Corresponding Java Statement
Note: We can place method icons on either side of a class or instance icon.
myWindow . setVisible ( true ) ;
Figure 2.7 Correspondence between message sending as represented in the program diagram and in the actual Java statement.
The expressioncalling object O’s method Mis synonymous withsending message M to object O.
1. Which of the following are invalid identifiers?
a. one
b. “Good Bye”
c. 1234
d. DecafeLattePlease reserved word
e. $hello$
f. JAVA
g. hello, there h. acct122
i. 4you j. _doWork k. Wait_For_Me
2. What’s wrong with the following code?
JFrame myWindow();
myWindow.setVisible(true);
3. Is there anything wrong with the following declarations?
mainWindow MainWindow;
Account, Customer account, customer;
4. Which of the following statements is valid?
a. myFirstWindow.setVisible("true"); b. myFirstWindow.setVisible(true);