Download presentation
Presentation is loading. Please wait.
1
Intro to OOP with Java, C. Thomas Wu
Chapter 1 Introduction to Object-Oriented Programming and Software Development ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
2
Intro to OOP with Java, C. Thomas Wu
Objectives After you have read and studied this chapter, you should be able to Name the basic components of object-oriented programming Differentiate classes and objects. Differentiate class and instance methods. Differentiate class and instance data values. Draw program diagrams using icons for classes and objects Describe significance of inheritance in object-oriented programs Name and explain the stages of the software lifecycle Upon completing this lesson and studying the corresponding sections from Chapter 1 of the textbook, you will have a basic understanding of classes, objects, methods, and data values. You should also be able to draw correct icons for classes and objects. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
3
Intro to OOP with Java, C. Thomas Wu
Classes and Objects Object-oriented programs use objects. An object is a thing, both tangible and intangible. Account, Vehicle, Employee, etc. To create an object inside the computer program, we must provide a definition for objects—how they behave and what kinds of information they maintain —called a class. An object is called an instance of a class. The two most important concepts in object-oriented programming are the class and the object. In the broadest term, an object is a thing, both tangible and intangible, which we can imagine. A program written in object-oriented style will consist of interacting objects. For a program to maintain bank accounts for a bank, for example, we may have many Account, Customer, Transaction, and ATM objects. An object is comprised of data and operations that manipulate these data. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
4
Graphical Representation of a Class
Intro to OOP with Java, C. Thomas Wu Graphical Representation of a Class <Class Name> We use a rectangle to represent a class with its name appearing inside the rectangle. Example: Account Motorcycle This is how we represent a class. The name of a class appears inside the rectangle. The example shows two classes: Account and Motorcycle. The notation we used here is based on the industry standard notation called UML, which stands for Unified Modeling Language. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
5
Graphical Representation of an Object
Intro to OOP with Java, C. Thomas Wu Graphical Representation of an Object We use a rectangle to represent an object and place the underlined name of the object inside the rectangle. <Object Name> Example: SV198 This is how we represent an object. The name of an object also appears inside the rectangle, but unlike the class name, an object name is underlined. This example shows an object whose name is SV198. Notice that just by looking at this icon, we cannot tell what type of an object it is? Is it a Motorcycle? Or is an Account? We will use another notation, shown in the next slide, when we wish to identify the class it belongs to. This is an object named SV198. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
6
An Object with the Class Name
Intro to OOP with Java, C. Thomas Wu An Object with the Class Name This notation indicates the class which the object is an instance. <Object Name> : <Class Name> Example: SV198 : BankAccount To indicate the class of an object, we suffix the object name with a colon and the class name. The example shows an object SV198 is a BankAccount object. This tells an object SV198 is an instance of the BankAccount class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
7
Intro to OOP with Java, C. Thomas Wu
Messages and Methods To instruct a class or an object to perform a task, we send a message to it. You can send a message only to the classes and objects that understand the message you sent to them. A class or an object must possess a matching method to be able to handle the received message. A method defined for a class is called a class method, and a method defined for an object is called an instance method. A value we pass to an object when sending a message is called an argument of the message. An object is not a passive container of information. Rather, it is an active entity capable of carrying out tasks. Tasks such as deducting a withdrawal amount from an account, computing the shortest route from your dorm to a classroom, and so forth. To command an object (or a class) to do something, we send a message to it. Not all objects (and classes) can respond to any messages sent them. They must be programmed to recognize messages. In other words, we define methods. Once a method is defined, then we can send a matching message. For example, we define a method, say, move to a MobileRobot object. Once this method is programmed correctly, then we can send a message to a MobileRobot object to move. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
8
Intro to OOP with Java, C. Thomas Wu
Sending a Message Message deposit with the argument is sent to a BankAccount object SV198. deposit SV198 : BankAccount Here’s an example of sending a message. This slide shows a sending of the message deposit to SV198. The BankAccount class must include a method named deposit. Otherwise, there will be an error because SV198 won’t be able to recognize the message. The name of the message we send to an object or a class must be the same as the method’s name. Because they are the same, the phrase “calling an object’s method” is synonymous to “sending a message to an object.” ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
9
Sending a Message and Getting an Answer
Intro to OOP with Java, C. Thomas Wu Sending a Message and Getting an Answer Ask for the current balance of this particular account. getCurrentBalance() SV198 : BankAccount current balance The current balance of SV198 is returned. The deposit method in the previous slide is an action-only method. An object takes some action when called, but returns no answer back to the caller. The getCurrentBalance method in this slide is a value-returning method. When called, an object will return a value. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
10
Intro to OOP with Java, C. Thomas Wu
Calling a Class Method Ask for the maximum possible speed for all MobileRobot objects is returned. MobileRobot getMaximumSpeed() maximum speed Here’s an example of calling a class method. It is not as common as the instance methods, but it can be handy in certain situations. The maximum speed of all MobileRobot objects is the same. Since the result is the same for all instances, we define getMaximumSpeed as a class method. General Idea: You define an instance method for a task that relates uniquely to individual instances (like getCurrentSpeed, which is different for individual mobile robots) and a class method for a task that relates to all instances of the class collectively. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
11
Class and Instance Data Values
Intro to OOP with Java, C. Thomas Wu Class and Instance Data Values An object is comprised of data values and methods. An instance data value is used to maintain information specific to individual instances. For example, each BankAccount object maintains its balance. A class data value is used to maintain information shared by all instances or aggregate information about the instances. For example, minimum balance is the information shared by all Account objects, whereas the average balance of all BankAccount objects is an aggregate information. Every object from the same class will have the same set of data values. The values themselves for individual objects would be different, of course. We assume here that the minimum balance is the same for all accounts. If this is the case, then the single value for minimum balance is shared by all Account objects. So we need to keep one value of the minimum balance that will be shared by all Account objects. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
12
Sample Instance Data Value
Intro to OOP with Java, C. Thomas Wu Sample Instance Data Value SV129 : BankAccount SV098 : BankAccount SV211 : BankAccount current balance 908.55 354.00 Here we see that all instances of the BankAccount class has a data value named current balance. Although only one instance data value is shown here, it does not mean these objects contain only one data value. Most likely the real BankAccount objects would include about a dozen or so instance data values. We only show a single instance data value here so the diagram would not become cluttered. All three BankAccount objects possess the same instance data value current balance. The actual dollar amounts are, of course, different. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
13
Sample Class Data Value
Intro to OOP with Java, C. Thomas Wu Sample Class Data Value BankAccount minimum balance 100.00 There is one copy of minimum balance for the whole class and shared by all instances. SV098 : BankAccount SV211 : BankAccount SV129 : BankAccount current balance 908.55 354.00 This line is an instance-of relationship. Here we see that a single class data value named minimum balance is shared by all instances. The dotted lines show the three objects are instance of the BankAccount class. To see the significance of a class data value, consider the situation where the minimum balance is represented as an instance data value. Because there’s only one value for the minimum balance, defining it as an instance data value would result in maintaining three copies of the same value, one copy per object. This is a waste of memory space. Not only that, more critically, keeping duplicates in memory will complicate the processing. When we have to change the value for the minimum balance, for example, we have to locate all copies and update them. Imagine updating the duplicates copies of 1000 BankAccount objects. This is a very time consuming and error-prone activity, which can be avoided easily by representing the information as a class data value. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
14
Object Icon with Class Data Value
Intro to OOP with Java, C. Thomas Wu Object Icon with Class Data Value SV129 : BankAccount current balance 908.55 minimum balance 100.00 When the class icon is not shown, we include the class data value in the object icon itself. When we do not include the class icon in a diagram, we can use this notation. Whether the data value name is underlined or not indicates the information is a class or an instance data value. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
15
Intro to OOP with Java, C. Thomas Wu
Inheritance Inheritance is a mechanism in OOP to design two or more entities that are different but share many common features. Features common to all classes are defined in the superclass. The classes that inherit common features from the superclass are called subclasses. We also call the superclass an ancestor and the subclass a descendant. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
16
Intro to OOP with Java, C. Thomas Wu
A Sample Inheritance Here are the superclass Account and its subclasses Savings and Checking. Account Checking Savings ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
17
Inheritance Hierarchy
Intro to OOP with Java, C. Thomas Wu Inheritance Hierarchy An example of inheritance hierarchy among different types of students. Student Graduate Undergrad Masters Doctoral Law Commuting Resident ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
18
Intro to OOP with Java, C. Thomas Wu
Software Engineering Much like building a skyscraper, we need a disciplined approach in developing complex software applications. Software engineering is the application of a systematic and disciplined approach to the development, testing, and maintenance of a program. In this class, we will learn how to apply sound software engineering principles when we develop sample programs. When a construction firm builds a house, it will follow a strict construction sequence that is based on sound engineering principles. Although software is not a physical object, it is just as complex as a building. And we also need to follow a strict software construction sequence if we expect to build an error-free software. We need a software construction sequence that is based on sound software engineering principles. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
19
Intro to OOP with Java, C. Thomas Wu
Software Life Cycle The sequence of stages from conception to operation of a program is called software life cycle. Five stages are Analysis Design Coding Testing Operation and Maintenance In the analysis phase, we perform a feasibility study. We analyze the problem and determine whether a solution is possible. If a solution is possible, the result of this phase is a requirements specification which describes the features of a program. In the design phase, we turn a requirements specification into a detailed design of the program. For an object-oriented design, the output from this phase will be a set of classes/objects that fulfill the requirements. In the coding phase, we implement the design into an actual program, in our case, a Java program. In the testing phase, we run the program using different sets of data to verify that the program runs according to the specification. Two types of testing are possible for object-oriented programs: unit testing and integration testing. With unit testing, we test classes individually. With integration testing, we test that the classes work together correctly. Activity to eliminate programming error is called debugging. An error could be a result of faulty implementation or design. When there's an error, we need to backtrack to earlier phases to eliminate the error. Finally, after the testing is successfully concluded, we enter the operation phase in which the program will be put into actual use. The most important and time-consuming activity during the operation phase is software maintenance. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
20
Intro to OOP with Java, C. Thomas Wu Getting Started with Java
Chapter 2 Getting Started with Java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
21
Intro to OOP with Java, C. Thomas Wu
Objectives After you have read and studied this chapter, you should be able to Identify the basic components of Java programs Write simple Java programs Describe the difference between object declaration and creation Describe the process of creating and running Java programs Use the Date, SimpleDateFormat, String, and JOptionPane standard classes Develop Java programs, using the incremental development approach ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
22
Intro to OOP with Java, C. Thomas Wu
The First Java Program The fundamental OOP concept illustrated by the program: An object-oriented program uses objects. This program displays a window on the screen. The size of the window is set to 300 pixels wide and 200 pixels high. Its title is set to My First Java Program. It’s kind of obvious, but the most fundamental important concept in OOP is the use of objects in a program. We will illustrate this key concept in the first sample program. The program, when executed, will display a window on the screen. The text displayed in the window’s title bar will be My First Java Program. The size of the window is set to 300 pixels wide and 200 pixels high. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
23
Intro to OOP with Java, C. Thomas Wu
Program Ch2Sample1 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); } Declare a name Create an object Use an object Based on what you learned about objects in the previous lessons and the description of the program in previous slide, can you make some sense from this program code? The three key tasks shown in the program are Declaring a name we use to refer to an object Create the actual object which the declared name will refer to Use this object by sending messages to it. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
24
Program Diagram for Ch2Sample1
Intro to OOP with Java, C. Thomas Wu Program Diagram for Ch2Sample1 Ch2Sample1 setSize(300, 200) myWindow : JFrame setTitle(“My First Java Program”) setVisible(true) This program diagram depicts the program structure graphically. From this diagram, we can tell that there is one class and one object, an instance of JFrame, in this program, and that three messages are sent from Ch2Sample1 to myWindow. When many messages are sent from one class or an object to another class or object, then drawing all messages makes the diagram too cluttered. To avoid cluttering, we show only dependency relationships (see next slide). ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
25
Dependency Relationship
Intro to OOP with Java, C. Thomas Wu Dependency Relationship Ch2Sample1 myWindow : JFrame Here’s an example of dependency relationship. To get a big picture, we are not that interested in seeing all the messages sent from one sender to a receiver. Instead, we would like to see who depends on whom. In this diagram, we see that Ch2Sample1 sends messages to myWindow. In other words, Ch2Sample1 depends on the services provided by myWindow to perform its tasks. Instead of drawing all messages, we summarize it by showing only the dependency relationship. The diagram shows that Ch2Sample1 “depends” on the service provided by myWindow. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
26
Intro to OOP with Java, C. Thomas Wu
Object Declaration Class Name This class must be defined before this declaration can be stated. Object Name One object is declared here. JFrame myWindow; More Examples To use an object in a program, we first declare and create an object, and then we send messages to it. The first step in using an object is to declare it. An object declaration designates the name of an object and the class to which the object belongs to. In this declaration, we are declaring the name myWindow, which we will use to refer to a JFrame object. Any valid identifier that is not reserved for other uses can be used as an object name. An identifier is a sequence of letters, digits, and the dollar sign with the first one being a letter. We use an identifier to name a class, object, method, and others. No spaces are allowed in an identifier. Remember that upper- and lowercase letters are distinguished in Java. Account customer; Student jan, jim, jon; Vehicle car1, car2; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
27
Intro to OOP with Java, C. Thomas Wu
Object Creation Object Name Name of the object we are creating here. Class Name An instance of this class is created. Argument No arguments are used here. myWindow = new JFrame ( ) ; More Examples An object declaration simply declares the name (identifier), which we use to refer to an object. The declaration does not create an object. To create the actual object, we need to invoke the new operation. Make sure you understand the distinction between object declaration and object creation. customer = new Customer( ); jon = new Student(“John Java”); car1 = new Vehicle( ); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
28
Declaration vs. Creation
Intro to OOP with Java, C. Thomas Wu Declaration vs. Creation 1 Customer customer; customer = new Customer( ); 2 1. The identifier customer is declared and space is allocated in memory. 2. A Customer object is created and the identifier customer is set to refer to it. customer 1 customer 2 This shows the distinction between object declaration and creation by showing the effect of executing the two statements in memory allocation. Notice that the memory space for a Customer object does not happen until the correct new command is executed. : Customer ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
29
State-of-Memory vs. Program
Intro to OOP with Java, C. Thomas Wu State-of-Memory vs. Program customer : Customer State-of-Memory Notation customer : Customer Program Diagram Notation This shows two different dagrams showing the same information. Namely, there’s a Customer object and the name we’re using to refer to it is customer. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
30
Intro to OOP with Java, C. Thomas Wu
Name vs. Objects Customer customer; customer = new Customer( ); customer Is this code fragment valid? Yes, the name and the object itself are two different things. The same name can refer to different objects at different times while the program is running. This example shows the same name pointing to two different objects (at different times, of course). Since there is no reference to the first Customer object when the second new statement, it will eventually 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 returning of space to the system is called deallocation, and the mechanism to deallocate unused space is called garbage collection. Created with the first new. : Customer : Customer Created with the second new. Reference to the first Customer object is lost. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
31
Intro to OOP with Java, C. Thomas Wu
Sending a Message Object Name Name of the object to which we are sending a message. Method Name The name of the message we are sending. Argument The argument we are passing with the message. myWindow setVisible ( true ) ; More Examples This is the Java syntax for seding a message to an object or a class. In this example, we are sending the setVisible method to myWindow with an argument true, so the window indeed becomes visible. If we want to hide it, then we pass the argument false. The name of the message we send to an object or a class must be the same as the method’s name, so we use the phrase “calling an object’s method” and “sending a message to an object” interchangeably. account.deposit( ); student.setName(“john”); car1.startEngine( ); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
32
Intro to OOP with Java, C. Thomas Wu
Program Components A Java program is composed of comments, import statements, and class declarations. Three key elements are comments, import statements, and class declarations. Strictly speaking, you can write a Java program that does not include comments or import statements, but such program is either very trivial or not well designed. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
33
Program Component: Comment
Intro to OOP with Java, C. Thomas Wu Program Component: Comment Comment /* Chapter 2 Sample Program: Displaying a Window File: Ch2Sample2.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); } A comment is any sequence of text that begins with the marker /* and terminates with another marker */. Although not required to run the program, comments are indispensable in writing easy-to-understand code. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
34
Matching Comment Markers
Intro to OOP with Java, C. Thomas Wu Matching Comment Markers /* This is a comment on one line */ /* Comment number 1 */ Comment number 2 This is a comment Error: No matching beginning marker. These are part of the comment. The beginning and ending markers are matched in pairs; that is, every beginning marker must have a matching ending marker. A beginning marker is matched with the next ending marker that appears. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
35
Three Types of Comments
Intro to OOP with Java, C. Thomas Wu Three Types of Comments /* This is a comment with three lines of text. */ Multiline Comment Single line Comments // This is a comment // This is another comment // This is a third comment /** * This class provides basic clock functions. In addition * to reading the current time and today’s date, you can * use this class for stopwatch functions. */ javadoc Comments The sample comments shown in previous slides are called multiline comments. There are two additional types of comments used in Java. The second type of comment is called a single-line comment. A single-line comment starts with double slashes //. Any text between the double-slash marker and the end of a line is a comment. The third type of comment is called a javadoc comment. It is a specialized comment that can appear before the class declaration and other program elements yet to be described in the book. Javadoc comments begin with the /** marker and end with the */ marker. We won’t worry about javadoc comments now. At this point, you are only required just to be aware of it. If you are curious about javadoc comments, you can find information on javadoc and samle Web documentation pages that are generated from javadoc comments at techdocs/api/ ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
36
Intro to OOP with Java, C. Thomas Wu
Import Statement /* Chapter 2 Sample Program: Displaying a Window File: Ch2Sample2.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); } Import Statement The import statement allows the program to use classes and their instances defined in the designated package. We develop object-oriented programs by using predefined classes whenever possible and defining our own classes when no suitable predefined classes are available. In Java, classes are grouped into packages. The Java compiler comes with over 2000 standard classes organized into several hundred packages. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
37
Import Statement Syntax and Semantics
Intro to OOP with Java, C. Thomas Wu Import Statement Syntax and Semantics Package Name Name of the package that contains the classes we want to use. Class Name The name of the class we want to import. Use asterisks to import all classes. <package name> <class name> ; e.g dorm Resident; More Examples To use the Resident class in the dorm package, we write dorm.Resident; which we read as “dorm dot Resident.” This notation is called dot notation. Notice that the import statement is terminated by a semicolon. A package can include subpackages, forming a hierarchy of packages. The notation javax.swing.JFrame means the JFrame class is located in the package swing, which itself is contained in the top-level javax package. If you need to import more than one class from the same package, then instead of using an import statement for every class, you can import them all using asterisk notation: <package name> . * ; For example, when we write import java.util.*; then we are importing all class from the java.util package. import javax.swing.JFrame; import java.util.*; import com.drcaffeine.simplegui.*; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
38
Intro to OOP with Java, C. Thomas Wu
Class Declaration /* Chapter 2 Sample Program: Displaying a Window File: Ch2Sample2.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); } Class Declaration A Java program is composed of one or more classes, some of them are predefined classes, while others are defined by ourselves. In this sample program, there are two classes—JFrame and Ch2Sample1. The JFrame class is from the java.util package and the Ch2Sample1 class is the class we define ourselves. The word class is a reserved word used to mark the beginning of a class declaration. We can use any valid identifier to name the class. One of the classes in a program must be designated as the main class. The main class of the sample program is Ch2Sample1. For now, we only learn how to define the main class. Later in the course, we’ll learn how to define other non-main classes. The main class must include a method called main, because when a Java program is executed, the main method of a main class is executed first. In other words, it is the entry point of program execution. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
39
Intro to OOP with Java, C. Thomas Wu
Method Declaration /* Chapter 2 Sample Program: Displaying a Window File: Ch2Sample2.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); } Method Declaration Here’s the main method of the class. We can include any valid statements in the main method, but the structure is fixed and cannot be changed. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
40
Method Declaration Elements
Intro to OOP with Java, C. Thomas Wu Method Declaration Elements Modifier Return Type Method Name Parameter public static void main( String[ ] args ){ JFrame myWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle(“My First Java Program”); myWindow.setVisible(true); } Method Body The syntax for method declaration is <modifiers> <return type> <method name> ( <parameters> ) { <method body> } where <modifiers> is a sequence of terms designating different kinds of methods, <return type> is the type of data value returned by a method, <method name> is the name of a method, <parameters> is a sequence of values passed to a method, and <method body> is a sequence of statements. We will explain the meanings of modifies, return types, and parameters in detail gradually as we progress through the course. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
41
Template for Simple Java Programs
Intro to OOP with Java, C. Thomas Wu Template for Simple Java Programs /* Chapter 2 Sample Program: Displaying a Window File: Ch2Sample2.java */ import javax.swing.*; class Ch2Sample { public static void main(String[ ] args) { JFrame myWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle(“My First Java Program”); myWindow.setVisible(true); } Comment Import Statements Class Name Comment: Use a comment to describe the program Import Statements: Include a sequence of import statements. Class Name: Give a descriptive name to the main class. Method Body: Include a sequence of instructions. Method Body ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
42
Why Use Standard Classes
Intro to OOP with Java, C. Thomas Wu Why Use Standard Classes Don’t reinvent the wheel. When there are existing objects that satisfy our needs, use them. Learning how to use standard Java classes is the first step toward mastering OOP. Before we can learn how to define our own classes, we need to learn how to use existing classes We will introduce four standard classes here: JOptionPane String Date SimpleDateFormat. Java comes with over 2000 standard classes. Developing complex Java programs involves defining our own classes and using existing standard classes. Whenever possible, we should use existing classes and avoid reinventing the wheel. Also, being able to use existing classes is a necessary foundation for us to learn how define our own classes. In this lesson, we will introduce four standard classes. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
43
Intro to OOP with Java, C. Thomas Wu
JOptionPane Using showMessageDialog of the JOptionPane class is a simple way to display a result of a computation to the user. JOptionPane.showMessageDialog(null, “I Love Java”); JOptionPane provides a convenient method for displaying shot messages. In this example, we are displaying a message I Love Java. The dialog with the specified message appears on the center of the screen. The argument null indicates that there is no containing frame. This indication results in a dialog appearing at the center of the screen. If we wish to position a dialog at the center of another window, then we pass a JFrame object instead of null as in JFrame win = new JFrame( ); win.setSize(500, 300); win.setVisible(true); JOptionPane.showMessageDialog(win, “I’m at the center of another window”); This dialog will appear at the center of the screen. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
44
Displaying Multiple Lines of Text
Intro to OOP with Java, C. Thomas Wu Displaying Multiple Lines of Text We can display multiple lines of text by separating lines with a new line marker \n. JOptionPane.showMessageDialog(null, “one\ntwo\nthree”); We can only pass a single line text to the showMessageDialog method, but it is possible to display it as multiple lines of text. The key is to embed a nonprintable new line marker \n. Notice that in the actual display, the new line markers are not shown. This new line and other nonprintable markers are called control characters because they are not for display but for controlling the test is displayed. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
45
Intro to OOP with Java, C. Thomas Wu
String The textual values passed to the showMessageDialog method are instances of the String class. A sequence of characters separated by double quotes is a String constant. There are close to 50 methods defined in the String class. We will introduce three of them here: substring, length, and indexOf. We will also introduce a string operation called concatenation. String manipulation is so fundamental to computer programs, it is critical to master the String class. We begin our study of the String class with its three frequently used methods and one string operation called concatenation. This operation puts two strings together to form a new string. We will learn more String methods as we progress through the course. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
46
Intro to OOP with Java, C. Thomas Wu
String is an Object 1 String name; name = new String(“Jon Java”); 2 1. The identifier name is declared and space is allocated in memory. 2. A String object is created and the identifier name is set to refer to it. name name 1 2 It is very important to remember that a string is full-fledged object in Java. As such, we use the new operator to create an instance as this example shows. Remember the distinction between the name of an object and the object itself. For the String class only, we can designate a new string without using new as in String name = “Ms. Latte”; : String Jon Java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
47
Intro to OOP with Java, C. Thomas Wu
String Indexing A string is viewed as an indexed sequence of characters with the first character at index position 0. This fact will be the key in understanding how the three String methods work. The position, or index, of the first character is 0. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
48
Definition: substring
Intro to OOP with Java, C. Thomas Wu Definition: substring Assume str is a String object and properly initialized to a string. str.substring( i, j ) will return a new string by extracting characters of str from position i to j-1 where 0 i length of str, 0 j length of str, and i j. If str is “programming” , then str.substring(3, 7) will create a new string whose value is “gram” because g is at position 3 and m is at position 6. The original string str remains unchanged. Let’s study how the substring method works. You pass two arguments i and j to this method. The first argument is the beginning index and the second argument is the ending index. The method returns a new string that is a substring of str extracting characters from position i to j-1. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
49
Intro to OOP with Java, C. Thomas Wu
Examples: substring String text = “Espresso”; text.substring(6,8) text.substring(0,8) text.substring(1,5) text.substring(3,3) text.substring(4,2) “so” “Espresso” “spre” Here are some examples of the substring method. Notice the last example is an error. The first argument must be the same or smaller than the second parameter. Also, notice that if the first and the second arguments are the same, then the new string created is an empty string. “” error ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
50
Intro to OOP with Java, C. Thomas Wu
Definition: length Assume str is a String object and properly initialized to a string. str.length( ) will return the number of characters in str. If str is “programming” , then str.length( ) will return 11 because there are 11 characters in it. The original string str remains unchanged. The length method is very straightforward. It returns the number of characters in the string. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
51
Intro to OOP with Java, C. Thomas Wu
Examples: length String str1, str2, str3, str4; str1 = “Hello” ; str2 = “Java” ; str3 = “” ; //empty string str4 = “ “ ; //one space str1.length( ) str2.length( ) str3.length( ) str4.length( ) 5 4 Here are some examples of the length method. Notice asking the length of an empty string is not an error. The value returned is 0. If the name does not refer to a real String object, however, it is an error, of course. For example, String str; str.length( ); will result in an error (specifically NullPointerException). 1 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
52
Intro to OOP with Java, C. Thomas Wu
Definition: indexOf Assume str and substr are String objects and properly initialized. str.indexOf( substr ) will return the first position substr occurs in str. If str is “programming” and substr is “gram” , then str.indexOf(substr ) will return 3 because the position of the first character of substr in str is 3. If substr does not occur in str, then –1 is returned. The search is case-sensitive. The indexOf method returns the position of the first character of a search string (substring) in a given string. If there are more than one occurrence of the same substing in a string, the position of the first occurrence is returned. If no match is found, then –1 is returned. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
53
Intro to OOP with Java, C. Thomas Wu
Examples: indexOf String str; str = “I Love Java and Java loves me.” ; 3 7 21 str.indexOf( “J” ) str2.indexOf( “love” ) str3. indexOf( “ove” ) str4. indexOf( “Me” ) 7 21 Here are some examples of the indexOf method. When there are more than one match, then the position of the first match is returned as the first example shows. If there’s no match, then –1 is returned. The search is case-sensitive so the last example returns –1. 3 -1 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
54
Definition: concatenation
Intro to OOP with Java, C. Thomas Wu Definition: concatenation Assume str1 and str2 are String objects and properly initialized. str1 + str2 will return a new string that is a concatenation of two strings. If str1 is “pro” and str2 is “gram” , then str1 + str2 will return “program”. Notice that this is an operator and not a method of the String class. The strings str1 and str2 remains the same. The concatenation operator forms a new string by putting two strings together. The original two strings remain the same. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
55
Examples: concatenation
Intro to OOP with Java, C. Thomas Wu Examples: concatenation String str1, str2; str1 = “Jon” ; str2 = “Java” ; str1 + str2 str1 + “ “ + str2 str2 + “, “ + str1 “Are you “ + str1 + “?” “JonJava” “Jon Java” Here are some examples of the concatenation operator. “Java, Jon” “Are you Jon?” ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
56
Intro to OOP with Java, C. Thomas Wu
Date The Date class from the java.util package is used to represent a date. When a Date object is created, it is set to today (the current date set in the computer) The class has toString method that converts the internal format to a string. Date today; today = new Date( ); today.toString( ); Date manipulation is a very common task in computer programs. A Date object actually keeps track of time also. We will learn more about this class later in the course. “Fri Oct 31 10:05:18 PST 2003” ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
57
Intro to OOP with Java, C. Thomas Wu
SimpleDateFormat The SimpleDateFormat class allows the Date information to be displayed with various format. Table 2.1 page 64 shows the formatting options. Date today = new Date( ); SimpleDateFormat sdf1, sdf2; sdf1 = new SimpleDateFormat( “MM/dd/yy” ); sdf2 = new SimpleDateFormat( “MMMM dd, yyyy” ); sdf1.format(today); sdf2.format(today); We use a SimpleDateFormat to display the Date information in the format we like. Follow this example and you can experiment with the different formatting options listed in Table 2.1 on page 64 of the textbook. “10/31/03” “October 31, 2003” ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
58
Intro to OOP with Java, C. Thomas Wu
JOptionPane for Input Using showInputDialog of the JOptionPane class is a simple way to input a string. String name; name = JOptionPane.showInputDialog (null, “What is your name?”); The showInputDialog method allows a program to accept a string data from the enduser. The method returns the data entered by the enduser as a String object, so we can assign it to a variable. This dialog will appear at the center of the screen ready to accept an input. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
59
Intro to OOP with Java, C. Thomas Wu
Problem Statement Problem statement: Write a program that asks for the user’s first, middle, and last names and replies with their initials. Example: input: Andrew Lloyd Weber output: ALW In this beginning course, we concentrate on three stages of the software lifecycle: design, coding, and testing. We view the problem statement as the requirement specification produced during the analysis phase of the lifecycle. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
60
Intro to OOP with Java, C. Thomas Wu
Overall Plan Identify the major tasks the program has to perform. We need to know what to develop before we develop! Tasks: Get the user’s first, middle, and last names Extract the initials and create the monogram Output the monogram It may not be obvious for a simple program like this one, but identifying and recording the program tasks are indispensable because the development steps are based on the identified tasks. If the tasks are not identified, we can’t develop them. Notice this program follows the universal pattern of computer programs, namely, the pattern of input, computation, and output. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
61
Intro to OOP with Java, C. Thomas Wu
Development Steps We will develop this program in two steps: Start with the program template and add code to get input Add code to compute and display the monogram In Step 1, we will use the program template for simple Java programs introduced in Lesson 2-2 as the starting point. We design and code the input routine. Once the Step 1 code is tested, we move on to Step 2 to complete the program by adding the code compute and display the monogram. When we finish the testing of the Step 2 code, we are done with the development. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
62
Intro to OOP with Java, C. Thomas Wu
Step 1 Design The program specification states “get the user’s name” but doesn’t say how. We will consider “how” in the Step 1 design We will use JOptionPane for input Input Style Choice #1 Input first, middle, and last names separately Input Style Choice #2 Input the full name at once We choose Style #2 because it is easier and quicker for the user to enter the information The specification tells “what” must be done (get the user’s input), but not “how” to do it. In the design stage, we will determine the “how.” First, we will use JOptionPane for input. This is no brainer because it is the only way we know how to input data at this point in the course. Second, how exactly should we input the user’s name? We can input it in three separate pieces—first, middle, and last names—by calling the showInputDialog method three times. Or, we can input the full name at once by calling the showInputDialog method once. We prefer the second style because it is much quicker for the user to enter his/her full name at once. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
63
Intro to OOP with Java, C. Thomas Wu
Step 1 Code /* Chapter 2 Sample Program: Displays the Monogram File: Step1/Ch2Monogram.java */ import javax.swing.*; class Ch2Monogram { public static void main (String[ ] args) { String name; name = JOptionPane.showInputDialog(null, "Enter your full name (first, middle, last):“); JOptionPane.showMessageDialog(null, name); } Notice the use of showMessageDialog to output the input data. This displaying of input data is called echo printing. This is a technique we use to verify the correctness of input data. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
64
Intro to OOP with Java, C. Thomas Wu
Step 1 Test In the testing phase, we run the program and verify that we can enter the name the name we enter is displayed correctly For the Step 1 test, we run the program and confirm the input routine is working correctly. Even for a simple program like this, incremental testing is important. By confirming the correctness of Step 1 Code, we can focus on the computation task in Step 2. Had we omitted this test and moved to Step 2, we would not be able to tell whether the input routine or the computation is not functioning correctly when there’s an error. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
65
Intro to OOP with Java, C. Thomas Wu
Step 2 Design Our programming skills are limited, so we will make the following assumptions: input string contains first, middle, and last names first, middle, and last names are separated by single blank spaces Example John Quincy Adams (okay) John Kennedy (not okay) Harrison, William Henry (not okay) Because our programming skills are still limited, we need to make some assumptions on input so we can carry out the required task. To simplify the processing task, we will impose these two restrictions on the input values. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
66
Intro to OOP with Java, C. Thomas Wu
Step 2 Design (cont’d) Given the valid input, we can compute the monogram by breaking the input name into first, middle, and last extracting the first character from them concatenating three first characters “Aaron Ben Cosner” “Aaron” “Ben Cosner” “Ben” “Cosner” “ABC” Given the input string that follows the designated format, we can use the sequence of the substring method to extract first, middle, and last names. Once the the name is separated into three pieces, we can then pull out and concatenate their first characters. We will be using all three string methods and string concatenation operator to achieve the task. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
67
Intro to OOP with Java, C. Thomas Wu
Step 2 Code /* Chapter 2 Sample Program: Displays the Monogram File: Step 2/Ch2MonogramStep2.java */ import javax.swing.*; class Ch2Monogram { public static void main (String[ ] args) { String name, first, middle, last, space, monogram; space = " “; //Input the full name name = JOptionPane.showInputDialog(null, "Enter your full name (first, middle, last):“ ); Notice the use of variable space to make the code more readable. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
68
Intro to OOP with Java, C. Thomas Wu
Step 2 Code (cont’d) //Extract first, middle, and last names first = name.substring(0, name.indexOf(space)); name = name.substring(name.indexOf(space)+1, name.length()); middle = name.substring(0, name.indexOf(space)); last = name.substring(name.indexOf(space)+1, name.length()); //Compute the monogram monogram = first.substring(0, 1) + middle.substring(0, 1) + last.substring(0,1); //Output the result JOptionPane.showMessageDialog(null, "Your monogram is " + monogram); } Make sure you follow the logic of breaking one input string to three substrings (first, middle, last) by applying a sequence of substring method in conjunction with indexOf and length methods. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
69
Intro to OOP with Java, C. Thomas Wu
Step 2 Test In the testing phase, we run the program and verify that, for all valid input values, correct monograms are displayed. We run the program numerous times. Seeing one correct answer is not enough. We have to try out many different types of (valid) input values. We run the final test by executing the program numerous times and trying out many different input values. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
70
Intro to OOP with Java, C. Thomas Wu
Program Review The work of a programmer is not done yet. Once the working program is developed, we perform a critical review and see if there are any missing features or possible improvements One suggestion Improve the initial prompt so the user knows the valid input format requires single spaces between the first, middle, and last names Programmers must be always diligent in actively looking for features that may be missing or features that can use improvements. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
71
Intro to OOP with Java, C. Thomas Wu Numerical Data
Chapter 3 Numerical Data ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
72
Intro to OOP with Java, C. Thomas Wu
Objectives After you have read and studied this chapter, you should be able to Select proper types for numerical data. Write arithmetic expressions in Java. Evaluate arithmetic expressions using the precedence rules. Describe how the memory allocation works for objects and primitive data values. Write mathematical expressions, using methods in the Math class. Use the GregorianCalendar class in manipulating date information such as year, month, and day. Use the DecimalFormat class to format numerical data Convert input string values to numerical data Perform input and output by using System.in and System.out ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
73
Intro to OOP with Java, C. Thomas Wu
Manipulating Numbers In Java, to add two numbers x and y, we write x + y But before the actual addition of the two numbers takes place, we must declare their data type. If x and y are integers, we write int x, y; or int x; int y; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
74
Intro to OOP with Java, C. Thomas Wu
Variables When the declaration is made, memory space is allocated to store the values of x and y. x and y are called variables. A variable has three properties: A memory location to store the value, The type of data stored in the memory location, and The name used to refer to the memory location. Sample variable declarations: int x; int v, w, y; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
75
Intro to OOP with Java, C. Thomas Wu
Numerical Data Types There are six numerical data types: byte, short, int, long, float, and double. Sample variable declarations: int i, j, k; float numberOne, numberTwo; long bigInteger; double bigNumber; At the time a variable is declared, it also can be initialized. For example, we may initialize the integer variables count and height to 10 and 34 as int count = 10, height = 34; In the same way that you can initialize variables for numbers, you can initialize with objects. For example, instead of JFrame myWindow; myWindow = new JFrame(); we can write more succintly as JFrame myWindow = new JFrame(); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
76
Intro to OOP with Java, C. Thomas Wu
Data Type Precisions The six data types differ in the precision of values they can store in memory. This is for information only. You do not have to memorize this table. Just get some general idea on the range of values that can be represented by the six numerical data types. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
77
Assignment Statements
Intro to OOP with Java, C. Thomas Wu Assignment Statements We assign a value to a variable using an assignment statements. The syntax is <variable> = <expression> ; Examples: sum = firstNumber + secondNumber; avg = (one + two + three) / 3.0; To assign a value to a variable, we use an assignment statement. A single variable appears to the left of equal symbol and an expression appears to the right. Assignment statements are terminated by a semicolon. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
78
Intro to OOP with Java, C. Thomas Wu
Arithmetic Operators The following table summarizes the arithmetic operators available in Java. This table lists five numerical operators. Unlike pure mathematics, the division whose two operands are integers will result in an integer. This is an integer division where the fractional part is truncated. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
79
Arithmetic Expression
Intro to OOP with Java, C. Thomas Wu Arithmetic Expression How does the expression x + 3 * y get evaluated? Answer: x is added to 3*y. We determine the order of evaluation by following the precedence rules. A higher precedence operator is evaluated before the lower one. If two operators are the same precedence, then they are evaluated left to right for most operators. You need to write the expression as (x + 3) * y if you want to multiply y to the sum of x and 3. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
80
Intro to OOP with Java, C. Thomas Wu
Precedence Rules If you want to alter the precedence rules, then use parentheses to dictate the order of evaluation. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
81
Intro to OOP with Java, C. Thomas Wu
Type Casting If x is a float and y is an int, what will be the data type of the following expression? x * y The answer is float. The above expression is called a mixed expression. The data types of the operands in mixed expressions are converted based on the promotion rules. The promotion rules ensure that the data type of the expression will be the same as the data type of an operand whose type has the highest precision. When an arithmetic expression consists of variables and constants of the same data type, then the result of the expression will be that data type also. When the data types of variables and constants in an arithmetic expression are of different data types, then a casting conversion will take place. A casting conversion, or type casting, is a process that converts a value of one data type to another data type. Two types of casting conversions in Java are implicit and explicit. An implicit conversion called numeric promotion is applied to the operands of an arithmetic operator. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
82
Intro to OOP with Java, C. Thomas Wu
Explicit Type Casting Instead of relying on the promotion rules, we can make an explicit type cast by prefixing the operand with the data type using the following syntax: ( <data type> ) <expression> Example (float) x / 3 (int) (x / y * 3.0) Type case x to float and then divide it by 3. We can always use the explicit type casting to change the data type of a value. Type cast the result of the expression x / y * 3.0 to int. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
83
Intro to OOP with Java, C. Thomas Wu
Implicit Type Casting Consider the following expression: double x = 3 + 5; The result of is of type int. However, since the variable x is double, the value 8 (type int) is promoted to 8.0 (type double) before being assigned to x. Notice that it is a promotion. Demotion is not allowed. int x = 3.5; When the explicit type casting is not included in the expression, then the implicit type casting is applied when a value is assigned to a variable. This implicit assignment type casting will promote the value of the expression to a higher precision to match the data type of the variable. Demotion on precision will not occur implicit. You need the explicit type casting for demotion, for example, int x = (int) 4.5 / 2.2; A higher precision value cannot be assigned to a lower precision variable. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
84
Intro to OOP with Java, C. Thomas Wu
Constants We can change the value of a variable. If we want the value to remain the same, we use a constant. final double PI = ; final int MONTH_IN_YEAR = 12; final short FARADAY_CONSTANT = 23060; These are constants, also called named constant. The reserved word final is used to declare constants. These are called literal constant. The data type of literal constant 3.45 is double and the data type of literal constant 398 is int. To designate other data types for literal constants, we suffix the literal constants with the designators F or f for float and L or l for long. For example, 2.45f 1453L Java convention uses all capitalized letters for constants. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
85
Primitive vs. Reference
Intro to OOP with Java, C. Thomas Wu Primitive vs. Reference Numerical data are called primitive data types. Objects are called reference data types, because the contents are addresses that refer to memory locations where the objects are actually stored. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
86
Primitive Data Declaration and Assignments
Intro to OOP with Java, C. Thomas Wu Primitive Data Declaration and Assignments firstNumber secondNumber A. Variables are allocated in memory. B. Values are assigned to variables. 234 87 A int firstNumber, secondNumber; firstNumber = 234; secondNumber = 87; B Code State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
87
Assigning Numerical Data
Intro to OOP with Java, C. Thomas Wu Assigning Numerical Data number A. The variable is allocated in memory. B. The value 237 is assigned to number. 237 C. The value 35 overwrites the previous value 237. 35 int number; number = 237; A B C number = 35; Notice how the old value is over written by the new value. Code State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
88
Intro to OOP with Java, C. Thomas Wu
Assigning Objects customer A. The variable is allocated in memory. B. The reference to the new object is assigned to customer. Customer C. The reference to another object overwrites the reference in customer. Customer A B Customer customer; customer = new Customer( ); C If the variable refers to an object, then the assignment and the corresponding effect to the memory allocation are different. Notice the content of the variable is not the value itself, as is the case with primitive data, but the address of, or reference to, the memory location where the object data is stored. We use arrows to indicate this memory reference. Code State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
89
Having Two References to a Single Object
Intro to OOP with Java, C. Thomas Wu Having Two References to a Single Object A. Variables are allocated in memory. clemens twain B. The reference to the new object is assigned to clemens. Customer C. The reference in clemens is assigned to customer. A B Customer clemens, twain, clemens = new Customer( ); twain = clemens; C This sample code shows the effect of two reference variables pointing to the same object, which is perfectly legal. This slide highlights the critical fact that the name (variable) and object are two distinct and separate entities. It is no problem to have multiple variables referring to a single object, much as a single person can be referred by many different names. Code State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
90
Intro to OOP with Java, C. Thomas Wu
Type Mismatch Suppose we want to input an age. Will this work? int age; age = JOptionPane.showInputDialog( null, “Enter your age”); You assign a value of one numerical data type to a variable of another numerical data type (directly or via some form of type casting). But you cannot assign a number to a String variable or vice versa. No. String value cannot be assigned directly to an int variable. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
91
Intro to OOP with Java, C. Thomas Wu
Type Conversion Wrapper classes are used to perform necessary type conversions, such as converting a String object to a numerical value. int age; String inputStr; inputStr = JOptionPane.showInputDialog( null, “Enter your age”); age = Integer.parseInt(inputStr); The Integer class includes a class method named parseInt that accepts a String argument and returns an integer. Not all string values can be converted. A string such as “14” can be converted to a numerical value of 14, but a string such as “ABC23” cannot be converted to an integer. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
92
Other Conversion Methods
Intro to OOP with Java, C. Thomas Wu Other Conversion Methods In addition to the conversion from a String to an int, we have other useful wrapper classes. Most commonly used converters are parseInt and parseDouble. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
93
Intro to OOP with Java, C. Thomas Wu
Sample Code Fragment //code fragment to input radius and output //area and circumference double radius, area, circumference; radiusStr = JOptionPane.showInputDialog( null, "Enter radius: " ); radius = Double.parseDouble(radiusStr); //compute area and circumference area = PI * radius * radius; circumference = 2.0 * PI * radius; JOptionPane.showMessageDialog(null, "Given Radius: " + radius + "\n" + "Area: " + area + "\n" + "Circumference: " + circumference); This code fragment accepts a radius as its input and outputs the circle’s area and circumference. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
94
Intro to OOP with Java, C. Thomas Wu
Overloaded Operator + The plus operator + can mean two different operations, depending on the context. <val1> + <val2> is an addition if both are numbers. If either one of them is a String, the it is a concatenation. Evaluation goes from left to right. output = “test” ; output = “test”; Notice the long expression in the previous slide "Given Radius: " + radius + "\n" + "Area: " + area + "\n" + "Circumference: " + circumference with string literal constants and double variables. The plus symbol is an overloaded operator. In this expression, they are string concatenations. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
95
The DecimalFormat Class
Intro to OOP with Java, C. Thomas Wu The DecimalFormat Class Use a DecimalFormat object to format the numerical output. double num = ; DecimalFormat df = new DecimalFormat(“0.000”); //three decimal places System.out.print(num); System.out.print(df.format(num)); When you print out a double value, you may get eight or nine decimal places. To limit the number of decimal places to display, you can use the DecimalFormat class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
96
Intro to OOP with Java, C. Thomas Wu
3.5 Standard Output The showMessageDialog method is intended for displaying short one-line messages, not for a general-purpose output mechanism. Using System.out, we can output multiple lines of text to the standard output window. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
97
Standard Output Window
Intro to OOP with Java, C. Thomas Wu Standard Output Window A sample standard output window for displaying multiple lines of text. This is a typical standard output window. Exactly how the standard output window is displayed depends on the Java tools you use. For some tools, the standard output window appears as a portion of the development environment instead of a separate window as shown here. The exact style of standard output window depends on the Java tool you use. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
98
Intro to OOP with Java, C. Thomas Wu
The print Method We use the print method to output a value to the standard output window. The print method will continue printing from the end of the currently displayed output. Example System.out.print( “Hello, Dr. Caffeine.” ); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
99
Intro to OOP with Java, C. Thomas Wu
The println Method We use println instead of print to skip a line. int x = 123, y = x + x; System.out.println( "Hello, Dr. Caffeine.“ ); System.out.print( " x = “ ); System.out.println( x ); System.out.print( " x + x = “ ); System.out.println( y ); System.out.println( " THE END“ ); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
100
Intro to OOP with Java, C. Thomas Wu
Standard Input The technique of using System.in to input data is called standard input. We can only input a single byte using System.in directly. To input primitive data values, we use the Scanner class (from Java 5.0). Scanner scanner; scanner = Scanner.create(System.in); int num = scanner.nextInt(); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
101
Common Scanner Methods:
Intro to OOP with Java, C. Thomas Wu Common Scanner Methods: Method Example nextByte( ) byte b = scanner.nextByte( ); nextDouble( ) double d = scanner.nextDouble( ); nextFloat( ) float f = scanner.nextFloat( ); nextInt( ) int i = scanner.nextInt( ); nextLong( ) long l = scanner.nextLong( ); nextShort( ) short s = scanner.nextShort( ); next() String str = scanner.next(); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
102
Intro to OOP with Java, C. Thomas Wu
The Math class The Math class in the java.lang package contains class methods for commonly used mathematical functions. double num, x, y; x = …; y = …; num = Math.sqrt(Math.max(x, y) ); You assign a value of one numerical data type to a variable of another numerical data type (directly or via some form of type casting). But you cannot assign a number to a String variable or vice versa. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
103
Some Math Class Methods
Intro to OOP with Java, C. Thomas Wu Some Math Class Methods Method Description exp(a) Natural number e raised to the power of a. log(a) Natural logarithm (base e) of a. floor(a) The largest whole number less than or equal to a. max(a,b) The larger of a and b. pow(a,b) The number a raised to the power of b. sqrt(a) The square root of a. sin(a) The sine of a. (Note: all trigonometric functions are computed in radians) This table list some of the Math class methods. Please refer to the actual Math class documentation for full description of all class methods. Table 3.8 page 113 in the textbook contains a list of class methods defined in the Math class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
104
Computing the Height of a Pole
Intro to OOP with Java, C. Thomas Wu Computing the Height of a Pole alphaRad = Math.toRadians(alpha); betaRad = Math.toRadians(beta); height = ( distance * Math.sin(alphaRad) * Math.sin(betaRad) ) / Math.sqrt( Math.sin(alphaRad + betaRad) * Math.sin(alphaRad - betaRad) ); Here’s one sample showing how the given mathematical formula is written using the Math class methods. The formula computes the height of a statue given the distance between the two measuring points A and B. ©The McGraw-Hill Companies, Inc.
105
The GregorianCalendar Class
Intro to OOP with Java, C. Thomas Wu The GregorianCalendar Class Use a GregorianCalendar object to manipulate calendar information GregorianCalendar today, independenceDay; today = new GregorianCalendar(); independenceDay = new GregorianCalendar(1776, 6, 4); //month 6 means July; 0 means January When you print out a double value, you may get eight or nine decimal places. To limit the number of decimal places to display, you can use the DecimalFormat class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
106
Retrieving Calendar Information
Intro to OOP with Java, C. Thomas Wu Retrieving Calendar Information This table shows the class constants for retrieving different pieces of calendar information from Date. We can use these class constants to retrieve different pieces of calendar information. We use the get method and pass the desired constant as an argument. The next slide shows a sample use. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
107
Sample Calendar Retrieval
Intro to OOP with Java, C. Thomas Wu Sample Calendar Retrieval GregorianCalendar cal = new GregorianCalendar(); //Assume today is Nov 9, 2003 System.out.print(“Today is ” + (cal.get(Calendar.MONTH)+1) + “/” + cal.get(Calendar.DATE) + “/” + cal.get(Calendar.YEAR)); Today is 11/9/2003 Output Here’s a sample code. Notice that we need to add 1 to the returned Month, because internally, January is represented as 0, February as 1, and so forth. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
108
Intro to OOP with Java, C. Thomas Wu
Problem Statement Problem statement: Write a loan calculator program that computes both monthly and total payments for a given loan amount, annual interest rate, and loan period. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
109
Intro to OOP with Java, C. Thomas Wu
Overall Plan Tasks: Get three input values: loanAmount, interestRate, and loanPeriod. Compute the monthly and total payments. Output the results. As a part of the overall plan, we begin by identifying the main tasks for the program. Notice this program follows the universal pattern of computer programs, namely, the pattern of input, computation, and output. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
110
Intro to OOP with Java, C. Thomas Wu
Required Classes Given the tasks identified in the overall program flow, we need to find suitable classes and objects to carry out the tasks. For this program, we will use the Math class for computation, JOptionPane for input, and System.out for output. The LoanCalculator class is the main class of the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
111
Intro to OOP with Java, C. Thomas Wu
Development Steps We will develop this program in four steps: Start with code to accept three input values. Add code to output the results. Add code to compute the monthly and total payments. Update or modify code and tie up any loose ends. This order of development steps is quite common. Notice that we are implementing the code for output before implementing the code for computation. Since we need some kind of output routine to test the correct implementation of the computation code, we will implement the actual code for output first, so when we implement the code for computation we can use the actual output routine for testing the computation code. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
112
Intro to OOP with Java, C. Thomas Wu
Step 1 Design Call the showInputDialog method to accept three input values: loan amount, annual interest rate, loan period. Data types are Input Format Data Type loan amount dollars and cents double annual interest rate in percent (e.g.,12.5) loan period in years int We will use JOptionPane to input three values. What would be the data types for these three input values? And are these values entered by the users? For example, how should the user enter the loan period? Number of years? Number of months? We need to decide the format that is most natural to the users. After the input format, we need to decide the data types. Are the input values real numbers or integers? ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
113
Intro to OOP with Java, C. Thomas Wu
Step 1 Code Directory: Chapter3/Step1 Source File: Ch3LoanCalculator.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Please open your Java IDE and run the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
114
Intro to OOP with Java, C. Thomas Wu
Step 1 Test In the testing phase, we run the program multiple times and verify that we can enter three input values we see the entered values echo-printed correctly on the standard output window ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
115
Intro to OOP with Java, C. Thomas Wu
Step 2 Design We will consider the display format for out. Two possibilities are (among many others) When designing an output routine, we need to decide what to display and how to display them, in other words, the layout of the display. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
116
Intro to OOP with Java, C. Thomas Wu
Step 2 Code Directory: Chapter3/Step2 Source File: Ch3LoanCalculator.java Run the program and check the output display format. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
117
Intro to OOP with Java, C. Thomas Wu
Step 2 Test We run the program numerous times with different types of input values and check the output display format. Adjust the formatting as appropriate We run the the program numerous times and trying out many different input values. We cannot overemphasize the importance of trying out different input values. The output format that may look nice may look horrible for a different set of input values. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
118
Intro to OOP with Java, C. Thomas Wu
Step 3 Design The formula to compute the geometric progression is the one we can use to compute the monthly payment. The formula requires the loan period in months and interest rate as monthly interest rate. So we must convert the annual interest rate (input value) to a monthly interest rate (per the formula), and the loan period to the number of monthly payments. Notice the difference in input values and the values required to plug into the formula. For example, we input annual interest rate, but we need monthly interest rate for the formula to compute the monthly payment. It is not appropriate to change the input routine to accept the monthly interest rate. It is easier for the programmer because we need no conversion, but we are writing the program for the sake of users, not for the convenience of programmers. We should always accept the input values that are natural to the users. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
119
Intro to OOP with Java, C. Thomas Wu
Step 3 Code Directory: Chapter3/Step3 Source File: Ch3LoanCalculator.java Run the program and check the computation. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
120
Intro to OOP with Java, C. Thomas Wu
Step 3 Test We run the program numerous times with different types of input values and check the results. We run the final test by executing the program numerous times and enter different input values. The input values in the given table are only suggestions. They are not a complete list of test input values by any mean. You need to try out many other different input values. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
121
Intro to OOP with Java, C. Thomas Wu
Step 4: Finalize We will add a program description We will format the monthly and total payments to two decimal places using DecimalFormat. Directory: Chapter3/Step4 Source File: Ch3LoanCalculator.java Programmers must be always diligent in actively looking for features that may be missing or features that can use improvements. We notice two features that are must-haves for a good program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
122
Intro to OOP with Java, C. Thomas Wu Defining Your Own Classes Part 1
Chapter 4 Defining Your Own Classes Part 1 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
123
Intro to OOP with Java, C. Thomas Wu
Objectives After you have read and studied this chapter, you should be able to Define a class with multiple methods and data members Differentiate the local and instance variables Define and use value-returning methods Distinguish private and public methods Distinguish private and public data members Pass both primitive data and objects to a method ©The McGraw-Hill Companies, Inc.
124
Why Programmer-Defined Classes
Intro to OOP with Java, C. Thomas Wu Why Programmer-Defined Classes Using just the String, GregorianCalendar, JFrame and other standard classes will not meet all of our needs. We need to be able to define our own classes customized for our applications. Learning how to define our own classes is the first step toward mastering the skills necessary in building large programs. Classes we define ourselves are called programmer-defined classes. The sample application programs we have written so far included only one class, the main class of the program. And the main class contained only one method, the main method. When we review the sample programs developed so far, we note two key characteristics: The programs included only one class, the main class of the program. The main class contained only one method, the main method. From this main method, we used objects and classes from the standard packages such as javax.swing and java.util . Such organization works only for small programs. In order to manage complexity of large programs, it is best to define instantiable classes. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
125
First Example: Using the Bicycle Class
Intro to OOP with Java, C. Thomas Wu First Example: Using the Bicycle Class class BicycleRegistration { public static void main(String[] args) { Bicycle bike1, bike2; String owner1, owner2; bike1 = new Bicycle( ); //Create and assign values to bike1 bike1.setOwnerName("Adam Smith"); bike2 = new Bicycle( ); //Create and assign values to bike2 bike2.setOwnerName("Ben Jones"); owner1 = bike1.getOwnerName( ); //Output the information owner2 = bike2.getOwnerName( ); System.out.println(owner1 + " owns a bicycle."); System.out.println(owner2 + " also owns a bicycle."); } This sample program shows the main class BicycleRegistration is using the Bicycle class. This Bicycle class is not part of any standard packages. It is something we (or other programmers) have to define ourselves. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
126
The Definition of the Bicycle Class
Intro to OOP with Java, C. Thomas Wu The Definition of the Bicycle Class class Bicycle { // Data Member private String ownerName; //Constructor: Initialzes the data member public void Bicycle( ) { ownerName = "Unknown"; } //Returns the name of this bicycle's owner public String getOwnerName( ) { return ownerName; //Assigns the name of this bicycle's owner public void setOwnerName(String name) { ownerName = name; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
127
Intro to OOP with Java, C. Thomas Wu
Multiple Instances Once the Bicycle class is defined, we can create multiple instances. Bicycle bike1, bike2; bike1 = new Bicycle( ); bike1.setOwnerName("Adam Smith"); bike2 = new Bicycle( ); bike2.setOwnerName("Ben Jones"); Once a class is defined, we can create multiple instances of the class as shown by this example. Notice how all the instances have their own copy of data members. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
128
The Program Structure and Source Files
Intro to OOP with Java, C. Thomas Wu The Program Structure and Source Files BicycleRegistration Bicycle BicycleRegistration.java Bicycle.java There are two source files. Each class definition is stored in a separate file. To run the program: 1. javac Bicycle.java (compile) 2. javac BicycleRegistration.java (compile) 3. java BicycleRegistration (run) ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
129
Class Diagram for Bicycle
Intro to OOP with Java, C. Thomas Wu Class Diagram for Bicycle Bicycle setOwnerName(String) Bicycle( ) getOwnerName( ) Method Listing We list the name and the data type of an argument passed to the method. We introduced the icon to represent a class in Chapter 2. We extend that icon to include the list of methods for the class. In listing a method, we indicate the data type of the arguments passed to the method. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
130
Template for Class Definition
Intro to OOP with Java, C. Thomas Wu Template for Class Definition class { } Import Statements Class Comment Class Name Data Members Methods (incl. Constructor) This is the template we use when creating programmer-defined classes. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
131
Data Member Declaration
Intro to OOP with Java, C. Thomas Wu Data Member Declaration <modifiers> <data type> <name> ; Modifiers Data Type Name private String ownerName ; Note: There’s only one modifier in this example. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
132
Intro to OOP with Java, C. Thomas Wu
Method Declaration <modifier> <return type> <method name> ( <parameters> ){ <statements> } Modifier Return Type Method Name Parameter public void setOwnerName ( String name ) { ownerName = name; } Statements ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
133
Intro to OOP with Java, C. Thomas Wu
Constructor A constructor is a special method that is executed when a new instance of the class is created. public <class name> ( <parameters> ){ <statements> } Modifier Class Name Parameter public Bicycle ( ) { ownerName = “Unassigned”; } Statements ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
134
Second Example: Using Bicycle and Account
Intro to OOP with Java, C. Thomas Wu Second Example: Using Bicycle and Account class SecondMain { //This sample program uses both the Bicycle and Account classes public static void main(String[] args) { Bicycle bike; Account acct; String myName = "Jon Java"; bike = new Bicycle( ); bike.setOwnerName(myName); acct = new Account( ); acct.setOwnerName(myName); acct.setInitialBalance(250.00); acct.add(25.00); acct.deduct(50); //Output some information System.out.println(bike.getOwnerName() + " owns a bicycle and"); System.out.println("has $ " + acct.getCurrentBalance() " left in the bank"); } This sample code shows a program that uses two programmer-defined classes Bicycle and Account. The same string value is passed as the name of the owner for both objects. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
135
Intro to OOP with Java, C. Thomas Wu
The Account Class class Account { private String ownerName; private double balance; public Account( ) { ownerName = "Unassigned"; balance = 0.0; } public void add(double amt) { balance = balance + amt; public void deduct(double amt) { balance = balance - amt; public double getCurrentBalance( ) { return balance; public String getOwnerName( ) { return ownerName; public void setInitialBalance (double bal) { balance = bal; } public void setOwnerName (String name) { ownerName = name; Page 1 Page 2 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
136
The Program Structure for SecondMain
Intro to OOP with Java, C. Thomas Wu The Program Structure for SecondMain Bicycle SecondMain Account SecondMain.java Bicycle.java Account.java To run the program: 1. javac Bicycle.java (compile) 2. javac Account.java (compile) 2. javac SecondMain.java (compile) 3. java SecondMain (run) Note: You only need to compile the class once. Recompile only when you made changes in the code. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
137
Arguments and Parameters
Intro to OOP with Java, C. Thomas Wu Arguments and Parameters An argument is a value we pass to a method. A parameter is a placeholder in the called method to hold the value of the passed argument. class Sample { public static void main(String[] arg) { Account acct = new Account(); . . . acct.add(400); } parameter class Account { . . . public void add(double amt) { balance = balance + amt; } argument ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
138
Matching Arguments and Parameters
Intro to OOP with Java, C. Thomas Wu Matching Arguments and Parameters The number or arguments and the parameters must be the same Arguments and parameters are paired left to right The matched pair must be assignment-compatible (e.g. you cannot pass a double argument to a int parameter) The following calls are valid int i, k, m; i = 12; k = 10; m = 14; demo.compute(3, 4, 5.5); demo.compute(i, k, m); demo.compute(m, 20, 40); The following calls are not valid demo.compute(2, 4); demo.compute(14.0, 2, 3.0); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
139
Passing Objects to a Method
Intro to OOP with Java, C. Thomas Wu Passing Objects to a Method As we can pass int and double values, we can also pass an object to a method. When we pass an object, we are actually passing the reference (name) of an object it means a duplicate of an object is NOT created in the called method ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
140
Passing a Student Object
Intro to OOP with Java, C. Thomas Wu Passing a Student Object ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
141
Intro to OOP with Java, C. Thomas Wu
Sharing an Object We pass the same Student object to card1 and card2 Since we are actually passing a reference to the same object, it results in the owner of two LibraryCard objects pointing to the same Student object ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
142
Information Hiding and Visibility Modifiers
Intro to OOP with Java, C. Thomas Wu Information Hiding and Visibility Modifiers The modifiers public and private designate the accessibility of data members and methods. If a class component (data member or method) is declared private, client classes cannot access it. If a class component is declared public, client classes can access it. Internal details of a class are declared private and hidden from the clients. This is information hiding. The visibility modifiers dictate the accessibility of class components by the clients. Anything that is considered as internal details should be declared as private and hidden from the clients. For example, exactly how a MobileRobot moves is an internal detail. All the client cares is that a mobile robot is set in motion when its method move is called. Public methods of a class determines the behavior of its instances. Internal details are implemented by private methods and private data members. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
143
Accessibility Example
Intro to OOP with Java, C. Thomas Wu Accessibility Example … Service obj = new Service(); obj.memberOne = 10; obj.memberTwo = 20; obj.doOne(); obj.doTwo(); class Service { public int memberOne; private int memberTwo; public void doOne() { … } private void doTwo() { } This is a simple example of public and private modifiers. See how the client can access the public data member and method. Client Service ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
144
Data Members Should Be private
Intro to OOP with Java, C. Thomas Wu Data Members Should Be private Data members are the implementation details of the class, so they should be invisible to the clients. Declare them private . Exception: Constants can (should) be declared public if they are meant to be used directly by the outside methods. If a data member is declared public then a client can make changes directly that can affect the internal operation adversely. Hide the component that needs to be hidden to maintain the integrity of the class. Although class constants should be declared public when direct access to them is desired, please note that once a constant is declared public, its name cannot be changed without affecting the client code that made a direct access. So it is important to derive a good name that you don’t have to come back and change it. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
145
Guideline for Visibility Modifiers
Intro to OOP with Java, C. Thomas Wu Guideline for Visibility Modifiers Guidelines in determining the visibility of data members and methods: Declare the class and instance variables private. Declare the class and instance methods private if they are used only by the other methods in the same class. Declare the class constants public if you want to make their values directly readable by the client programs. If the class constants are used for internal purposes only, then declare them private. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
146
Diagram Notation for Visibility
Intro to OOP with Java, C. Thomas Wu Diagram Notation for Visibility If we include both the private and public components, then we use the plus symbol for public and the minus symbol for private. public – plus symbol (+) private – minus symbol (-) ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
147
Intro to OOP with Java, C. Thomas Wu
Class Constants In Chapter 3, we introduced the use of constants. We illustrate the use of constants in programmer-defined service classes here. Remember, the use of constants provides a meaningful description of what the values stand for. number = UNDEFINED; is more meaningful than number = -1; provides easier program maintenance. We only need to change the value in the constant declaration instead of locating all occurrences of the same value in the program code Suppose we have a constant declaration private final static int MIN_NUM = 10; and this constant is used in 20 different places in the code. When we need to change this value to 50, we only need to change the declaration. What happens if we didn’t declare this constant? We have to hunt for all 20 occurrences of the value 10 and change them to 20. What if you missed one or two of them? The program would not work at all or produce a wrong result. Easy, just use global replace command? You have to be very careful in using global replace. What happens if there’s a value of 10 in the code, but this 10 refers to a different use (say, one set of occurrences is referring to the weight, while others referring to the age)? If you globally replaced all occurrences of 10, again your program would stop working correctly. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
148
A Sample Use of Constants
Intro to OOP with Java, C. Thomas Wu A Sample Use of Constants class Dice { private static final int MAX_NUMBER = 6; private static final int MIN_NUMBER = 1; private static final int NO_NUMBER = 0; private int number; public Dice( ) { number = NO_NUMBER; } //Rolls the dice public void roll( ) { number = (int) (Math.floor(Math.random() * (MAX_NUMBER - MIN_NUMBER + 1)) + MIN_NUMBER); //Returns the number on this dice public int getNumber( ) { return number; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
149
Intro to OOP with Java, C. Thomas Wu
Local Variables Local variables are declared within a method declaration and used for temporary services, such as storing intermediate computation results. public double convert(int num) { double result; result = Math.sqrt(num * num); return result; } local variable ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
150
Local, Parameter & Data Member
Intro to OOP with Java, C. Thomas Wu Local, Parameter & Data Member An identifier appearing inside a method can be a local variable, a parameter, or a data member. The rules are If there’s a matching local variable declaration or a parameter, then the identifier refers to the local variable or the parameter. Otherwise, if there’s a matching data member declaration, then the identifier refers to the data member. Otherwise, it is an error because there’s no matching declaration. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
151
Intro to OOP with Java, C. Thomas Wu
Sample Matching class MusicCD { private String artist; private String title; private String id; public MusicCD(String name1, String name2) { String ident; artist = name1; title = name2; ident = artist.substring(0,2) + "-" + title.substring(0,9); id = ident; } ... Here’s an example on how the matching declaration is found. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
152
Calling Methods of the Same Class
Intro to OOP with Java, C. Thomas Wu Calling Methods of the Same Class So far, we have been calling a method of another class (object). It is possible to call method of a class from another method of the same class. in this case, we simply refer to a method without dot notation ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
153
Changing Any Class to a Main Class
Intro to OOP with Java, C. Thomas Wu Changing Any Class to a Main Class Any class can be set to be a main class. All you have to do is to include the main method. class Bicycle { //definition of the class as shown before comes here //The main method that shows a sample //use of the Bicycle class public static void main(String[] args) { Bicycle myBike; myBike = new Bicycle( ); myBike.setOwnerName("Jon Java"); System.out.println(myBike.getOwnerName() + "owns a bicycle"); } When we create a program, we must designate one class as the program’s main class. The designated main class must include the main method. This requirement does not prohibit us to include the main method to other classes in the program. Any class can include the main method. As long as the one we designate as the main class includes the main method, all other classes may or may not include the main method. Being able to include the main method in any class allows to provide a sample use of the class in the class definition itself, which makes the source management easier. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
154
Intro to OOP with Java, C. Thomas Wu
Problem Statement Problem statement: Write a loan calculator program that computes both monthly and total payments for a given loan amount, annual interest rate, and loan period. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
155
Intro to OOP with Java, C. Thomas Wu
Overall Plan Tasks: Get three input values: loanAmount, interestRate, and loanPeriod. Compute the monthly and total payments. Output the results. As a part of the overall plan, we begin by identifying the main tasks for the program. Notice this program follows the universal pattern of computer programs, namely, the pattern of input, computation, and output. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
156
Intro to OOP with Java, C. Thomas Wu
Required Classes LoanCalculator JOptionPane Loan PrintStream Given the tasks identified in the overall program flow, we need to find suitable classes and objects to carry out the tasks. For this program, we will use the Math class for computation, JOptionPane for input, and System.out (PrintStream) for output as we did in Chapter 3 sample development. Unlike Chapter 3 where all tasks were carried out inside the main method, we now delegate the tasks to two classes. The first is the LoanCalculator class that controls other objects, and the second is the Loan class that represents a single loan and provides methods that pertain to payment computation. input computation output ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
157
Intro to OOP with Java, C. Thomas Wu
Development Steps We will develop this program in five steps: Start with the main class LoanCalculator. Define a temporary placeholder Loan class. Implement the input routine to accept three input values. Implement the output routine to display the results. Implement the computation routine to compute the monthly and total payments. Finalize the program. We begin with the skeleton code for the top controller class LoanCalculator and the service, or logic, class Loan. Because all of the major tasks are now handled by the LoanCalculator and Loan classes, the main method is very simply to create an instance of the LoanCalculator class and run it. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
158
Intro to OOP with Java, C. Thomas Wu
Step 1 Design The methods of the LoanCalculator class Method Visibility Purpose start public Starts the loan calcution. Calls other methods computePayment private Give three parameters, compute the monthly and total payments describeProgram Displays a short description of a program displayOutput Displays the output getInput Gets three input values We design how the main class (client) will interact with the controller class LoanCalculator. Instead of requiring the client to call the correct methods of LoanCalculator in the correct order, we will simplify the interaction by requiring the client to call just one method named start. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
159
Intro to OOP with Java, C. Thomas Wu
Step 1 Code Directory: Chapter4/Step1 Source Files: LoanCalculator.java Loan.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Please use your Java IDE to view the source files and run the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
160
Intro to OOP with Java, C. Thomas Wu
Step 1 Test In the testing phase, we run the program multiple times and verify that we get the following output inside describeProgram inside getInput inside computePayment inside displayOutput Run the program and verify that you get the same result. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
161
Intro to OOP with Java, C. Thomas Wu
Step 2 Design Design the input routines LoanCalculator will handle the user interaction of prompting and getting three input values LoanCalculator calls the setAmount, setRate and setPeriod of a Loan object. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
162
Intro to OOP with Java, C. Thomas Wu
Step 2 Code Directory: Chapter4/Step2 Source Files: LoanCalculator.java Loan.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
163
Intro to OOP with Java, C. Thomas Wu
Step 2 Test We run the program numerous times with different input values Check the correctness of input values by echo printing System.out.println("Loan Amount: $" + loan.getAmount()); System.out.println("Annual Interest Rate:" + loan.getRate() + "%"); System.out.println("Loan Period (years):" + loan.getPeriod()); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
164
Intro to OOP with Java, C. Thomas Wu
Step 3 Design We will implement the displayOutput method. We will reuse the same design we adopted in Chapter 3 sample development. The design of the output layout is the same as the one we used in Chapter 3 sample development. The only difference is the location of code for performing the output. Instead of placing them in the main method, it is now handled by the LoanCalculator class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
165
Intro to OOP with Java, C. Thomas Wu
Step 3 Code Directory: Chapter4/Step3 Source Files: LoanCalculator.java Loan.java Run the program and check the output display format. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
166
Intro to OOP with Java, C. Thomas Wu
Step 3 Test We run the program numerous times with different input values and check the output display format. Adjust the formatting as appropriate The output format that may look nice may look horrible for a different set of input values, so don’t forget to test the program with many different input values. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
167
Intro to OOP with Java, C. Thomas Wu
Step 4 Design Two methods getMonthlyPayment and getTotalPayment are defined for the Loan class We will implement them so that they work independent of each other. It is considered a poor design if the clients must call getMonthlyPayment before calling getTotalPayment. The getMonthlyPayment method sets the data member monthlyPayment. So one may think (incorrectly) that getTotalPayment can be defined as public double getTotalPayment( ) { return monthlyPayment * numberOfPayments; } This is wrong because it puts unnecessary burden on the client programmers to remember to call getMonthlyPayment first. The getTotalPayment should work correctly regardless of getMonthlyPayment being called prior to it or not. We will implement them as two independent methods without any requirements in the order of calling them. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
168
Intro to OOP with Java, C. Thomas Wu
Step 4 Code Directory: Chapter4/Step4 Source Files: LoanCalculator.java Loan.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
169
Intro to OOP with Java, C. Thomas Wu
Step 4 Test We run the program numerous times with different types of input values and check the results. We will use the same test data used in Chapter 3 sample development. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
170
Intro to OOP with Java, C. Thomas Wu
Step 5: Finalize We will implement the describeProgram method We will format the monthly and total payments to two decimal places using DecimalFormat. Directory: Chapter4/Step5 Source Files (final version): LoanCalculator.java Loan.java Make sure to test the program fully one more time after the changes/additions in this step is done. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
171
Intro to OOP with Java, C. Thomas Wu Selection Statements
Chapter 5 Selection Statements ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
172
Intro to OOP with Java, C. Thomas Wu
Objectives After you have read and studied this chapter, you should be able to Implement a selection control using if statements Implement a selection control using switch statements Write boolean expressions using relational and boolean expressions Evaluate given boolean expressions correctly Nest an if statement inside another if statement Describe how objects are compared Choose the appropriate selection control statement for a given task We will study two forms of if statements in this lesson. They are called if-then-else and if-then. Although the compiler does not care how we format the if statements, we will present the recommended style. ©The McGraw-Hill Companies, Inc.
173
Intro to OOP with Java, C. Thomas Wu
The if Statement int testScore; testScore = //get test score input if (testScore < 70) JOptionPane.showMessageDialog(null, "You did not pass" ); else "You did pass" ); This statement is executed if the testScore is less than 70. We assume there’s some kind of input routine to input test score value and assign it to ‘testScore’. This sample shows how to make a decision on the input value by using an if test. This statement is executed if the testScore is 70 or higher. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
174
Syntax for the if Statement
Intro to OOP with Java, C. Thomas Wu Syntax for the if Statement if ( <boolean expression> ) <then block> else <else block> Boolean Expression if ( testScore < ) JOptionPane.showMessageDialog(null, "You did not pass" ); else JOptionPane.showMessageDialog(null, "You did pass " ); Then Block Else Block ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
175
Intro to OOP with Java, C. Thomas Wu
Control Flow testScore < 70 ? JOptionPane. showMessageDialog (null, "You did pass"); false JOptionPane. showMessageDialog (null, "You did not pass"); true This shows how the control logic flows. When the test is true, the true block is executed. When the test is false, the else block is executed. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
176
Intro to OOP with Java, C. Thomas Wu
Relational Operators < //less than <= //less than or equal to == //equal to != //not equal to > //greater than >= //greater than or equal to testScore < 80 testScore * 2 >= 350 30 < w / (h * h) x + y != 2 * (a + b) 2 * Math.PI * radius <= The list shows six relational operators for comparing values. The result is a boolean value, i.e., either true or false. One very common error in writing programs is mixing up the assignment and equality operators. We frequently make a mistake of writing if (x = 5) ... when we actually wanted to say if (x == 5) ... ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
177
Intro to OOP with Java, C. Thomas Wu
Compound Statements Use braces if the <then> or <else> block has multiple statements. if (testScore < 70) { JOptionPane.showMessageDialog(null, "You did not pass“ ); JOptionPane.showMessageDialog(null, “Try harder next time“ ); } else JOptionPane.showMessageDialog(null, “You did pass“ ); JOptionPane.showMessageDialog(null, “Keep up the good work“ ); Then Block When there are more than one statement in the then or else block, then we put the braces as this example illustrates. Rules for writing the then and else blocks: - Left and right braces are necessary to surround the statements if the then or else block contains multiple statements. - Braces are not necessary if the then or else block contains only one statement. - A semicolon is not necessary after a right brace. Else Block ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
178
Intro to OOP with Java, C. Thomas Wu
Style Guide if ( <boolean expression> ) { … } else { Style 1 if ( <boolean expression> ) { … } else Style 2 Here are two most common format styles. In this course, we will use Style 1, mainly because this style is more common among programmers, and it follows the recommended style guide for Java. If you prefer Style 2, then go ahead and use it. Whichever style you choose, be consistent, because consistent look and feel are very important to make your code readable. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
179
Intro to OOP with Java, C. Thomas Wu
The if-then Statement if ( <boolean expression> ) <then block> Boolean Expression if ( testScore >= ) JOptionPane.showMessageDialog(null, "You are an honor student"); Then Block Here's the second form of the if statement. We call this form if-then. Notice that the if–then statement is not necessary, because we can write any if–then statement using if–then–else by including no statement in the else block. For instance, the sample if–then statement can be written as if (testScore >= 95) { messageBox.show("You are an honor student"); } else { } In this book, we use if-then statements whenever appropriate. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
180
Control Flow of if-then
Intro to OOP with Java, C. Thomas Wu Control Flow of if-then testScore >= 95? JOptionPane. showMessageDialog (null, "You are an honor student"); true false This shows how the control logic of the if-then statement flows. When the test is true, the true block is executed. When the test is false, the statement that follows this if-then statement is executed. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
181
The Nested-if Statement
Intro to OOP with Java, C. Thomas Wu The Nested-if Statement The then and else block of an if statement can contain any valid statements, including other if statements. An if statement containing another if statement is called a nested-if statement. if (testScore >= 70) { if (studentAge < 10) { System.out.println("You did a great job"); } else { System.out.println("You did pass"); //test score >= 70 } //and age >= 10 } else { //test score < 70 System.out.println("You did not pass"); } It is possible to write if tests in different ways to achieve the same result. For example, the above code can also be expressed as if (testScore >= 70 && studentAge < 10) { messageBox.show("You did a great job"); } else { //either testScore < 70 OR studentAge >= 10 if (testScore >= 70) { messageBox.show("You did pass"); } else { messageBox.show("You did not pass"); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
182
Control Flow of Nested-if Statement
Intro to OOP with Java, C. Thomas Wu Control Flow of Nested-if Statement inner if messageBox.show ("You did not pass"); false true testScore >= 70 ? studentAge < 10 ? false true messageBox.show ("You did pass"); messageBox.show ("You did a great job"); This diagram shows the control flow of the example nested-if statement. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
183
Writing a Proper if Control
Intro to OOP with Java, C. Thomas Wu Writing a Proper if Control if (num1 < 0) if (num2 < 0) if (num3 < 0) negativeCount = 3; else negativeCount = 2; negativeCount = 1; negativeCount = 0; negativeCount = 0; if (num1 < 0) negativeCount++; if (num2 < 0) if (num3 < 0) The two sample if statements illustrate how the same task can be implemented in very different ways. The task is to find out how many of the three numbers are negative. Which one is the better one? The one on the right is the way to do it. The statement negativeCount++; increments the variable by one and, therefore, is equivalent to negativeCount = negativeCount + 1; The double plus operator (++) is called the increment operator, and the double minus operator (--) is the decrement operator (which decrements the variable by one). The statement negativeCount++; increments the variable by one ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
184
Intro to OOP with Java, C. Thomas Wu
if – else if Control if (score >= 90) System.out.print("Your grade is A"); else if (score >= 80) System.out.print("Your grade is B"); else if (score >= 70) System.out.print("Your grade is C"); else if (score >= 60) System.out.print("Your grade is D"); else System.out.print("Your grade is F"); Test Score Grade 90 score A 80 score 90 B 70 score 80 C 60 score 70 D score 60 F This is the style we format the nested-if statement that has empty then blocks. We will call such nested-if statements if-else if. If we follow the general rule , the above if-else if will be written as below, but the style shown in the slide is the standard notation. if (score >= 90) System.out.print("Your grade is A"); else if (score >= 80) System.out.print("Your grade is B"); if (score >= 70) System.out.print("Your grade is C"); if (score >= 60) System.out.print("Your grade is D"); messageBox.show("Your grade is F"); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
185
Intro to OOP with Java, C. Thomas Wu
Matching else Are and different? A B if (x < y) if (x < z) System.out.print("Hello"); else System.out.print("Good bye"); A if (x < y) { if (x < z) { System.out.print("Hello"); } else { System.out.print("Good bye"); } Both and means… A B if (x < y) if (x < z) System.out.print("Hello"); else System.out.print("Good bye"); B It is important to realize that the indentation alone is not sufficient to determine the nesting of if statements. The compiler will always match the else with the nearest if as this illustration shows. If you want the else to match with the first if, then you have to write if (x < y) { if (x < z) messageBox.show("Hello"); } else messageBox.show("Good bye"); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
186
Intro to OOP with Java, C. Thomas Wu
Boolean Operators A boolean operator takes boolean values as its operands and returns a boolean value. The three boolean operators are and: && or: || not ! The result of relational comparison such as score > 80 is a boolean value. Relational comparisons can be connected by boolean operators &&, ||, or !. The sample boolean expression is true if BOTH relational comparisons are true. if (temperature >= 65 && distanceToDestination < 2) { System.out.println("Let's walk"); } else { System.out.println("Let's drive"); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
187
Semantics of Boolean Operators
Intro to OOP with Java, C. Thomas Wu Semantics of Boolean Operators Boolean operators and their meanings: P Q P && Q P || Q !P false true Here's the table that lists the semantics of three boolean operators. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
188
Intro to OOP with Java, C. Thomas Wu
De Morgan's Law De Morgan's Law allows us to rewrite boolean expressions in different ways Rule 1: !(P && Q) !P || !Q Rule 2: !(P || Q) !P && !Q !(temp >= 65 && dist < 2) !(temp >=65) || !(dist < 2) by Rule 1 (temp < 65 || dist >= 2) Following the De Morgan's Law help us rewrite a boolean expression is a more logically easier-to-follow syntax. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
189
Short-Circuit Evaluation
Intro to OOP with Java, C. Thomas Wu Short-Circuit Evaluation Consider the following boolean expression: x > y || x > z The expression is evaluated left to right. If x > y is true, then there’s no need to evaluate x > z because the whole expression will be true whether x > z is true or not. To stop the evaluation once the result of the whole expression is known is called short-circuit evaluation. What would happen if the short-circuit evaluation is not done for the following expression? z == 0 || x / z > 20 The Java interpreter does not always evaluate the complete boolean expression. When the result of a given boolean expression is determined before fully evaluating the complete expression, the interpreter stops the evaluation. If the expression z == 0 || x / z > 20 is fully evaluated, it will result in a divide-by-zero error when the value of z is equal to 0. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
190
Operator Precedence Rules
Intro to OOP with Java, C. Thomas Wu Operator Precedence Rules The precedence table shows the order of operator evaluation. Instead of memorizing this table, it is more convenient and the code more readable if you use the parentheses judiciously. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
191
Intro to OOP with Java, C. Thomas Wu
Boolean Variables The result of a boolean expression is either true or false. These are the two values of data type boolean. We can declare a variable of data type boolean and assign a boolean value to it. boolean pass, done; pass = 70 < x; done = true; if (pass) { … } else { } The result of a boolean expression is one of the values of data type boolean. As we can assign an int value to an int variable, we can assign a boolean value to a boolean variable. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
192
Intro to OOP with Java, C. Thomas Wu
Boolean Methods A method that returns a boolean value, such as private boolean isValid(int value) { if (value < MAX_ALLOWED) return true; } else { return false; } if (isValid(30)) { … } else { } This example shows an effective use of a boolean method. We will be seeing this style of using boolean methods frequently, so make sure you are comfortable with this. Can be used as ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
193
Intro to OOP with Java, C. Thomas Wu
Comparing Objects With primitive data types, we have only one way to compare them, but with objects (reference data type), we have two ways to compare them. We can test whether two variables point to the same object (use ==), or We can test whether two distinct objects have the same contents. Comparing primitive data types is straightforward because there's only one way to compare them. Comparing objects is a little trickier because we can compare them in two different ways. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
194
Using == With Objects (Sample 1)
Intro to OOP with Java, C. Thomas Wu Using == With Objects (Sample 1) String str1 = new String("Java"); String str2 = new String("Java"); if (str1 == str2) { System.out.println("They are equal"); } else { System.out.println("They are not equal"); } They are not equal When we use the equality operator (==), we can comparing the contents of the variables str1 and str2. So str1 == str2 being true means the contents are the same, which in turn, means they are pointing to the same object because the content of a reference data type is an address. Therefore, if there are two distinct objects, even the values hold by these objects are the same, the equality testing by the equality operator will always result in false. Not equal because str1 and str2 point to different String objects. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
195
Using == With Objects (Sample 2)
Intro to OOP with Java, C. Thomas Wu Using == With Objects (Sample 2) String str1 = new String("Java"); String str2 = str1; if (str1 == str2) { System.out.println("They are equal"); } else { System.out.println("They are not equal"); } They are equal It's equal here because str1 and str2 point to the same object. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
196
Using equals with String
Intro to OOP with Java, C. Thomas Wu Using equals with String String str1 = new String("Java"); String str2 = new String("Java"); if (str1.equals(str2)) { System.out.println("They are equal"); } else { System.out.println("They are not equal"); } To compare whether two String objects have the same sequence of characters, we use the equals method. This method checks for the case. If we want to compare String objects case-insensitively, then we use the equalsIgnoreCase method. They are equal It's equal here because str1 and str2 have the same sequence of characters. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
197
Intro to OOP with Java, C. Thomas Wu
The Semantics of == ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
198
In Creating String Objects
Intro to OOP with Java, C. Thomas Wu In Creating String Objects ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
199
Intro to OOP with Java, C. Thomas Wu
The switch Statement int gradeLevel; gradeLevel = JOptionPane.showInputDialog("Grade (Frosh-1,Soph-2,...):" ); switch (gradeLevel) { case 1: System.out.print("Go to the Gymnasium"); break; case 2: System.out.print("Go to the Science Auditorium"); case 3: System.out.print("Go to Harris Hall Rm A3"); case 4: System.out.print("Go to Bolt Hall Rm 101"); } This statement is executed if the gradeLevel is equal to 1. This is an example of a switch statement. The variable gradeLevel is called a switch control. The data type for a switch control must be one of the integer data types or a char. This statement is executed if the gradeLevel is equal to 4. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
200
Syntax for the switch Statement
Intro to OOP with Java, C. Thomas Wu Syntax for the switch Statement switch ( <arithmetic expression> ) { <case label 1> : <case body 1> … <case label n> : <case body n> } Arithmetic Expression switch ( gradeLevel ) { case 1: System.out.print("Go to the Gymnasium"); break; case 2: System.out.print("Go to the Science Auditorium"); case 3: System.out.print("Go to Harris Hall Rm A3"); case 4: System.out.print("Go to Bolt Hall Rm 101"); } Case Label This is the general syntax rule for a switch statement. The case body may contain zero or more statements. Case Body ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
201
switch With No break Statements
Intro to OOP with Java, C. Thomas Wu switch With No break Statements x = 10; false true N == 1 ? x = 20; x = 30; N == 2 ? N == 3 ? switch ( N ) { case 1: x = 10; case 2: x = 20; case 3: x = 30; } This flowchart shows the control flow of a switch statement when case bodies do not include the break statement. The flow will first start from the matching case body and then proceed to the subsequent case bodies. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
202
switch With break Statements
Intro to OOP with Java, C. Thomas Wu switch With break Statements x = 10; false true N == 1 ? x = 20; x = 30; N == 2 ? N == 3 ? break; switch ( N ) { case 1: x = 10; break; case 2: x = 20; case 3: x = 30; } By placing a break statement at the end of a case body, the control flow will jump to the next statement that follows this switch statement. By placing a break statement at the end of each case body, the case bodies become mutually exclusive, i.e., at most one case body will be executed. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
203
switch With the default Block
Intro to OOP with Java, C. Thomas Wu switch With the default Block switch (ranking) { case 10: case 9: case 8: System.out.print("Master"); break; case 7: case 6: System.out.print("Journeyman"); case 5: case 4: System.out.print("Apprentice"); default: System.out.print("Input error: Invalid Data"); } If the ranking is 10, 9, or 8, then the text “Master” is displayed. If the ranking is 7 or 6, “Journeyman” is displayed. If the ranking is 5 or 4, “Apprentice” is displayed. If there’s no matching case, the default case is executed and an error message is displayed. If a default case is included, then it is executed when there are no matching cases. You can define at most one default case. A default case is often used to detect an erroneous value in the control variable. Although not required, it is a standard to place the default case at the end. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
204
Intro to OOP with Java, C. Thomas Wu
Drawing Graphics Chapter 5 introduces four standard classes related to drawing geometric shapes. They are java.awt.Graphics java.awt.Color java.awt.Point java.awt.Dimension These classes are used in the Sample Development section Please refer to Java API for details A Graphics object keeps track of necessary information about the system to draw geometric shapes. A Color object represents a color in RGB (red, green, blue) format. A Point object represents a point in a coordinate system. A Dimension object represents the dimension of a rectangular shape. Section 5.6 of the textbook explains these four standard classes. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
205
Intro to OOP with Java, C. Thomas Wu
Sample Drawing This program draws a rectangle of size 100 pixels wide by 30 pixels high at location (50, 50) in a frame window. We are actually drawing the rectangle on the content pane of the frame window. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
206
Intro to OOP with Java, C. Thomas Wu
The Effect of drawRect ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
207
Intro to OOP with Java, C. Thomas Wu
Problem Statement Problem statement: Write an application that simulates a screensaver by drawing various geometric shapes in different colors. The user has an option of choosing a type (ellipse or rectangle), color, and movement (stationary, smooth, or random). ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
208
Intro to OOP with Java, C. Thomas Wu
Overall Plan Tasks: Get the shape the user wants to draw. Get the color of the chosen shape. Get the type of movement the user wants to use. Start the drawing. As a part of the overall plan, we begin by identifying the main tasks for the program. Notice this program follows the universal pattern of computer programs, namely, the pattern of input, computation, and output. The drawing of a specified object constitutes the computation and output aspects of the program pattern. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
209
Intro to OOP with Java, C. Thomas Wu
Required Classes Ch5DrawShape JOptionPane standard class DrawingBoard DrawableShape Given the tasks identified in the overall program flow, we need to find suitable classes and objects to carry out the tasks. For this program, we will use one helper class that provides a service of drawing and moving geometric shapes. The actual shape to be drawn is determined by the code programmed in the DrawableShape class. We specify the shapes we want to draw by implementing the DrawableShape class accordingly. In addition to this class, we will implement the main class Ch5DrawShape. class we implement helper class given to us ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
210
Intro to OOP with Java, C. Thomas Wu
Development Steps We will develop this program in six steps: Start with a program skeleton. Explore the DrawingBoard class. Define an experimental DrawableShape class that draws a dummy shape. Add code to allow the user to select a shape. Extend the DrawableShape and other classes as necessary. Add code to allow the user to specify the color. Extend the DrawableShape and other classes as necessary. Add code to allow the user to specify the motion type. Extend the DrawableShape and other classes as necessary. Finalize the code by tying up loose ends. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
211
Intro to OOP with Java, C. Thomas Wu
Step 1 Design The methods of the DrawingBoard class public void addShape(DrawableShape shape) Adds a shape to the DrawingBoard. No limit to the number shapes you can add public void setBackground(java.awt.Color color) Sets the background color of a window to the designated color public void setDelayTime(double delay) Sets the delay time between drawings to delay seconds public void setMovement(int type) Sets the movement type to STATIONARY, RANDOM, or SMOOTH public void setVisible(boolean state) public void start( ) Starts the drawing of added shapes using the designated movement type and delay time. In the first step, we explore the given DrawingBoard class. There are six public methods. Fuller explanation can be found on page 268 of the textbook. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
212
Intro to OOP with Java, C. Thomas Wu
Step 1 Code Directory: Chapter5/Step1 Source Files: Ch5DrawShape.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Please use your Java IDE to view the source files and run the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
213
Intro to OOP with Java, C. Thomas Wu
Step 1 Test In the testing phase, we run the program and verify that a DrawingBoard window with black background appears on the screen and fills the whole screen. Run the program and verify that you get the same result. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
214
Intro to OOP with Java, C. Thomas Wu
Step 2 Design Define a preliminary DrawableShape class The required methods of this class are public void draw(java.awt.Graphics g) Draws a shape on Graphics object g. public java.awt.Point getCenterPoint( ) Returns the center point of this shape public java.awt.Dimension getDimension( ) Returns the bounding rectangle of this shape public void setCenterPoint(java.awt.Point pt) Sets the center point of this shape to pt. We are now ready to test the actual drawing of some geometric shape. The DrawingBoard class controls a collection of shapes by drawing and moving them on a frame window. The actual drawing of a shape is delegated to the draw method of DrawableShape. So by defining this method ourselves, we can draw any shape we want to draw. In addition to calling to the draw method, a DrawingBoard object will be calling three additional public methods of the DrawableShape class. We need to define them also. In this step we will draw a fix-sized circle whose radius is set to 100 pixels and dimension to 200 by 200 pixels. We will improve the methods as we progress through the development steps. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
215
Intro to OOP with Java, C. Thomas Wu
Step 2 Code Directory: Chapter5/Step2 Source Files: Ch5DrawShape.java DrawableShape.java We extended the start method of the Ch5DrawShape class to add three DrawableShape objects with different center points. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
216
Intro to OOP with Java, C. Thomas Wu
Step 2 Test We compile and run the program numerous times We confirm the movement types STATIONARY, RANDOM, and SMOOTH. We experiment with different delay times We try out different background colors Our key purpose of Step 2 testing is to confirm the connection between the DrawingBoard and DrawableShape classes. We need to try out all three movement types and confirm how they affect the movement of geometric shapes. We will also experiment with the delay times and background colors. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
217
Intro to OOP with Java, C. Thomas Wu
Step 3 Design We extend the main class to allow the user to select a shape information. We will give three choices of shapes to the user: Ellipse, Rectangle, and Rounded Rectangle We also need input routines for the user to enter the dimension and center point. The center point determines where the shape will appear on the DrawingBoard. Three input methods are private int inputShapeType( ) private Dimension inputDimension( ) private Point inputCenterPoint( ) The input methods for shape type, dimension, and center point will include input validation tests. For example, the width of a shape is restricted within the range of 100 and 500 pixels. Any invalid input will be replaced by a minimum valid value of 100. The DrawableShape class is updated accordingly to handle the drawing of different shapes. In the previous step, a fix-sized circle was drawn. The drawShape method is updated to draw three different types of shapes. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
218
Intro to OOP with Java, C. Thomas Wu
Step 3 Code Directory: Chapter5/Step3 Source Files: Ch5DrawShape.java DrawableShape.java Both classes include substantial additions to the code. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
219
Intro to OOP with Java, C. Thomas Wu
Step 3 Test We run the program numerous times with different input values and check the results. Try both valid and invalid input values and confirm the response is appropriate We need to try out as many variations as possible for the input values, trying out all three possible shape types, different dimensions, and different center points. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
220
Intro to OOP with Java, C. Thomas Wu
Step 4 Design We extend the main class to allow the user to select a color. We follow the input pattern of Step 3. We will allow the user to select one of the five colors. The color input method is private Color inputColor( ) We follow the pattern of inputting the shape type for the color input routine. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
221
Intro to OOP with Java, C. Thomas Wu
Step 4 Code Directory: Chapter5/Step4 Source Files: Ch5DrawShape.java DrawableShape.java We make intermediate extensions to both classes to handle the color input and drawing. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
222
Intro to OOP with Java, C. Thomas Wu
Step 4 Test We run the program numerous times with different color input. Try both valid and invalid input values and confirm the response is appropriate We need to try out as many variations as possible to test the color input routine and verify the color selected is used in the actual drawing of shapes. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
223
Intro to OOP with Java, C. Thomas Wu
Step 5 Design We extend the main class to allow the user to select a movement type. We follow the input pattern of Step 3. We will allow the user to select one of the three movement types. The movement input method is private int inputMotionType( ) We follow the pattern of inputting the shape type for the movement input routine. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
224
Intro to OOP with Java, C. Thomas Wu
Step 5 Code Directory: Chapter5/Step5 Source Files: Ch5DrawShape.java DrawableShape.java We make minor extensions to both classes to handle the movement input routine. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
225
Intro to OOP with Java, C. Thomas Wu
Step 5 Test We run the program numerous times with different movement input. Try both valid and invalid input values and confirm the response is appropriate We need to try out as many variations as possible to test the movement input routine and verify the movement selected is used in the actual drawing of shapes. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
226
Intro to OOP with Java, C. Thomas Wu
Step 6: Finalize Possible Extensions Morphing the object shape Changing the object color Drawing multiple objects Drawing scrolling text There are a number of very interesting extensions we can make to the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
227
Intro to OOP with Java, C. Thomas Wu Repetition Statements
Chapter 6 Repetition Statements ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
228
Intro to OOP with Java, C. Thomas Wu
Objectives After you have read and studied this chapter, you should be able to Implement repetition control in a program using while statements. Implement repetition control in a program using do-while statements. Implement a generic loop-and-a-half repetition control statement Implement repetition control in a program using for statements. Nest a loop repetition statement inside another repetition statement. Choose the appropriate repetition control statement for a given task Prompt the user for a yes-no reply using the showConfirmDialog method of JOptionPane. (Optional) Write simple recursive methods We will study two forms of repetition statements in this lesson. They are while and do-while statement. ©The McGraw-Hill Companies, Inc.
229
Intro to OOP with Java, C. Thomas Wu
Definition Repetition statements control a block of code to be executed for a fixed number of times or until a certain condition is met. Count-controlled repetitions terminate the execution of the block after it is executed for a fixed number of times. Sentinel-controlled repetitions terminate the execution of the block after one of the designated values called a sentinel is encountered. Repetition statements are called loop statements also. In Chapter 5, we studied selection control statements. We will study in this chapter the second type of control statement, a repetition statement, that alters the sequential control flow. It controls the number of times a block of code is executed. In other words, a block of code is executed repeatedly until some condition occurs to stop the repetition. There are fundamentally two ways to stop the repetition—count-controlled and sentinel-controlled. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
230
Intro to OOP with Java, C. Thomas Wu
The while Statement int sum = 0, number = 1; while ( number <= 100 ) { sum = sum + number; number = number + 1; } These statements are executed as long as number is less than or equal to 100. The first repetition control we will study is the while statement. Here’s an example that computes the sum of integers from 1 to 100, inclusively. Note: there’s a closed form to compute the sum of 1 to 100, which is (100 * 101) / 2, so this repetition statement is a illustration purpose only. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
231
Syntax for the while Statement
Intro to OOP with Java, C. Thomas Wu Syntax for the while Statement while ( <boolean expression> ) <statement> Boolean Expression while ( number <= ) { sum = sum + number; number = number + 1; } Here’s the general syntax of a while statement. As long as the <boolean expression> is true, the loop body is executed. Notice that the loop body may not be executed at all. Statement (loop body) ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
232
Intro to OOP with Java, C. Thomas Wu
Control Flow of while int sum = 0, number = 1 number <= 100 ? sum = sum + number; number = number + 1; true false This flowchart shows the control flow of the while statement. If the <boolean expression> is true, the loop body is executed and the control returns to the top. If the <boolean expression> is false, then the control flows to the next statement that follows this while statement. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
233
Intro to OOP with Java, C. Thomas Wu
More Examples int sum = 0, number = 1; while ( sum <= ) { sum = sum + number; number = number + 1; } 1 Keeps adding the numbers 1, 2, 3, … until the sum becomes larger than 1,000,000. int product = 1, number = 1, count = 20, lastNumber; lastNumber = 2 * count - 1; while (number <= lastNumber) { product = product * number; number = number + 2; } 2 Computes the product of the first 20 odd integers. Variation on computing the product of the first 20 odd integers: int product = 1, number = 1, lastTerm = 20, count = 1; while ( count <= lastTerm ) { product = product * (2 * number – 1); count = count + 1; } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
234
Finding GCD ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
235
Example: Testing Input Data
Intro to OOP with Java, C. Thomas Wu Example: Testing Input Data String inputStr; int age; inputStr = JOptionPane.showInputDialog(null, "Your Age (between 0 and 130):"); age = Integer.parseInt(inputStr); while (age < 0 || age > 130) { JOptionPane.showMessageDialog(null, "An invalid age was entered. Please try again."); age = Integer.parseInt(inputStr); } Priming Read Here's a more practical example of using a repetition statement. This code will only accept a value greater than 0 but less than 130. If an input value is invalid, then the code will repeat until the valid input is read. Notice that the 'age' variable must have a value before the boolean expression of the while statement can be evaluated. We therefore read the input value before the while test. This reading of input values before the test is called priming read. The loop body of this while statement is executed zero times if the input is valid the first time. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
236
Useful Shorthand Operators
Intro to OOP with Java, C. Thomas Wu Useful Shorthand Operators sum = sum + number; sum += number; is equivalent to Operator Usage Meaning += a += b; a = a + b; -= a -= b; a = a – b; *= a *= b; a = a * b; /= a /= b; a = a / b; %= a %= b; a = a % b; When writing a repetition statement, we often see the statement that modifies the value of a variable in the form such as sum = sum + number. Because of a high occurrence of such statement, we can use shorthand operators. These shorthand assignment operators have precedence lower than any other arithmetic operators, so, for example, the statement sum *= a + b; is equivalent to sum = sum * (a + b); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
237
Intro to OOP with Java, C. Thomas Wu
Watch Out for Pitfalls Watch out for the off-by-one error (OBOE). Make sure the loop body contains a statement that will eventually cause the loop to terminate. Make sure the loop repeats exactly the correct number of times. If you want to execute the loop body N times, then initialize the counter to 0 and use the test condition counter < N or initialize the counter to 1 and use the test condition counter <= N. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
238
Intro to OOP with Java, C. Thomas Wu
Loop Pitfall - 1 int product = 0; while ( product < ) { product = product * 5; } 1 Infinite Loops Both loops will not terminate because the boolean expressions will never become false. int count = 1; while ( count != 10 ) { count = count + 2; } 2 If you are not careful, you can easily end up writing an infinite loop. Make sure the test is written in such a way that the loop will terminate eventually. ©The McGraw-Hill Companies, Inc.
239
Intro to OOP with Java, C. Thomas Wu
Overflow An infinite loop often results in an overflow error. An overflow error occurs when you attempt to assign a value larger than the maximum value the variable can hold. In Java, an overflow does not cause program termination. With types float and double, a value that represents infinity is assigned to the variable. With type int, the value “wraps around” and becomes a negative value. When an overflow error occurs, the execution of the program is terminated in almost all programming languages. When an overflow occurs in Java, a value that represents infinity (IEEE 754 infinity, to be precise) is assigned to a variable and no abnormal termination of a program will happen. Also, in Java an overflow occurs only with float and double variables; no overflow will happen with int variables. When you try to assign a value larger than the maximum possible integer an int variable can hold, the value “wraps around” and becomes a negative value. Whether the loop terminates or not because of an overflow error, the logic of the loop is still an infinite loop, and we must watch out for it. When you write a loop, you must make sure that the boolean expression of the loop will eventually become false. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
240
Intro to OOP with Java, C. Thomas Wu
Loop Pitfall - 2 float count = 0.0f; while ( count != 1.0f ) { count = count f; } //seven 3s 1 Using Real Numbers Loop 2 terminates, but Loop 1 does not because only an approximation of a real number can be stored in a computer memory. float count = 0.0f; while ( count != 1.0f ) { count = count f; } //eight 3s 2 Although 1/3 + 1/3 + 1/3 == 1 is mathematically true, the expression 1.0/ / /3.0 in computer language may or may not get evaluated to 1.0 depending on how precise the approximation is. In general, avoid using real numbers as counter variables because of this imprecision. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
241
Intro to OOP with Java, C. Thomas Wu
Loop Pitfall – 2a int result = 0; double cnt = 1.0; while (cnt <= 10.0){ cnt += 1.0; result++; } System.out.println(result); 1 Using Real Numbers Loop 1 prints out 10, as expected, but Loop 2 prints out 11. The value 0.1 cannot be stored precisely in computer memory. 10 11 int result = 0; double cnt = 0.0; while (cnt <= 1.0){ cnt += 0.1; result++; } System.out.println(result); 2 Here's another example of using a double variable as a counter. The two loops are identical in concept, and therefore, should output the same result. They would if real numbers are stored precisely in computer memory. Because the value of 0.1 cannot be represented precisely in computer memory, the second one will actually print out 11, while the first one prints out 10, as expected. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
242
Intro to OOP with Java, C. Thomas Wu
Loop Pitfall - 3 Goal: Execute the loop body 10 times. count = 1; while ( count < 10 ){ . . . count++; } 1 count = 1; while ( count <= 10 ){ . . . count++; } 2 count = 0; while ( count <= 10 ){ . . . count++; } 3 count = 0; while ( count < 10 ){ . . . count++; } 4 Yes, you can write the desired loop as count = 1; while (count != 10 ) { ... count++; } but this condition for stopping the count-controlled loop is dangerous. We already mentioned about the potential trap of an infinite loop. 1 3 and exhibit off-by-one error. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
243
The do-while Statement
Intro to OOP with Java, C. Thomas Wu The do-while Statement int sum = 0, number = 1; do { sum += number; number++; } while ( sum <= ); These statements are executed as long as sum is less than or equal to 1,000,000. Here's an example of the second type of repetition statement called do-while. This sample code computes the sum of integers starting from 1 until the sum becomes greater than 1,000,000. The main difference between the while and do-while is the relative placement of the test. The test occurs before the loop body for the while statement, and the text occurs after the loop body for the do-while statement. Because of this characteristic, the loop body of a while statement is executed 0 or more times, while the loop body of the do-while statement is executed 1 or more times. In general, the while statement is more frequently used than the do–while statement. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
244
Syntax for the do-while Statement
Intro to OOP with Java, C. Thomas Wu Syntax for the do-while Statement do <statement> while ( <boolean expression> ) ; do { sum += number; number++; } while ( sum <= ); Statement (loop body) Here’s the general syntax of a do-while statement. As long as the <boolean expression> is true, the loop body is executed. Notice that the loop body is executed at least once. Boolean Expression ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
245
Control Flow of do-while
Intro to OOP with Java, C. Thomas Wu Control Flow of do-while int sum = 0, number = 1 sum += number; number++; true sum <= ? This flowchart shows the control flow of the do-while statement. If the <boolean expression> is true, the control returns to the top. If the <boolean expression> is false, then the control flows to the next statement that follows this do-while statement. false ©The McGraw-Hill Companies, Inc.
246
Loop-and-a-Half Repetition Control
Intro to OOP with Java, C. Thomas Wu Loop-and-a-Half Repetition Control Loop-and-a-half repetition control can be used to test a loop’s terminating condition in the middle of the loop body. It is implemented by using reserved words while, if, and break. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
247
Example: Loop-and-a-Half Control
Intro to OOP with Java, C. Thomas Wu Example: Loop-and-a-Half Control String name; while (true){ name = JOptionPane.showInputDialog(null, "Your name"); if (name.length() > 0) break; JOptionPane.showMessageDialog(null, "Invalid Entry." + "You must enter at least one character."); } This is a simple example of a loop-and-a-half control. Notice the priming read is avoided with this control. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
248
Pitfalls for Loop-and-a-Half Control
Intro to OOP with Java, C. Thomas Wu Pitfalls for Loop-and-a-Half Control Be aware of two concerns when using the loop-and-a-half control: The danger of an infinite loop. The boolean expression of the while statement is true, which will always evaluate to true. If we forget to include an if statement to break out of the loop, it will result in an infinite loop. Multiple exit points. It is possible, although complex, to write a correct control loop with multiple exit points (breaks). It is good practice to enforce the one-entry one-exit control flow. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
249
Intro to OOP with Java, C. Thomas Wu
Confirmation Dialog A confirmation dialog can be used to prompt the user to determine whether to continue a repetition or not. JOptionPane.showConfirmDialog(null, /*prompt*/ "Play Another Game?", /*dialog title*/ "Confirmation", /*button options*/ JOptionPane.YES_NO_OPTION); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
250
Example: Confirmation Dialog
Intro to OOP with Java, C. Thomas Wu Example: Confirmation Dialog boolean keepPlaying = true; int selection; while (keepPlaying){ //code to play one game comes here // . . . selection = JOptionPane.showConfirmDialog(null, "Play Another Game?", "Confirmation", JOptionPane.YES_NO_OPTION); keepPlaying = (selection == JOptionPane.YES_OPTION); } Here's an example of how we can use a confirmation dialog in a loop. At the end of the loop, we prompt the user to repeat the loop again or not. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
251
Intro to OOP with Java, C. Thomas Wu
The for Statement int i, sum = 0, number; for (i = 0; i < 20; i++) { number = scanner.nextInt( ); sum += number; } These statements are executed for 20 times ( i = 0, 1, 2, … , 19). This is a basic example of a for statement. This for statement reads 20 integers and compute their sum. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
252
Syntax for the for Statement
Intro to OOP with Java, C. Thomas Wu Syntax for the for Statement for ( <initialization>; <boolean expression>; <increment> ) <statement> Initialization Boolean Expression Increment for ( i = 0 ; i < ; i ) { number = scanner.nextInt(); sum += number; } This shows the general syntax for the for statement. The <initialization> component also can include a declaration of the control variable. We can do something like this: for (int i = 0; i < 10; i++) instead of int i; for (i = 0; i < 10; i++) Statement (loop body) ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
253
Intro to OOP with Java, C. Thomas Wu
Control Flow of for i = 0; i < 20 ? false number = ; sum = number; true i ++; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
254
Intro to OOP with Java, C. Thomas Wu
More for Loop Examples for (int i = 0; i < 100; i += 5) 1 i = 0, 5, 10, … , 95 for (int j = 2; j < 40; j *= 2) 2 j = 2, 4, 8, 16, 32 Here are some more examples of a for loop. Notice how the counting can go up or down by changing the increment expression accordingly. for (int k = 100; k > 0; k--) ) 3 k = 100, 99, 98, 97, ..., 1 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
255
The Nested-for Statement
Intro to OOP with Java, C. Thomas Wu The Nested-for Statement Nesting a for statement inside another for statement is commonly used technique in programming. Let’s generate the following table using nested-for statement. Just an if statement can be nested inside another if statement, we often nest for loops. For example, using a nest-for loop is the most appropriate way to generate a table such as the illustration. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
256
Intro to OOP with Java, C. Thomas Wu
Generating the Table int price; for (int width = 11; width <=20, width++){ for (int length = 5, length <=25, length+=5){ price = width * length * 19; //$19 per sq. ft. System.out.print (“ “ + price); } //finished one row; move on to next row System.out.println(“”); INNER OUTER Here's how the table can be produced by a nested-for loop. For each value of width, length will range from 5 to 25 with an increment of 5. Here’s how the values for width and length change over the course of execution. width length 11 5 10 15 20 25 12 13 and so on… ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
257
Intro to OOP with Java, C. Thomas Wu
Formatting Output We call the space occupied by an output value the field. The number of characters allocated to a field is the field width. The diagram shows the field width of 6. From Java 5.0, we can use the Formatter class. System.out (PrintStream) also includes the format method. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
258
Intro to OOP with Java, C. Thomas Wu
The Formatter Class We use the Formatter class to format the output. First we create an instance of the class Formatter formatter = new Formatter(System.out); Then we call its format method int num = 467; formatter.format("%6d", num); This will output the value with the field width of 6. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
259
The format Method of Formatter
Intro to OOP with Java, C. Thomas Wu The format Method of Formatter The general syntax is format(<control string>, <expr1>, <expr2>, ) Example: int num1 = 34, num2 = 9; int num3 = num1 + num2; formatter.format("%3d + %3d = %5d", num1, num2, num3); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
260
The format Method of PrintStream
Intro to OOP with Java, C. Thomas Wu The format Method of PrintStream Instead of using the Formatter class directly, we can achieve the same result by using the format method of PrintStream (System.out) Formatter formatter = new Formatter(System.out); formatter.format("%6d", 498); is equivalent to System.out.format("%6d", 498); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
261
Intro to OOP with Java, C. Thomas Wu
Control Strings Integers % <field width> d Real Numbers % <field width> . <decimal places> f Strings % s For other data types and more formatting options, please consult the Java API for the Formatter class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
262
Estimating the Execution Time
Intro to OOP with Java, C. Thomas Wu Estimating the Execution Time In many situations, we would like to know how long it took to execute a piece of code. For example, Execution time of a loop statement that finds the greatest common divisor of two very large numbers, or Execution time of a loop statement to display all prime numbers between 1 and 100 million Execution time can be measured easily by using the Date class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
263
Intro to OOP with Java, C. Thomas Wu
Using the Date Class Here's one way to measure the execution time Date startTime = new Date(); //code you want to measure the execution time Date endTime = new Date(); long elapsedTimeInMilliSec = endTime.getTime() – startTime.getTime(); We can achieve the same result by using the currentTimeMillis method of the System class as long start = System.currentTimeMillis(); //code to measure long end = System.currentTimeMillis(); long elapsedTimeInMilliSec = end – start; To get the elasped time in seconds, we divide the milliseconds by 1000 long elapsedTimeInSec = elapsedTimeInMilliSec / 1000; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
264
Intro to OOP with Java, C. Thomas Wu
Problem Statement Problem statement: Write an application that will play Hi-Lo games with the user. The objective of the game is for the user to guess the computer-generated secret number in the least number of tries. The secret number is an integer between 1 and 100, inclusive. When the user makes a guess, the program replies with HI or LO depending on whether the guess is higher or lower than the secret number. The maximum number of tries allowed for each game is six. The user can play as many games as she wants. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
265
Intro to OOP with Java, C. Thomas Wu
Overall Plan Tasks: do { Task 1: generate a secret number; Task 2: play one game; } while ( the user wants to play ); As a part of the overall plan, we begin by identifying the main tasks for the program. Unlike the overall plan for the previous sample developments, we will use a pseudo code to express the top level logic of the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
266
Intro to OOP with Java, C. Thomas Wu
Required Classes JOptionPane Ch6HiLo Math The structure of this program is very simple. We will use two standard classes, one for input and output and another for generating random numbers. main class standard classes ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
267
Intro to OOP with Java, C. Thomas Wu
Development Steps We will develop this program in four steps: Start with a skeleton Ch6HiLo class. Add code to the Ch6HiLo class to play a game using a dummy secret number. Add code to the Ch6HiLo class to generate a random number. Finalize the code by tying up loose ends. The second and the third steps correspond to the two major tasks identified in the overall plan. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
268
Intro to OOP with Java, C. Thomas Wu
Step 1 Design The topmost control logic of HiLo 1. describe the game rules; 2. prompt the user to play a game or not; while ( answer is yes ) { 3. generate the secret number; 4. play one game; 5. prompt the user to play another game or not; } In the first step, we determine a little more detailed control logic than the one stated in the overall plan. For each of the five identified functions, we will define a method: describeRules, generateSecretNumber, playGame, and prompt. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
269
Intro to OOP with Java, C. Thomas Wu
Step 1 Code Directory: Chapter6/Step1 Source Files: Ch6HiLo.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Please use your Java IDE to view the source files and run the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
270
Intro to OOP with Java, C. Thomas Wu
Step 1 Test In the testing phase, we run the program and verify confirm that the topmost control loop terminates correctly under different conditions. Play the game zero times one time one or more times Run the program and verify that the topmost control loop is functioning correctly. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
271
Intro to OOP with Java, C. Thomas Wu
Step 2 Design Implement the playGame method that plays one game of HiLo. Use a dummy secret number By using a fix number such as 45 as a dummy secret number, we will be able to test the correctness of the playGame method In order to verify whether our code is working correctly or not, we need to know what is the secret number. The easiest way to do this is to use a fixed number, such as 45, make the temporary generateRandomNumber to return this fixed number. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
272
Intro to OOP with Java, C. Thomas Wu
The Logic of playGame int guessCount = 0; do { get next guess; guessCount++; if (guess < secretNumber) { print the hint LO; } else if (guess > secretNumber) { print the hint HI; } } while (guessCount < number of guesses allowed && guess != secretNumber ); if (guess == secretNumber) { print the winning message; } else { print the losing message; Here's the playGame method expressed as a pseudocode. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
273
Intro to OOP with Java, C. Thomas Wu
Step 2 Code Directory: Chapter6/Step2 Source Files: Ch6HiLo.java We implement the playGame and getNextGuess methods in this step. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
274
Intro to OOP with Java, C. Thomas Wu
Step 2 Test We compile and run the program numerous times To test getNextGuess, enter a number less than 1 a number greater than 100 a number between 2 and 99 the number 1 and the number 100 To test playGame, enter a guess less than 45 a guess greater than 45 45 six wrong guesses We need to verify the correctness of two methods: playGame and getNextGuess. Try all cases presented here and confirm that you get the expected responses. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
275
Intro to OOP with Java, C. Thomas Wu
Step 3 Design We complete the generateSecretNumber method. We want to generate a number between 1 and 100 inclusively. private void generateSecretNumber( ) { double X = Math.random(); secretNumber = (int) Math.floor( X * 100 ) + 1; System.out.println("Secret Number: " secretNumber); // TEMP return secretNumber; } Notice that we have one temporary statement to output the value of secretNumber. We include it for the testing purpose, i.e., we need to check the numbers generated are valid. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
276
Intro to OOP with Java, C. Thomas Wu
Step 3 Code Directory: Chapter6/Step3 Source Files: Ch6HiLo.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
277
Intro to OOP with Java, C. Thomas Wu
Step 3 Test We use a separate test driver to generate 1000 secret numbers. We run the program numerous times with different input values and check the results. Try both valid and invalid input values and confirm the response is appropriate As always, we run the final test by running the program numerous times trying out as many variations as possible. Before testing the generateSecretNumber method as a part of the final program, we will use a separate test driver to generate 1000 (or more) secret numbers and verify that they are valid. class TestRandom { public static void main (String[] args) { int N = 1000, count = 0, number; double X; do { count++; X = Math.random(); number = (int) Math.floor( X * 100 ) + 1; } while ( count < N && 1 <= number && number <= 100 ); if ( number < 1 || number > 100 ) { System.out.println("Error: " + number); } else { System.out.println("Okay"); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
278
Intro to OOP with Java, C. Thomas Wu
Step 4: Finalize Program Completion Finish the describeRules method Remove all temporary statements Possible Extensions Allow the user to set her desired min and max for secret numbers Allow the user to set the number of guesses allowed Keep the score—the number of guesses made —while playing games and display the average score when the user quits the program ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
279
Defining Your Own Classes Part 2
Chapter 7 Defining Your Own Classes Part 2 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
280
Intro to OOP with Java, C. Thomas Wu
Objectives After you have read and studied this chapter, you should be able to Describe how objects are returned from methods Describe how the reserved word this is used Define overloaded methods and constructors Define class methods and variables Describe how the arguments are passed to the parameters using the pass-by-value scheme Document classes with javadoc comments Organize classes into a package A class is instantiable if we can create instances of it. For example, the JFrame class is instantiable. A class is noninstantiable if we cannot create its instances. The Math class is one example of noninstantiable classes. The main classes we have been writing are all noninstantiable. We will learn how to define instantiable classes in this lesson. A constructor is a special method that is used to initialize an instance of a class when it is first created. ©The McGraw-Hill Companies, Inc.
281
Returning an Object from a Method
Intro to OOP with Java, C. Thomas Wu Returning an Object from a Method As we can return a primitive data value from a method, we can return an object from a method also. We return an object from a method, we are actually returning a reference (or an address) of an object. This means we are not returning a copy of an object, but only the reference of this object We already know how to return an object from a method, because we have been returning a string from a method and a string is an object (an instance of the String class). However, String objects are treated much like primitive data. We will explore a little deeper into this topic. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
282
Sample Object-Returning Method
Here's a sample method that returns an object: Return type indicates the class of an object we're returning from the method. public Fraction simplify( ) { Fraction simp; int num = getNumberator(); int denom = getDenominator(); int gcd = gcd(num, denom); simp = new Fraction(num/gcd, denom/gcd); return simp; } Return an instance of the Fraction class ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
283
A Sample Call to simplify
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
284
A Sample Call to simplify (cont'd)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
285
Reserved Word this The reserved word this is called a self-referencing pointer because it refers to an object from the object's method. The reserved word this can be used in three different ways. We will see all three uses in this chapter. : Object this ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
286
The Use of this in the add Method
Intro to OOP with Java, C. Thomas Wu The Use of this in the add Method public Fraction add(Fraction frac) { int a, b, c, d; Fraction sum; a = this.getNumerator(); //get the receiving b = this.getDenominator(); //object's num and denom c = frac.getNumerator(); //get frac's num d = frac.getDenominator(); //and denom sum = new Fraction(a*d + b*c, b*d); return sum; } The use of the reserved word this is option in this context. Calling a method of a class or accessing a data member of the class can be achieved without the reserved word this. Consider, for example, class One { public int m1( ) { return 10; } public void m2( ) { int num; num = m1(); this is equivalent to num = this.m1(); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
287
Intro to OOP with Java, C. Thomas Wu
f1.add(f2) Because f1 is the receiving object (we're calling f1's method), so the reserved word this is referring to f1. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
288
f2.add(f1) This time, we're calling f2's method, so the reserved word this is referring to f2. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
289
Using this to Refer to Data Members
Intro to OOP with Java, C. Thomas Wu Using this to Refer to Data Members In the previous example, we showed the use of this to call a method of a receiving object. It can be used to refer to a data member as well. class Person { int age; public void setAge(int val) { this.age = val; } . . . ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
290
Intro to OOP with Java, C. Thomas Wu
Overloaded Methods Methods can share the same name as long as they have a different number of parameters (Rule 1) or their parameters are of different data types when the number of parameters is the same (Rule 2) public void myMethod(int x, int y) { ... } public void myMethod(int x) { ... } Rule 1 Notice that the difference in the return type alone is not enough to overload the methods. For example, the following declaration is invalid public double convert(int num) { } public float convert(int num) { } public void myMethod(double x) { ... } public void myMethod(int x) { ... } Rule 2 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
291
Overloaded Constructor
Intro to OOP with Java, C. Thomas Wu Overloaded Constructor The same rules apply for overloaded constructors this is how we can define more than one constructor to a class public Person( ) { ... } public Person(int age) { ... } Rule 1 Notice that the difference in the return type alone is not enough to overload the methods. For example, the following declaration is invalid public double convert(int num) { } public float convert(int num) { } public Pet(int age) { ... } public Pet(String name) { ... } Rule 2 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
292
Intro to OOP with Java, C. Thomas Wu
Constructors and this public Fraction( ) { //creates 0/1 this(0. 1); } public Fraction(int number) { //creates number/1 this(number, 1); public Fraction(Fraction frac) { //copy constructor this(frac.getNumerator(), frac.getDenominator()); public Fraction(int num, int denom) { setNumerator(num); setDenominator(denom); To call a constructor from another constructor of the same class, we use the reserved word this. Without using the reserved word this, we need to define the four constructors as follows (it forces us to repeat the same code): public Fraction( ) { //creates 0/1 setNumerator(0); setDenominator(1); } public Fraction(int number) { //creates number/1 setNumerator(number); public Fraction(Fraction frac) { //copy constructor setNumerator(frac.getNumerator()); setDenominator(frac.getDenominator()); public Fraction(int num, int denom) { setNumerator(num); setDenominator(denom); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
293
Class Methods We use the reserved word static to define a class method. public static int gcd(int m, int n) { //the code implementing the Euclidean algorithm } public static Fraction min(Fraction f1, Fraction f2) { //convert to decimals and then compare ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
294
Call-by-Value Parameter Passing
When a method is called, the value of the argument is passed to the matching parameter, and separate memory space is allocated to store this value. This way of passing the value of arguments is called a pass-by-value or call-by-value scheme. Since separate memory space is allocated for each parameter during the execution of the method, the parameter is local to the method, and therefore changes made to the parameter will not affect the value of the corresponding argument. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
295
Call-by-Value Example
class Tester { public void myMethod(int one, double two ) { one = 25; two = 35.4; } Tester tester; int x, y; tester = new Tester(); x = 10; y = 20; tester.myMethod(x, y); System.out.println(x + " " + y); 10 20 produces ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
296
Memory Allocation for Parameters
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
297
Memory Allocation for Parameters (cont'd)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
298
Parameter Passing: Key Points
1. Arguments are passed to a method by using the pass-by- value scheme. 2. Arguments are matched to the parameters from left to right.The data type of an argument must be assignment-compatible with the data type of the matching parameter. 3. The number of arguments in the method call must match the number of parameters in the method definition. 4. Parameters and arguments do not have to have the same name. 5. Local copies, which are distinct from arguments,are created even if the parameters and arguments share the same name. 6. Parameters are input to a method, and they are local to the method.Changes made to the parameters will not affect the value of corresponding arguments. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
299
Organizing Classes into a Package
For a class A to use class B, their bytecode files must be located in the same directory. This is not practical if we want to reuse programmer-defined classes in many different programs The correct way to reuse programmer-defined classes from many different programs is to place reusable classes in a package. A package is a Java class library. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
300
Creating a Package The following steps illustrate the process of creating a package name myutil that includes the Fraction class. 1. Include the statement package myutil; as the first statement of the source file for the Fraction class. 2. The class declaration must include the visibility modifier public as public class Fraction { ... } 3. Create a folder named myutil, the same name as the package name. In Java, the package must have a one-to-one correspondence with the folder. 4. Place the modified Fraction class into the myutil folder and compile it. 5. Modify the CLASSPATH environment variable to include the folder that contains the myutil folder. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
301
Using Javadoc Comments
Many of the programmer-defined classes we design are intended to be used by other programmers. It is, therefore, very important to provide meaningful documentation to the client programmers so they can understand how to use our classes correctly. By adding javadoc comments to the classes we design, we can provide a consistent style of documenting the classes. Once the javadoc comments are added to a class, we can generate HTML files for documentation by using the javadoc command. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
302
javadoc for Fraction This is a portion of the HTML documentation for the Fraction class shown in a browser. This HTML file is produced by processing the javadoc comments in the source file of the Fraction class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
303
javadoc Tags The javadoc comments begins with /** and ends with */
Special information such as the authors, parameters, return values, and others are indicated by marker @param @author @return etc ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
304
Example: javadoc Source
Intro to OOP with Java, C. Thomas Wu Example: javadoc Source . . . /** * Returns the sum of this Fraction * and the parameter frac. The sum * returned is NOT simplified. * frac the Fraction to add to this * Fraction the sum of this and frac */ public Fraction add(Fraction frac) { ... } this javadoc will produce In the command prompt window, we used the commands javac and java to compile and run Java programs, respectively. Similarly, to generate javadoc files, we use the javadoc command. For example, to generate a javadoc file for the Fraction class, we enter javadoc -private Fraction.java We specify the -private option because we want to generate the documentation for all types of methods (so far, we have covered two of these—private and public). The private option generates the most complete documentation. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
305
Example: javadoc Output
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
306
javadoc Resources General information on javadoc is located at
Detailed reference on how to use javadoc on Windows is located at ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
307
Intro to OOP with Java, C. Thomas Wu
Problem Statement Problem statement: Write an application that computes the total charges for the overdue library books. For each library book, the user enters the due date and (optionally) the overdue charge per day,the maximum charge, and the title. If the optional values are not entered, then the preset default values are used. A complete list of book information is displayed when the user finishes entering the input data.The user can enter different return dates to compare the overdue charges. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
308
Intro to OOP with Java, C. Thomas Wu
Overall Plan Tasks: Get the information for all books Display the entered book information Ask for the return date and display the total charge. Repeat this step until the user quits. As a part of the overall plan, we begin by identifying the main tasks for the program. Unlike the overall plan for the previous sample developments, we will use a pseudo code to express the top level logic of the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
309
Intro to OOP with Java, C. Thomas Wu
Required Classes Scanner OverdueChecker BookTracker LibraryBook The structure of this program is very simple. We will use two standard classes, one for input and output and another for generating random numbers. helper class ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
310
Intro to OOP with Java, C. Thomas Wu
Development Steps We will develop this program in five steps: 1. Define the basic LibraryBook class. 2. Explore the given BookTracker class and integrate it with the LibraryBook class. 3. Define the top-level OverdueChecker class. Implement the complete input routines. 4. Complete the LibraryBook class by fully implementing the overdue charge computation. 5. Finalize the program by tying up loose ends. The second and the third steps correspond to the two major tasks identified in the overall plan. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
311
Intro to OOP with Java, C. Thomas Wu
Step 1 Design Develop the basic LibraryBook class. The key design task is to identify the data members for storing relevant information. We will include multiple constructors for ease of creating LibraryBook objects. Make sure that an instance will be initiated correctly no matter which constructor is used. In the first step, we determine a little more detailed control logic than the one stated in the overall plan. For each of the five identified functions, we will define a method: describeRules, generateSecretNumber, playGame, and prompt. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
312
Intro to OOP with Java, C. Thomas Wu
Step 1 Code Directory: Chapter7/Step1 Source Files: LibraryBook.java Step1Main.java (test program) Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Please use your Java IDE to view the source files and run the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
313
Intro to OOP with Java, C. Thomas Wu
Step 1 Test In the testing phase, we run the test main program Step1Main and confirm that we get the expected output: Run the program and verify that the topmost control loop is functioning correctly. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
314
Intro to OOP with Java, C. Thomas Wu
Step 2 Design Explore the helper BookTracker class and incorporate it into the program. Adjust the LibraryBook class to make it compatible with the BookTracker class. In order to verify whether our code is working correctly or not, we need to know what is the secret number. The easiest way to do this is to use a fixed number, such as 45, make the temporary generateRandomNumber to return this fixed number. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
315
Intro to OOP with Java, C. Thomas Wu
Step 2 Code Directory: Chapter7/Step2 Source Files: LibraryBook.java Step2Main.java (test program) We implement the playGame and getNextGuess methods in this step. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
316
Intro to OOP with Java, C. Thomas Wu
Step 2 Test In the testing phase, we run the test main program Step2Main and confirm that we get the expected output. We run the program multiple times trying different variations each time. We need to verify the correctness of two methods: playGame and getNextGuess. Try all cases presented here and confirm that you get the expected responses. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
317
Intro to OOP with Java, C. Thomas Wu
Step 3 Design We implement the top-level control class OverdueChecker. The top-level controller manages a single BookTracker object and multiple LibraryBook objects. The top-level controller manages the input and output routines If the input and output routines are complex, then we would consider designing separate classes to delegate the I/O tasks. Notice that we have one temporary statement to output the value of secretNumber. We include it for the testing purpose, i.e., we need to check the numbers generated are valid. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
318
Intro to OOP with Java, C. Thomas Wu
Step 3 Pseudocode GregorianCalendar returnDate; String reply, table; double totalCharge; inputBooks(); //read in all book information table = bookTracker.getList(); System.out.println(table); //try different return dates do { returnDate = read return date ; totalCharge = bookTracker.getCharge(returnDate); displayTotalCharge(totalCharge); reply = prompt the user to continue or not; } while ( reply is yes ); The body of the inputBooks method is as follows: while (isContinue()) { title = readString("Title : "); chargePerDay = readDouble("Charge per day: "); maxCharge = readDouble("Maximum charge: "); dueDate = readDate ("Due Date : "); book = createBook(title, chargePerDay, maxCharge, dueDate); bookTracker.add(book); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
319
Intro to OOP with Java, C. Thomas Wu
Step 3 Code Directory: Chapter7/Step3 Source Files: OverdueChecker.java LibraryBook.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
320
Intro to OOP with Java, C. Thomas Wu
Step 3 Test Now we run the program multiple times, trying different input types and values. We confirm that all control loops are implemented and working correctly. At this point, the code to compute the overdue charge is still a stub, so we will always get the same overdue charge for the same number of books. After we verify that everything is working as expected,we proceed to the next step. As always, we run the final test by running the program numerous times trying out as many variations as possible. Before testing the generateSecretNumber method as a part of the final program, we will use a separate test driver to generate 1000 (or more) secret numbers and verify that they are valid. class TestRandom { public static void main (String[] args) { int N = 1000, count = 0, number; double X; do { count++; X = Math.random(); number = (int) Math.floor( X * 100 ) + 1; } while ( count < N && 1 <= number && number <= 100 ); if ( number < 1 || number > 100 ) { System.out.println("Error: " + number); } else { System.out.println("Okay"); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
321
Step 4: Compute the Charge
Intro to OOP with Java, C. Thomas Wu Step 4: Compute the Charge To compute the overdue charge, we need two dates: the due date and the date the books are or to be returned. The getTimeInMillis method returns the time elasped since the epoch to the date in milliseconds. By subtracting this since-the-epoch milliseconds value of the due date from the same of the return date, we can find the difference between the two. If the difference is negative, then it’s not past due, so there’s no charge. If the difference is positive, then we convert the milliseconds to the equivalent number of days and multiply it by the per-day charge to compute the total charge. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
322
Intro to OOP with Java, C. Thomas Wu
Step 4 Code Directory: Chapter7/Step3 Source Files: OverdueChecker.java LibraryBook.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
323
Intro to OOP with Java, C. Thomas Wu
Step 4 Test We run the program mutiple times again, possibly using the same set of input data. We enter different input variations to try out all possible cases for the computeCharge method. Try cases such as the return date and due date are the same, the return date occurs before the due date, the charge is beyond the maximum, and so forth. After we verify the program,we move on to the next step. As always, we run the final test by running the program numerous times trying out as many variations as possible. Before testing the generateSecretNumber method as a part of the final program, we will use a separate test driver to generate 1000 (or more) secret numbers and verify that they are valid. class TestRandom { public static void main (String[] args) { int N = 1000, count = 0, number; double X; do { count++; X = Math.random(); number = (int) Math.floor( X * 100 ) + 1; } while ( count < N && 1 <= number && number <= 100 ); if ( number < 1 || number > 100 ) { System.out.println("Error: " + number); } else { System.out.println("Okay"); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
324
Step 5: Finalize / Extend
Intro to OOP with Java, C. Thomas Wu Step 5: Finalize / Extend Program Review Are all the possible cases handled? Are the input routines easy to use? Will it be better if we allow different formats for entering the date information? Possible Extensions Warn the user, say, by popping a warning window or ringing an alarm, when the due date is approaching. Provide a special form window to enter data (Note: To implement these extensions, we need techniques not covered yet.) ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
325
Intro to OOP with Java, C. Thomas Wu Exceptions and Assertions
Chapter 8 Exceptions and Assertions ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
326
Intro to OOP with Java, C. Thomas Wu
Objectives After you have read and studied this chapter, you should be able to Improve the reliability of code by incorporating exception-handling and assertion mechanisms. Write methods that propagate exceptions. Implement the try-catch blocks for catching and handling exceptions. Write programmer-defined exception classes. Distinguish the checked and unchecked, or runtime, exceptions. ©The McGraw-Hill Companies, Inc.
327
Intro to OOP with Java, C. Thomas Wu
Definition An exception represents an error condition that can occur during the normal course of program execution. When an exception occurs, or is thrown, the normal sequence of flow is terminated. The exception-handling routine is then executed; we say the thrown exception is caught. We can increase our programs’ reliability and robustness if we catch the exceptions ourselves using error recovery routines we develop. One way to do this is to wrap the statements that may throw an exception with the try-catch control statement. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
328
Not Catching Exceptions
Intro to OOP with Java, C. Thomas Wu Not Catching Exceptions String inputStr; int age; inputStr = JOptionPane.showInputDialog(null, "Age:"); age = Integer.parseInt(inputStr); Error message for invalid input Consider the given example. What would happen if the user enters a value such as the text 'ten' instead of 10? The parseInt method cannot convert such an input to an internal numerical format. This type of error is called an exception, and it will result in displaying an error message such as the one shown here. We say the parseInt method has thrown a NumberFormatException. java.lang.NumberFormatException: ten at java.lang.Integer.parseInt(Integer.java:405) at java.lang.Integer.parseInt(Integer.java:454) at Ch8Sample1.main(Ch8Sample1.java:20) ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
329
Intro to OOP with Java, C. Thomas Wu
Catching an Exception inputStr = JOptionPane.showInputDialog(null, "Age:"); try { age = Integer.parseInt(inputStr); } catch (NumberFormatException e){ JOptionPane.showMessageDialog(null, "’" + inputStr + "‘ is invalid\n" + "Please enter digits only"); } try catch This example shows a way to handle a thrown exception in our code, instead of letting the system handle it, as in the previous example. If any statement inside the try block throws an exception, then the statements in the matching catch block are executed. And the program continues the execution from the statement that follows this try-catch statement. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
330
try-catch Control Flow
Intro to OOP with Java, C. Thomas Wu try-catch Control Flow This illustrates how the control flows when there is an exception and when there is no exception. In the case when no statements in the try block throw an exception, then the catch block is skipped and execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
331
Intro to OOP with Java, C. Thomas Wu
Getting Information There are two methods we can call to get information about the thrown exception: getMessage printStackTrace try { . . . } catch (NumberFormatException e){ System.out.println(e.getMessage()); System.out.println(e.printStackTrace()); } In the previous example, we simply displayed a fixed error message. We can get display a more generic error message by using the getMessage or printStrackTrace methods. We will experiment with these methods in the lab. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
332
Intro to OOP with Java, C. Thomas Wu
Multiple catch Blocks A single try-catch statement can include multiple catch blocks, one for each type of exception. try { . . . age = Integer.parseInt(inputStr); val = cal.get(id); //cal is a GregorianCalendar } catch (NumberFormatException e){ } catch (ArrayIndexOutOfBoundsException e){ } In this example, we see two statements in the try block that can potentially throw exceptions. The parseInt method throws a NumberFormatException while the get method throws an ArrayIndexOutOfBoundsException when the argument id is outside the range of valid values. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
333
Multiple catch Control Flow
Intro to OOP with Java, C. Thomas Wu Multiple catch Control Flow Here's how the control flows when there are multiple catch blocks. In the case when no statements in the try block throw an exception, then all catch blocks are skipped and execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the matching catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
334
Intro to OOP with Java, C. Thomas Wu
The finally Block There are situations where we need to take certain actions regardless of whether an exception is thrown or not. We place statements that must be executed regardless of exceptions in the finally block. The finally block is not used often in introductory level programs, but we will introduce them here for the sake of complete coverage of the topic. For example, suppose we open a communication channel from our Java program to a remote web server to exchange data. If the data exchange is successfully completed in the try block, then we close the communication channel and finish the operation. If the data exchange is interrupted for some reason, an exception is thrown and the operation is aborted. In this case also, we need to close the communication channel, because leaving the channel open by one application blocks other applications from using it. The code to close the communication channel should therefore be placed in the finally block. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
335
try-catch-finally Control Flow
Intro to OOP with Java, C. Thomas Wu try-catch-finally Control Flow Here's how the control flows when there are multiple catch blocks and the finally block. In the case when no statements in the try block throw an exception, then all catch blocks are skipped, but the statements in the finally block are executed. Execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the matching catch block are executed first and the statements in the finally block are executed next. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
336
Propagating Exceptions
Intro to OOP with Java, C. Thomas Wu Propagating Exceptions Instead of catching a thrown exception by using the try-catch statement, we can propagate the thrown exception back to the caller of our method. The method header includes the reserved word throws. public int getAge( ) throws NumberFormatException { . . . int age = Integer.parseInt(inputStr); return age; } Using the try-catch statement is the first way to handle the exceptions. The second way is to propagate the thrown exception back to the caller of the method. The method that includes the statement that calls our method must either catch it or propagate it back to their caller. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
337
Intro to OOP with Java, C. Thomas Wu
Throwing Exceptions We can write a method that throws an exception directly, i.e., this method is the origin of the exception. Use the throw reserved to create a new instance of the Exception or its subclasses. The method header includes the reserved word throws. public void doWork(int num) throws Exception { . . . if (num != val) throw new Exception("Invalid val"); } It is possible to throw an exception from our own method. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
338
Intro to OOP with Java, C. Thomas Wu
Exception Thrower When a method may throw an exception, either directly or indirectly, we call the method an exception thrower. Every exception thrower must be one of two types: catcher. propagator. We say a method throws an exception directly when the method includes the throw statement. Otherwise, a method is throwing an exception indirectly. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
339
Types of Exception Throwers
Intro to OOP with Java, C. Thomas Wu Types of Exception Throwers An exception catcher is an exception thrower that includes a matching catch block for the thrown exception. An exception propagator does not contain a matching catch block. A method may be a catcher of one exception and a propagator of another. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
340
Intro to OOP with Java, C. Thomas Wu
Sample Call Sequence This illustration shows a sequence of method calls among the exception throwers. Method D throws an instance of Exception. The green arrows indicate the direction of calls. The red arrows show the reversing of call sequence, looking for a matching catcher. Method B is the catcher. The call sequence is traced by using a stack. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
341
Intro to OOP with Java, C. Thomas Wu
Exception Types All types of thrown errors are instances of the Throwable class or its subclasses. Serious errors are represented by instances of the Error class or its subclasses. Exceptional cases that common applications should handle are represented by instances of the Exception class or its subclasses. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
342
Intro to OOP with Java, C. Thomas Wu
Throwable Hierarchy There are over 60 classes in the hierarchy. The classes shown here are some of the more common classes in the Throwable class hierarchy. We will be seeing most of the Exception and its subclasses shown here in the later modules. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
343
Intro to OOP with Java, C. Thomas Wu
Checked vs. Runtime There are two types of exceptions: Checked. Unchecked. A checked exception is an exception that is checked at compile time. All other exceptions are unchecked, or runtime, exceptions. As the name suggests, they are detected only at runtime. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
344
Different Handling Rules
Intro to OOP with Java, C. Thomas Wu Different Handling Rules When calling a method that can throw checked exceptions use the try-catch statement and place the call in the try block, or modify the method header to include the appropriate throws clause. When calling a method that can throw runtime exceptions, it is optional to use the try-catch statement or modify the method header to include a throws clause. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
345
Handling Checked Exceptions
Intro to OOP with Java, C. Thomas Wu Handling Checked Exceptions Callers of a method that can throw a checked exception must include the try-catch statement in the method body or the throws clause in the header. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
346
Handling Runtime Exceptions
Intro to OOP with Java, C. Thomas Wu Handling Runtime Exceptions It is optional for callers of a method that can throw runtime exceptions to include the try-catch statement in the method body or the throws clause in the header. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
347
Programmer-Defined Exceptions
Intro to OOP with Java, C. Thomas Wu Programmer-Defined Exceptions Using the standard exception classes, we can use the getMessage method to retrieve the error message. By defining our own exception class, we can pack more useful information for example, we may define a OutOfStock exception class and include information such as how many items to order AgeInputException is defined as a subclass of Exception and includes public methods to access three pieces of information it carries: lower and upper bounds of valid age input and the (invalid) value entered by the user. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
348
Intro to OOP with Java, C. Thomas Wu
Assertions The syntax for the assert statement is assert <boolean expression>; where <boolean expression> represents the condition that must be true if the code is working correctly. If the expression results in false, an AssertionError (a subclass of Error) is thrown. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
349
Intro to OOP with Java, C. Thomas Wu
Sample Use #1 public double deposit(double amount) { double oldBalance = balance; balance += amount; assert balance > oldBalance; } public double withdraw(double amount) { balance -= amount; assert balance < oldBalance; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
350
Intro to OOP with Java, C. Thomas Wu
Second Form The assert statement may also take the form: assert <boolean expression>: <expression>; where <expression> represents the value passed as an argument to the constructor of the AssertionError class. The value serves as the detailed message of a thrown exception. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
351
Intro to OOP with Java, C. Thomas Wu
Sample Use #2 public double deposit(double amount) { double oldBalance = balance; balance += amount; assert balance > oldBalance : "Serious Error – balance did not " + " increase after deposit"; } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
352
Compiling Programs with Assertions
Intro to OOP with Java, C. Thomas Wu Compiling Programs with Assertions Before Java 2 SDK 1.4, the word assert is a valid nonreserved identifier. In version 1.4 and after, the word assert is treated as a regular identifier to ensure compatibility. To enable the assertion mechanism, compile the source file using javac –source 1.4 <source file> ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
353
Running Programs with Assertions
Intro to OOP with Java, C. Thomas Wu Running Programs with Assertions To run the program with assertions enabled, use java –ea <main class> If the –ea option is not provided, the program is executed without checking assertions. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
354
Different Uses of Assertions
Intro to OOP with Java, C. Thomas Wu Different Uses of Assertions Precondition assertions check for a condition that must be true before executing a method. Postcondition assertions check conditions that must be true after a method is executed. A control-flow invariant is a third type of assertion that is used to assert the control must flow to particular cases. We will be seeing examples of using assertions in the sample programs later. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
355
Intro to OOP with Java, C. Thomas Wu
Problem Statement Problem statement: Implement a Keyless Entry System that asks for three pieces of information: resident’s name, room number, and a password. A password is a sequence of characters ranging in length from 4 to 8 and is unique to an individual dorm resident. If everything matches, then the system unlocks and opens the door. We assume no two residents have the same name. We use the provided support classes Door and Dorm. Sample resident data named samplelist.dat can be used for development. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
356
Intro to OOP with Java, C. Thomas Wu
Overall Plan Tasks: To begin our development effort, we must first find out the capabilities of the Dorm and Door classes. Also, for us to implement the class correctly, we need the specification of the Resident class. In addition to the given helper classes and the Resident class, we need to design other classes for this application. As the number of classes gets larger, we need to plan the classes carefully. For this application, we are given two helper classes. In order to use the Dorm class, we must supply the Resident class whose specification is already set so it works correctly with the given Dorm class. The relationship between the Dorm and Resident is similar to the one between the DrawingBoard and the DrawableShape classes. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
357
Intro to OOP with Java, C. Thomas Wu
Design Document Class Purpose Ch8EntranceMonitor The top-level control object that manages other objects in the program. This is an instantiable main class. Door The given predefined class that simulates the opening of a door. Dorm The given predefined class that maintains a list of Resident objects. Resident This class maintains information on individual dorm residents. Specification for this class is provided to us. InputHandler The user interface class for handling input routines. JOptionPane The standard class for displaying messages. There will be a total of six key classes in this application. We will be designing three classes: Ch8EntranceMonitor, Resident, and InputFrame. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
358
Intro to OOP with Java, C. Thomas Wu
Class Relationships InputFrame Ch8EntranceMonitor Dorm (main class) JOptionPane Door Resident Most relationships follow the client-service pattern, except the one between the InputFrame and Ch8EntranceMonitor follows the supervisor-subordinate pattern. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
359
Intro to OOP with Java, C. Thomas Wu
Development Steps We will develop this program in three steps: Define the Resident class and explore the Dorm class. Start with a program skeleton to test the Resident class. Define the user interface InputHandler class. Modify the top-level control class as necessary. Finalize the code by making improvements and tying up loose ends. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
360
Intro to OOP with Java, C. Thomas Wu
Step 1 Design Explore the Dorm class Implement the Resident class, following the given specification Start with the skeleton main class ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
361
Intro to OOP with Java, C. Thomas Wu
Step 1 Code Directory: Chapter8/Step1 Source Files: Resident.java Ch8EntranceMonitor.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Please use your Java IDE to view the source files and run the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
362
Intro to OOP with Java, C. Thomas Wu
Step 1 Test The purpose of Step 1 testing is to verify that the Dorm class is used correctly to open a file and get the contents of the file. To test it, we need a file that contains the resident information. A sample test file called testfile.dat is provided for testing purpose. This file contains information on four residents. This file was created by executing the SampleCreateResidentFile program, which you can modify to create other test data files. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
363
Intro to OOP with Java, C. Thomas Wu
Step 2 Design Design and implement the InputHandler class. Modify the main class to incorporate the new class. . ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
364
Intro to OOP with Java, C. Thomas Wu
Step 2 Code Directory: Chapter8/Step2 Source Files: Resident.java Ch8EntranceMonitor.java InputHandler.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
365
Intro to OOP with Java, C. Thomas Wu
Step 2 Test The purpose of Step 2 testing is to verify the correct behavior of an InputHandler. We need to test both successful and unsuccessful cases. We must verify that the door is in fact opened when the valid information is entered. We must also verify that the error message is displayed when there’s an error in input. We should test invalid cases such as entering nonexistent name, corrent name but wrong password, not enetering all information, and so forth. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
366
Intro to OOP with Java, C. Thomas Wu
Step 3: Finalize Possible Extensions Improve the user interface with a customized form window for entering three pieces of information. Terminate the program when the administrator enters a special code ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
367
Intro to OOP with Java, C. Thomas Wu Characters and Strings
Chapter 9 Characters and Strings ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
368
Intro to OOP with Java, C. Thomas Wu
Objectives After you have read and studied this chapter, you should be able to Declare and manipulate data of the char data type. Write string processing program using String, StringBuilder, and StringBuffer objects. Differentiate the three string classes and use the correct class for a given task. Specify regular expressions for searching a pattern in a string. Use the Pattern and Matcher classes. Compare the String objects correctly. We will cover the basic string processing in this lesson, manipulating char and String data. ©The McGraw-Hill Companies, Inc.
369
Intro to OOP with Java, C. Thomas Wu
Characters In Java, single characters are represented using the data type char. Character constants are written as symbols enclosed in single quotes. Characters are stored in a computer memory using some form of encoding. ASCII, which stands for American Standard Code for Information Interchange, is one of the document coding schemes widely used today. Java uses Unicode, which includes ASCII, for representing char constants. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
370
Intro to OOP with Java, C. Thomas Wu
ASCII Encoding For example, character 'O' is 79 (row value 70 + col value 9 = 79). O 9 70 Characters can be stored in a computer memory using the ASCII encoding. The ASCII codes range from 0 to 127. The character 'A' is represented as 65, for example. The ASCII values from 0 to 32 are called nonprintable control characters. For example, ASCII code 04 eot stands for End of Transmission. We can use this character to signal the end of transmission of data when sending data over a communication line. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
371
Intro to OOP with Java, C. Thomas Wu
Unicode Encoding The Unicode Worldwide Character Standard (Unicode) supports the interchange, processing, and display of the written texts of diverse languages. Java uses the Unicode standard for representing char constants. char ch1 = 'X'; System.out.println(ch1); System.out.println( (int) ch1); ASCII works well for English-language documents because all characters and punctuation marks are included in the ASCII codes. But ASCII codes cannot be used to represent character sets of other languages. To overcome this limitation, unicode encoding was proposed. Unicode uses two bytes to represent characters and adopts the same encoding for the first 127 values as the ASCII codes. Encoding value of a character can be accessed by converting it to an int as the sample code illustrates. X 88 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
372
Intro to OOP with Java, C. Thomas Wu
Character Processing Declaration and initialization char ch1, ch2 = ‘X’; Type conversion between int and char. System.out.print("ASCII code of character X is " + (int) 'X' ); System.out.print("Character with ASCII code 88 is " + (char)88 ); This comparison returns true because ASCII value of 'A' is 65 while that of 'c' is 99. ‘A’ < ‘c’ ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
373
Intro to OOP with Java, C. Thomas Wu
Strings A string is a sequence of characters that is treated as a single value. Instances of the String class are used to represent strings in Java. We can access individual characters of a string by calling the charAt method of the String object. We introduced the String class in Chapter 2. We will study additional String methods. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
374
Accessing Individual Elements
Intro to OOP with Java, C. Thomas Wu Accessing Individual Elements Individual characters in a String accessed with the charAt method. String name = "Sumatra"; 1 2 3 4 5 6 S u m a t r name This variable refers to the whole string. name.charAt( 3 ) The method returns the character at position # 3. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
375
Example: Counting Vowels
Intro to OOP with Java, C. Thomas Wu Example: Counting Vowels char letter; String name = JOptionPane.showInputDialog(null,"Your name:"); int numberOfCharacters = name.length(); int vowelCount = 0; for (int i = 0; i < numberOfCharacters; i++) { letter = name.charAt(i); if ( letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U' ) { vowelCount++; } System.out.print(name + ", your name has " + vowelCount + " vowels"); Here’s the code to count the number of vowels in the input string. This sample code counts the number of vowels in a given input. Using the toUpperCase method, that converts all alphabetic characters to uppercase, we can rewrite the code as char letter; String name = inputBox.getString("What is your name?"); int numberOfCharacters = name.length(); int vowelCount = 0; String nameUpper = name.toUpperCase(); for (int i = 0; i < numberOfCharacters; i++) { letter = nameUpper.charAt(i); if ( letter == 'A' || letter == 'E' || letter == 'I' || letter == 'O' || letter == 'U' ) { vowelCount++; } System.out.print(name + ", your name has " + vowelCount + " vowels"); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
376
Example: Counting ‘Java’
Intro to OOP with Java, C. Thomas Wu Example: Counting ‘Java’ int javaCount = 0; boolean repeat = true; String word; while ( repeat ) { word = JOptionPane.showInputDialog(null,"Next word:"); if ( word.equals("STOP") ) { repeat = false; } else if ( word.equalsIgnoreCase("Java") ) { javaCount++; } Continue reading words and count how many times the word Java occurs in the input, ignoring the case. Notice how the comparison is done. We are not using the == operator. This sample code counts the number of times the word 'Java' is entered. Notice that we wrote word.equals( “STOP”) not word == “STOP” We described the differences in Lesson 5-2. In this situation, we need to use 'equals' because we are testing whether two String objects have the same sequence of characters. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
377
Other Useful String Operators
Intro to OOP with Java, C. Thomas Wu Other Useful String Operators Method Meaning compareTo Compares the two strings. str1.compareTo( str2 ) substring Extracts the a substring from a string. str1.substring( 1, 4 ) trim Removes the leading and trailing spaces. str1.trim( ) valueOf Converts a given primitive data value to a string. String.valueOf( ) startsWith Returns true if a string starts with a specified prefix string. str1.startsWith( str2 ) endsWith Returns true if a string ends with a specified suffix string. str1.endsWith( str2 ) Here are some examples: String str1 = “Java”, str2 = “ Wow “; str1.compareTo( “Hello” ); //returns positive integer //because str1 >= “Hello” str1.substring( 1, 4 ); //returns “ava” str2.trim( ) //returns “Wow”, str2 stays same str1.startsWith( “Ja” ); //returns true str1.endsWith( “avi” ); //returns false See the String class documentation for details. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
378
Intro to OOP with Java, C. Thomas Wu
Pattern Example Suppose students are assigned a three-digit code: The first digit represents the major (5 indicates computer science); The second digit represents either in-state (1), out-of-state (2), or foreign (3); The third digit indicates campus housing: On-campus dorms are numbered 1-7. Students living off-campus are represented by the digit 8. The 3-digit pattern to represent computer science majors living on-campus is We can use a pattern to represent a range of valid codes succintly. Without using the sample 3-digit pattern for computer science majors living on-campus, we must spell out 21 separate codes. 5[123][1-7] first character is 5 second character is 1, 2, or 3 third character is any digit between 1 and 7 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
379
Intro to OOP with Java, C. Thomas Wu
Regular Expressions The pattern is called a regular expression. Rules The brackets [ ] represent choices The asterisk symbol * means zero or more occurrences. The plus symbol + means one or more occurrences. The hat symbol ^ means negation. The hyphen – means ranges. The parentheses ( ) and the vertical bar | mean a range of choices for multiple characters. Regular expression allows us to express a large set of “words” (any sequence of symbols) succinctly. We use specially designated symbols such as the asterisk to formulate regular expressions. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
380
Regular Expression Examples
Intro to OOP with Java, C. Thomas Wu Regular Expression Examples Expression Description [013] A single digit 0, 1, or 3. [0-9][0-9] Any two-digit number from 00 to 99. [0-9&&[^4567]] A single digit that is 0, 1, 2, 3, 8, or 9. [a-z0-9] A single character that is either a lowercase letter or a digit. [a-zA-z][a-zA-Z0-9_$]* A valid Java identifier consisting of alphanumeric characters, underscores, and dollar signs, with the first character being an alphabet. [wb](ad|eed) Matches wad, weed, bad, and beed. (AZ|CA|CO)[0-9][0-9] Matches AZxx,CAxx, and COxx, where x is a single digit. Here are some examples of regular expressions. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
381
Intro to OOP with Java, C. Thomas Wu
The replaceAll Method The replaceAll method replaces all occurrences of a substring that matches a given regular expression with a given replacement string. Replace all vowels with the String originalText, modifiedText; originalText = ...; //assign string modifiedText = ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
382
The Pattern and Matcher Classes
Intro to OOP with Java, C. Thomas Wu The Pattern and Matcher Classes The matches and replaceAll methods of the String class are shorthand for using the Pattern and Matcher classes from the java.util.regex package. If str and regex are String objects, then str.matches(regex); is equivalent to Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); matcher.matches(); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
383
Intro to OOP with Java, C. Thomas Wu
The compile Method The compile method of the Pattern class converts the stated regular expression to an internal format to carry out the pattern-matching operation. This conversion is carried out every time the matches method of the String class is executed, so it is more efficient to use the compile method when we search for the same pattern multiple times. See the sample programs Ch9MatchJavaIdentifier2 and Ch9PMCountJava ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
384
Intro to OOP with Java, C. Thomas Wu
The find Method The find method is another powerful method of the Matcher class. It searches for the next sequence in a string that matches the pattern, and returns true if the pattern is found. When a matcher finds a matching sequence of characters, we can query the location of the sequence by using the start and end methods. See Ch9PMCountJava2 The start method returns the position in the string where the first character of the pattern is found. The end method returns the value 1 more than the position in the string where the last character of the pattern is found. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
385
The String Class is Immutable
Intro to OOP with Java, C. Thomas Wu The String Class is Immutable In Java a String object is immutable This means once a String object is created, it cannot be changed, such as replacing a character with another character or removing a character The String methods we have used so far do not change the original string. They created a new string from the original. For example, substring creates a new string from a given string. The String class is defined in this manner for efficiency reason. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
386
Effect of Immutability
Intro to OOP with Java, C. Thomas Wu Effect of Immutability We can do this because String objects are immutable. By making String objects immutable, we can treat it much like a primitive data type for efficient processing. If we use the new operator to create a String object, a separate object is created as the top diagram illustrates. If we use a simple assignment as in the bottom diagram, then all literal constants refer to the same object. We can do this because String objects are immutable. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
387
The StringBuffer Class
Intro to OOP with Java, C. Thomas Wu The StringBuffer Class In many string processing applications, we would like to change the contents of a string. In other words, we want it to be mutable. Manipulating the content of a string, such as replacing a character, appending a string with another string, deleting a portion of a string, and so on, may be accomplished by using the StringBuffer class. If the situation calls for directing changing the contents of a string, then we use the StringBuffer class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
388
Intro to OOP with Java, C. Thomas Wu
StringBuffer Example word : StringBuffer Java Before word : StringBuffer Diva After Changing a string Java to Diva This sample code illustrates how the original string is changed. Notice that the String class does not include the setCharAt method. The method is only defined in the mutable StringBuffer class. StringBuffer word = new StringBuffer("Java"); word.setCharAt(0, 'D'); word.setCharAt(1, 'i'); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
389
Intro to OOP with Java, C. Thomas Wu
Sample Processing Replace all vowels in the sentence with ‘X’. char letter; String inSentence = JOptionPane.showInputDialog(null, "Sentence:"); StringBuffer tempStringBuffer = new StringBuffer(inSentence); int numberOfCharacters = tempStringBuffer.length(); for (int index = 0; index < numberOfCharacters; index++) { letter = tempStringBuffer.charAt(index); if ( letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U' ) { tempStringBuffer.setCharAt(index,'X'); } JOptionPane.showMessageDialog(null, tempStringBuffer ); Notice how the input routine is done. We are reading in a String object and converting it to a StringBuffer object, because we cannot simply assign a String object to a StringBuffer variable. For example, the following code is invalid: StringBuffer strBuffer = inputBox.getString( ); We are required to create a StringBuffer object from a String object as in String str = "Hello"; StringBuffer strBuf = new StringBuffer( str ); You cannot input StringBuffer objects. You have to input String objects and convert them to StringBuffer objects. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
390
The append and insert Methods
Intro to OOP with Java, C. Thomas Wu The append and insert Methods We use the append method to append a String or StringBuffer object to the end of a StringBuffer object. The method can also take an argument of the primitive data type. Any primitive data type argument is converted to a string before it is appended to a StringBuffer object. We can insert a string at a specified position by using the insert method. The append and insert are the two very useful methods of the StringBuffer class for string manipulation. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
391
The StringBuilder Class
Intro to OOP with Java, C. Thomas Wu The StringBuilder Class This class is new to Java 5.0 (SDK 1.5) The class is added to the newest version of Java to improve the performance of the StringBuffer class. StringBuffer and StringBuilder support exactly the same set of methods, so they are interchangeable. There are advanced cases where we must use StringBuffer, but all sample applications in the book, StringBuilder can be used. Since the performance is not our main concern and that the StringBuffer class is usable for all versions of Java, we will use StringBuffer only in this book. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
392
Intro to OOP with Java, C. Thomas Wu
Problem Statement Problem statement: Write an application that will build a word concordance of a document. The output from the application is an alphabetical list of all words in the given document and the number of times they occur in the document. The documents are a text file (contents of the file are an ASCII characters) and the output of the program is saved as an ASCII file also. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
393
Intro to OOP with Java, C. Thomas Wu
Overall Plan Tasks expressed in pseudocode: while ( the user wants to process another file ) { Task 1: read the file; Task 2: build the word list; Task 3: save the word list to a file; } For this application, we are given two helper classes. The FileManager class handles the file input and output. The WordList class handles the maintenance of word lists. Our responsibility is to extract the words from a given document and use the helper classes correctly. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
394
Intro to OOP with Java, C. Thomas Wu
Design Document Class Purpose Ch9WordConcordanceMain The instantiable main class of the program that implements the top-level program control. Ch9WordConcordance The key class of the program. An instance of this class managers other objects to build the word list. FileManager A helper class for opening a file and saving the result to a file. Details of this class can be found in Chapter 12. WordList Another helper class for maintaining a word list. Details of this class can be found in Chapter 10. Pattern/Matcher Classes for pattern matching operations. There will be a total of six key classes in this application. We will be designing two classes: Ch9WordConcordanceMain and Ch9WordConcordance. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
395
Intro to OOP with Java, C. Thomas Wu
Class Relationships FileManger WordList Ch9Word ConcordanceMain (main class) Ch9Word Concordance Pattern Matcher class we implement helper class given to us ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
396
Intro to OOP with Java, C. Thomas Wu
Development Steps We will develop this program in four steps: Start with a program skeleton. Define the main class with data members. Begin with a rudimentary Ch9WordConcordance class. Add code to open a file and save the result. Extend the existing classes as necessary. Complete the implemention of the Ch9WordConcordance class. Finalize the code by removing temporary statements and tying up loose ends. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
397
Intro to OOP with Java, C. Thomas Wu
Step 1 Design Define the skeleton main class Define the skeleton Ch9WordConcordance class that has only an empty zero-argument constructor ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
398
Intro to OOP with Java, C. Thomas Wu
Step 1 Code Directory: Chapter9/Step1 Source Files: Ch9WordConcordanceMain.java Ch9WordConcordance.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Please use your Java IDE to view the source files and run the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
399
Intro to OOP with Java, C. Thomas Wu
Step 1 Test The purpose of Step 1 testing is to verify that the constructor is executed correctly and the repetition control in the start method works as expected. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
400
Intro to OOP with Java, C. Thomas Wu
Step 2 Design Design and implement the code to open and save a file The actual tasks are done by the FileManager class, so our objective in this step is to find out the correct usage of the FileManager helper class. The FileManager class has two key methods: openFile and saveFile. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
401
Intro to OOP with Java, C. Thomas Wu
Step 2 Code Directory: Chapter9/Step2 Source Files: Ch9WordConcordanceMain.java Ch9WordConcordance.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
402
Intro to OOP with Java, C. Thomas Wu
Step 2 Test The Step2 directory contains several sample input files. We will open them and verify the file contents are read correctly by checking the temporary echo print output to System.out. To verify the output routine, we save to the output (the temporary output created by the build method of Ch9WordConcordance) and verify its content. Since the output is a textfile, we can use any word processor or text editor to view its contents. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
403
Intro to OOP with Java, C. Thomas Wu
Step 3 Design Complete the build method of Ch9WordConcordance class. We will use the second helper class WordList here, so we need to find out the details of this helper class. The key method of the WordList class is the add method that inserts a given word into a word list. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
404
Intro to OOP with Java, C. Thomas Wu
Step 3 Code Directory: Chapter9/Step3 Source Files: Ch9WordConcordanceMain.java Ch9WordConcordance.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
405
Intro to OOP with Java, C. Thomas Wu
Step 3 Test We run the program against varying types of input textfiles. We can use a long document such as the term paper for the last term’s economy class (don’t forget to save it as a textfile before testing). We should also use some specially created files for testing purposes. One file may contain one word repeated 7 times, for example. Another file may contain no words at all. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
406
Intro to OOP with Java, C. Thomas Wu
Step 4: Finalize Possible Extensions One is an integrated user interface where the end user can view both the input document files and the output word list files. Another is the generation of different types of list. In the sample development, we count the number of occurences of each word. Instead, we can generate a list of positions where each word appears in the document. For the second extension, the WordList class itself needs to be modified. Details on how to implement this extension can be found in Chapter 10 of the textbook. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
407
Chapter 10 Arrays ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
408
Intro to OOP with Java, C. Thomas Wu
Objectives After you have read and studied this chapter, you should be able to Manipulate a collection of data values, using an array. Declare and use an array of primitive data types in writing a program. Declare and use an array of objects in writing a program Define a method that accepts an array as its parameter and a method that returns an array Describe how a two-dimensional array is implemented as an array of arrays Manipulate a collection of objects, using lists and maps We will cover the basic array processing in this lesson, manipulating arrays of primitive data types and objects. ©The McGraw-Hill Companies, Inc.
409
Intro to OOP with Java, C. Thomas Wu
Array Basics An array is a collection of data values. If your program needs to deal with 100 integers, 500 Account objects, 365 real numbers, etc., you will use an array. In Java, an array is an indexed collection of data values of the same type. Suppose you need to handle up to 300 Student objects in a program for maintaining a high school alumni list, would you use 300 variables? Suppose you need to process daily temperatures for a 12-month period in a science project, would you use 365 variables? You can, but would you? To manipulate a collection of data, we can use arrays. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
410
Arrays of Primitive Data Types
Intro to OOP with Java, C. Thomas Wu Arrays of Primitive Data Types Array Declaration <data type> [ ] <variable> //variation 1 <data type> <variable>[ ] //variation 2 Array Creation <variable> = new <data type> [ <size> ] Example double[ ] rainfall; rainfall = new double[12]; Variation 1 double rainfall [ ]; rainfall = new double[12]; Variation 2 As you can declare and create objects in one statement such as Person p = new Person( ); you can declare and create an array in one statement as double[ ] rainfall = new double[12]; Strictly speaking, an array is a reference data type and really an object because there is no class called Array in Java. The thumbnail note in page 413 is therefore not 100 percent accurate. An array is like an object! ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
411
Accessing Individual Elements
Intro to OOP with Java, C. Thomas Wu Accessing Individual Elements Individual elements in an array accessed with the indexed expression. double[] rainfall = new double[12]; rainfall 1 2 3 4 5 6 7 8 9 10 11 rainfall[2] This indexed expression refers to the element at position #2 The index of the first position in an array is 0. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
412
Array Processing – Sample1
Intro to OOP with Java, C. Thomas Wu Array Processing – Sample1 double[] rainfall = new double[12]; double annualAverage, sum = 0.0; for (int i = 0; i < rainfall.length; i++) { rainfall[i] = Double.parseDouble( JOptionPane.showinputDialog(null, "Rainfall for month " + (i+1) ) ); sum += rainfall[i]; } annualAverage = sum / rainfall.length; The public constant length returns the capacity of an array. This code computes the average annual rainfall. Notice the public constant length returns the capacity, not the actual number of non-blank values in the array. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
413
Array Processing – Sample 2
Intro to OOP with Java, C. Thomas Wu Array Processing – Sample 2 double[] rainfall = new double[12]; String[] monthName = new String[12]; monthName[0] = "January"; monthName[1] = "February"; … double annualAverage, sum = 0.0; for (int i = 0; i < rainfall.length; i++) { rainfall[i] = Double.parseDouble( JOptionPane.showinputDialog(null, "Rainfall for " monthName[i] )); sum += rainfall[i]; } annualAverage = sum / rainfall.length; The same pattern for the remaining ten months. This code also computes the average annual rainfall, but this time we use the second array, an arrray of String so the prompt becomes "Rainfall for January", "Rainfall for February", and so forth. Notice how the monthName array is used in the for loop. The actual month name instead of a number. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
414
Array Processing – Sample 3
Intro to OOP with Java, C. Thomas Wu Array Processing – Sample 3 Compute the average rainfall for each quarter. //assume rainfall is declared and initialized properly double[] quarterAverage = new double[4]; for (int i = 0; i < 4; i++) { sum = 0; for (int j = 0; j < 3; j++) { //compute the sum of sum += rainfall[3*i + j]; //one quarter } quarterAverage[i] = sum / 3.0; //Quarter (i+1) average This code computes the average rainfall for each quarter. The inner loop is used to compute the rainfall for a given quarter. The outer loop processes the four quarters. This is how the values for i, j, and 3*i+j change: i j 3*i+j 0 0 0 1 1 2 2 1 0 3 1 4 2 5 2 0 6 1 7 2 8 1 10 2 11 The sample code is equivalent to for (int i = 0; i < 3; i++ ) { quarterAverage[0] += rainfall[i]; quarterAverage[1] += rainfall[i+3]; quarterAverage[2] += rainfall[i+6]; quarterAverage[3] += rainfall[i+9]; } quarterAverage[0] = quarterAverage[0] / 3.0; quarterAverage[1] = quarterAverage[1] / 3.0; quarterAverage[2] = quarterAverage[2] / 3.0; quarterAverage[3] = quarterAverage[3] / 3.0; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
415
Intro to OOP with Java, C. Thomas Wu
Array Initialization Like other data types, it is possible to declare and initialize an array at the same time. int[] number = { 2, 4, 6, 8 }; double[] samplingData = { 2.443, 8.99, 12.3, , 18.2, 9.00, 3.123, , }; String[] monthName = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; When an array is initialized in this manner, its capacity is set to the number of elements in the list. number.length samplingData.length monthName.length 4 9 12 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
416
Variable-size Declaration
Intro to OOP with Java, C. Thomas Wu Variable-size Declaration In Java, we are not limited to fixed-size array declaration. The following code prompts the user for the size of an array and declares an array of designated size: int size; int[] number; size= Integer.parseInt(JOptionPane.showInputDialog(null, "Size of an array:")); number = new int[size]; Instead of declaring the array size to a fixed value, it is possible to declare its size at the runtime. For example, we can prompt the user for the size of an array as illustrated in the sample code shown here. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
417
Intro to OOP with Java, C. Thomas Wu
Arrays of Objects In Java, in addition to arrays of primitive data types, we can declare arrays of objects An array of primitive data is a powerful tool, but an array of objects is even more powerful. The use of an array of objects allows us to model the application more cleanly and logically. By combining the power of arrays and objects, we can structure programs in a clean, logical manner. Without an array of objects, to represent a collection of Account objects, for example, we need to use several different arrays, one for names, one for addresses, and so forth. This is very cumbersome and error-prone. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
418
Intro to OOP with Java, C. Thomas Wu
The Person Class We will use Person objects to illustrate the use of an array of objects. Person latte; latte = new Person( ); latte.setName("Ms. Latte"); latte.setAge(20); latte.setGender('F'); System.out.println( "Name: " + latte.getName() ); System.out.println( "Age : " + latte.getAge() ); System.out.println( "Sex : " + latte.getGender() ); The Person class supports the set methods and get methods. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
419
Creating an Object Array - 1
Intro to OOP with Java, C. Thomas Wu Creating an Object Array - 1 Code Person[ ] person; person = new Person[20]; person[0] = new Person( ); A Only the name person is declared, no array is allocated yet. After is executed A person State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
420
Creating an Object Array - 2
Intro to OOP with Java, C. Thomas Wu Creating an Object Array - 2 Code Person[ ] person; person = new Person[20]; person[0] = new Person( ); Now the array for storing 20 Person objects is created, but the Person objects themselves are not yet created. B person After is executed B 1 2 3 4 16 17 18 19 person State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
421
Creating an Object Array - 3
Intro to OOP with Java, C. Thomas Wu Creating an Object Array - 3 Code Person[ ] person; person = new Person[20]; person[0] = new Person( ); One Person object is created and the reference to this object is placed in position 0. C 1 2 3 4 16 17 18 19 person 1 2 3 4 16 17 18 19 person After is executed C Person State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
422
Person Array Processing – Sample 1
Intro to OOP with Java, C. Thomas Wu Person Array Processing – Sample 1 Create Person objects and set up the person array. String name, inpStr; int age; char gender; for (int i = 0; i < person.length; i++) { name = inputBox.getString("Enter name:"); //read in data values age = inputBox.getInteger("Enter age:"); inpStr = inputBox.getString("Enter gender:"); gender = inpStr.charAt(0); person[i] = new Person( ); //create a new Person and assign values person[i].setName ( name ); person[i].setAge ( age ); person[i].setGender( gender ); } The indexed expression person[i] is used to refer to the (i+1)st object in the person array. Since this expression refers to an object, we write person[i].setAge( 20 ); to call this Person object’s setAge method, for example. This is the syntax we use to call an object’s method. We are just using an indexed expression to refer to an object instead of a simple variable. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
423
Person Array Processing – Sample 2
Intro to OOP with Java, C. Thomas Wu Person Array Processing – Sample 2 Find the youngest and oldest persons. int minIdx = 0; //index to the youngest person int maxIdx = 0; //index to the oldest person for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < person[minIdx].getAge() ) { minIdx = i; //found a younger person } else if (person[i].getAge() > person[maxIdx].getAge() ) { maxIdx = i; //found an older person } //person[minIdx] is the youngest and person[maxIdx] is the oldest Here’s another approach with two Person variables: Person youngest, //points to the youngest person oldest; //points to the oldest person youngest = oldest = person[0]; for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < youngest.getAge() ) { youngest = person[i]; //found a younger person } else if ( person[i].getAge() > oldest.getAge() ) { oldest = person[i]; //found an older person outputBox.printLine("Oldest : " + oldest.getName() + " is " + oldest.getAge() + " years old."); outputBox.printLine("Youngest: " + youngest.getName() + " is " + youngest.getAge() + " years old."); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
424
Object Deletion – Approach 1
Intro to OOP with Java, C. Thomas Wu Object Deletion – Approach 1 int delIdx = 1; person[delIdx] = null; Delete Person B by setting the reference in position 1 to null. A 1 2 3 person A B C D 1 2 3 person A C D Before is executed After is executed In this approach, we simply leave the position of a deleted object to a null. With this approach, an array index positions will be a mixture of null and real pointers. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
425
Object Deletion – Approach 2
Intro to OOP with Java, C. Thomas Wu Object Deletion – Approach 2 int delIdx = 1, last = 3; person[delIndex] = person[last]; person[last] = null; Delete Person B by setting the reference in position 1 to the last person. A 1 2 3 person A B C D 1 2 3 person A C D Before is executed After is executed With the second approach, we divide the array into two parts: the first part contains the real references and the second part contains the null references. When we delete a node, a hole will result and we must fill this hole. There are two possible solutions. The first solution is to pack the elements. If an object at position J is removed (i.e., this position is set to null), then elements from position J+1 till the last non-null reference are shifted one position lower. And, finally, the last non-null reference is set to null. The second solution is to replace the removed element by the last element in the array. The first solution is necessary if the Person objects are arranged in some order (e.g., in ascending order of age). The second solution is a better one if the Person objects are not arranged in any order. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
426
Person Array Processing – Sample 3
Intro to OOP with Java, C. Thomas Wu Person Array Processing – Sample 3 Searching for a particular person. Approach 2 Deletion is used. int i = 0; while ( person[i] != null && !person[i].getName().equals("Latte") ) { i++; } if ( person[i] == null ) { //not found - unsuccessful search System.out.println("Ms. Latte was not in the array"); } else { //found - successful search System.out.println("Found Ms. Latte at position " + i); Here’s another approach with two Person variables: Person youngest, //points to the youngest person oldest; //points to the oldest person youngest = oldest = person[0]; for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < youngest.getAge() ) { youngest = person[i]; //found a younger person } else if ( person[i].getAge() > oldest.getAge() ) { oldest = person[i]; //found an older person System.out.println("Oldest : " + oldest.getName() + " is " + oldest.getAge() + " years old."); System.out.println("Youngest: " + youngest.getName() + " is " + youngest.getAge() + " years old."); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
427
Passing Arrays to Methods - 1
Intro to OOP with Java, C. Thomas Wu Passing Arrays to Methods - 1 Code A public int searchMinimum(float[] number)) { … } minOne = searchMinimum(arrayOne); At before searchMinimum A arrayOne A. Local variable number does not exist before the method execution When an array is passed to a method, only its reference is passed. A copy of the array is NOT created in the method. public int searchMinimum(float[] number) { int indexOfMinimum = 0; for (int i = 1; i < number.length; i++) { if (number[i] < number[indexOfMinimum]) { //found a indexOfMinimum = i; //smaller element } return indexOfMinimum; State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
428
Passing Arrays to Methods - 2
Intro to OOP with Java, C. Thomas Wu Passing Arrays to Methods - 2 Code public int searchMinimum(float[] number)) { … } B minOne = searchMinimum(arrayOne); arrayOne The address is copied at B number arrayOne B. The value of the argument, which is an address, is copied to the parameter. State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
429
Passing Arrays to Methods - 3
Intro to OOP with Java, C. Thomas Wu Passing Arrays to Methods - 3 Code public int searchMinimum(float[] number)) { … } C minOne = searchMinimum(arrayOne); arrayOne number While at inside the method C C. The array is accessed via number inside the method. State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
430
Passing Arrays to Methods - 4
Intro to OOP with Java, C. Thomas Wu Passing Arrays to Methods - 4 Code public int searchMinimum(float[] number)) { … } minOne = searchMinimum(arrayOne); D arrayOne number arrayOne At after searchMinimum D D. The parameter is erased. The argument still points to the same object. State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
431
Two-Dimensional Arrays
Intro to OOP with Java, C. Thomas Wu Two-Dimensional Arrays Two-dimensional arrays are useful in representing tabular information. In Java, data may be organized in a two-dimensional array. A table is an example of a two-dimensional array. In a two-dimensional array, two indices (in a table, one for the row and one for the column) are used to refer to the array element. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
432
Declaring and Creating a 2-D Array
Intro to OOP with Java, C. Thomas Wu Declaring and Creating a 2-D Array Declaration <data type> [][] <variable> //variation 1 <data type> <variable>[][] //variation 2 Creation <variable> = new <data type> [ <size1> ][ <size2> ] Example 3 2 1 4 payScaleTable payScaleTable = new double[4][5]; is really a shorthand for payScaleTable = new double[4][ ]; payScaleTable[0] = new double[5]; payScaleTable[1] = new double[5]; payScaleTable[2] = new double[5]; payScaleTable[3] = new double[5]; which is equivalent to for (int i = 0; i < 4; i++) { payScaleTable[i] = new double[5]; } double[][] payScaleTable; payScaleTable = new double[4][5]; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
433
Intro to OOP with Java, C. Thomas Wu
Accessing an Element An element in a two-dimensional array is accessed by its row and column index. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
434
Sample 2-D Array Processing
Intro to OOP with Java, C. Thomas Wu Sample 2-D Array Processing Find the average of each row. double[ ] average = { 0.0, 0.0, 0.0, 0.0 }; for (int i = 0; i < payScaleTable.length; i++) { for (int j = 0; j < payScaleTable[i].length; j++) { average[i] += payScaleTable[i][j]; } average[i] = average[i] / payScaleTable[i].length; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
435
Java Implementation of 2-D Arrays
Intro to OOP with Java, C. Thomas Wu Java Implementation of 2-D Arrays The sample array creation payScaleTable = new double[4][5]; is really a shorthand for payScaleTable = new double [4][ ]; payScaleTable[0] = new double [5]; payScaleTable[1] = new double [5]; payScaleTable[2] = new double [5]; payScaleTable[3] = new double [5]; The concept of the two-dimensional array in Java is just that: a concept. There is no explicit structure called the “two-dimensional array” in Java. The two-dimensional array concept is implemented by using an array of arrays. ©The McGraw-Hill Companies, Inc.
436
10.5 Two-Dimensional Arrays
Intro to OOP with Java, C. Thomas Wu 10.5 Two-Dimensional Arrays Subarrays may be different lengths. Executing triangularArray = new double[4][ ]; for (int i = 0; i < 4; i++) triangularArray[i] = new double [i + 1]; results in an array that looks like: An array that is part of another array is called a subarray. An array of arrays may be initialized when it is created. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
437
Intro to OOP with Java, C. Thomas Wu
Lists and Maps The java.util standard package contains different types of classes for maintaining a collection of objects. These classes are collectively referred to as the Java Collection Framework (JCF). JCF includes classes that maintain collections of objects as sets, lists, or maps. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
438
Intro to OOP with Java, C. Thomas Wu
Java Interface A Java interface defines only the behavior of objects It includes only public methods with no method bodies. It does not include any data members except public constants No instances of a Java interface can be created One Java interface we have seen is the ActionListener interface. The declaration for an interface includes the reserved word 'interface'. In the declaration, we list the method headers (i.e. a method without body) only. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
439
Intro to OOP with Java, C. Thomas Wu
JCF Lists JCF includes the List interface that supports methods to maintain a collection of objects as a linear list L = (l0, l1, l2, , lN) We can add to, remove from, and retrieve objects in a given list. A list does not have a set limit to the number of objects we can add to it. A list being linear means the object, or elements, in the list are positioned in a linear sequence. That is, l0 is the first element, l1 is the second element, and so forth. A list has not size limit; there is no set limit to the number of elements we can add to a list. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
440
Intro to OOP with Java, C. Thomas Wu
List Methods Here are five of the 25 list methods: boolean add ( Object o ) Adds an object o to the list void clear ( ) Clears this list, i.e., make the list empty Object get ( int idx ) Returns the element at position idx boolean remove ( int idx ) Removes the element at position idx int size ( ) Returns the number of elements in the list There are total of 25 methods defined in the List interface. The five listed here are the very frequently used subset of those 25 methods. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
441
Intro to OOP with Java, C. Thomas Wu
Using Lists To use a list in a program, we must create an instance of a class that implements the List interface. Two classes that implement the List interface: ArrayList LinkedList The ArrayList class uses an array to manage data. The LinkedList class uses a technique called linked-node representation. Because both the ArrayList and LinkedList classes implement the same interface, we know that instances of ArrayList and LinkedList behave the same way, i.e., they support the same set of public methods defined in the List interface. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
442
Intro to OOP with Java, C. Thomas Wu
Sample List Usage Here's an example of manipulating a list: import java.util.*; List friends; Person person; friends = new ArrayList( ); person = new Person("jane", 10, 'F'); friends.add( person ); person = new Person("jack", 6, 'M'); Person p = (Person) friends.get( 1 ); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
443
Intro to OOP with Java, C. Thomas Wu
JCF Maps JCF includes the Map interface that supports methods to maintain a collection of objects (key, value) pairs called map entries. key value k0 k1 kn v0 v1 vn . one entry We can add to, remove from, and retrieve objects in a given list. A list does not have a set limit to the number of objects we can add to it. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
444
Intro to OOP with Java, C. Thomas Wu
Map Methods Here are five of the 14 list methods: void clear ( ) Clears this list, i.e., make the map empty boolean containsKey ( Object key ) Returns true if the map contains an entry with a given key Object put (Object key, Object value) Adds the given (key, value) entry to the map boolean remove ( Object key ) Removes the entry with the given key from the map int size ( ) Returns the number of elements in the map There are total of 14 methods defined in the List interface. The five listed here are the very frequently used subset of these 14 methods. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
445
Intro to OOP with Java, C. Thomas Wu
Using Maps To use a map in a program, we must create an instance of a class that implements the Map interface. Two classes that implement the Map interface: HashMap TreeMap ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
446
Intro to OOP with Java, C. Thomas Wu
Sample Map Usage Here's an example of manipulating a map: import java.util.*; Map catalog; catalog = new TreeMap( ); catalog.put("CS101", "Intro Java Programming"); catalog.put("CS301", "Database Design"); catalog.put("CS413", "Software Design for Mobile Devices"); if (catalog.containsKey("CS101")) { System.out.println("We teach Java this semester"); } else { System.out.println("No Java courses this semester"); } The (key, value) pair for this sample map is the course number and the course title, respectively. ©The McGraw-Hill Companies, Inc.
447
Intro to OOP with Java, C. Thomas Wu
Problem Statement Problem statement: Write an AddressBook class that manages a collection of Person objects. An AddressBook object will allow the programmer to add, delete, or search for a Person object in the address book. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
448
Overall Plan / Design Document
Intro to OOP with Java, C. Thomas Wu Overall Plan / Design Document Since we are designing a single class, our task is to identify the public methods. Public Method Purpose AddressBook A constructor to initialize the object. We will include multiple constructors as necessary. add Adds a new Person object to the address book. delete Deletes a specified Person object from the address book. search Searches a specified Person object in the address book and returns this person if found. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
449
Intro to OOP with Java, C. Thomas Wu
Development Steps We will develop this program in five steps: Implement the constructor(s). Implement the add method. Implement the search method. Implement the delete method. Finalize the class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
450
Intro to OOP with Java, C. Thomas Wu
Step 1 Design Start the class definition with two constructors The zero-argument constructor will create an array of default size The one-argument constructor will create an array of the specified size ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
451
Intro to OOP with Java, C. Thomas Wu
Step 1 Code Directory: Chapter10/Step1 Source Files: AddressBook.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Please use your Java IDE to view the source files and run the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
452
Intro to OOP with Java, C. Thomas Wu
Step 1 Test The purpose of Step 1 testing is to verify that the constructors work as expected. Argument to Constructor Purpose Negative numbers Test the invalid data. Test the end case of invalid data. 1 Test the end case of valid data. >= 1 Test the normal cases. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
453
Intro to OOP with Java, C. Thomas Wu
Step 2 Design Design and implement the add method The array we use internal to the AddressBook class has a size limit, so we need consider the overflow situation Alternative 1: Disallow adds when the capacity limit is reached Alternative 2: Create a new array of bigger size We will adopt Alternative 2 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
454
Intro to OOP with Java, C. Thomas Wu
Step 2 Code Directory: Chapter10/Step2 Source Files: AddressBook.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
455
Intro to OOP with Java, C. Thomas Wu
Step 2 Test The purpose of Step 2 test is to confirm that objects are added correctly and the creation of a bigger array takes place when an overflow situation occurs. Test Sequence Purpose Create the array of size 4 Test that the array is created correctly. Add four Person objects Test that the Person objects are added correctly. Add the fifth Person object Test that the new array is created and the Person object is added correctly (to the new array). ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
456
Intro to OOP with Java, C. Thomas Wu
Step 3 Design Design and implement the search method. loc = 0; while ( loc < count && name of Person at entry[loc] is not equal to the given search name ) { loc++; } if (loc == count) { foundPerson = null; } else { foundPerson = entry[loc]; return foundPerson; Here's the pseudocode to locate a person with the designated name. Notice that for this routine to work correctly, the array must be packed with the real pointers in the first half and null pointers in the last half. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
457
Intro to OOP with Java, C. Thomas Wu
Step 3 Code Directory: Chapter10/Step3 Source Files: AddressBook.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
458
Intro to OOP with Java, C. Thomas Wu
Step 3 Test To test the correct operation of the search method, we need to carry out test routines much more elaborate than previous tests. Test Sequence Purpose Create the array of size 5 and add five Person objects with unique names. Test that the array is created and set up correctly. Here, we will test the case where the array is 100 percent filled. Search for the person in the first position of the array Test that the successful search works correctly for the end case. Search for the person in the last position of the array Test another version of the end case. Search for a person somewhere in the middle of the array. Test the normal case. Search for a person not in the array. Test for the unsuccessful search. Repeat the above steps with an array of varying sizes, especially the array of size 1. Test that the routine works correctly for arrays of different sizes. Repeat the testing with the cases where the array is not fully filled, say, array length is 5 and the number of objects in the array is 0 or 3. Test that the routine works correctly for other cases. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
459
Intro to OOP with Java, C. Thomas Wu
Step 4 Design Design and implement the delete method. boolean status; int loc; loc = findIndex( searchName ); if ( loc is not valid ) { status = false; } else { //found, pack the hole replace the element at index loc+1 by the last element at index count; status = true; count--; //decrement count, since we now have one less element assert 'count' is valid; } return status; Here's the pseudocode to delete a person with the designated name. First we locate the person. If the person is not found, we exit the delete routine. If the person is found, then we remove it and fill the hole. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
460
Intro to OOP with Java, C. Thomas Wu
Step 4 Code Directory: Chapter10/Step4 Source Files: AddressBook.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
461
Intro to OOP with Java, C. Thomas Wu
Step 4 Test To test the correct operation of the delete method, we need to carry out a detailed test routine. Test Sequence Purpose Create the array of size 5 and add five Person objects with unique names. Test the array is created and set up correctly. Here, we will test the case where the array is 100 percent filled. Search for a person to be deleted next. Verify that the person is in the array before deletion. Delete the person in the array Test that the delete method works correctly. Search for the deleted person. Test that the delete method works correctly by checking the value null is returned by the search. Attempt to delete a nonexisting person. Test that the unsuccessful operation works correctly. Repeat the above steps by deleting persons at the first and last positions. Test that the routine works correctly for arrays of different sizes. Repeat testing where the array is not fully filled, say, an array length is 5 and the number of objects in the array is 0 or 3. Test that the routine works correctly for other cases. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
462
Intro to OOP with Java, C. Thomas Wu
Step 5: Finalize Final Test Since the three operations of add, delete, and search are interrelated, it is critical to test these operations together. We try out various combinations of add, delete, and search operations. Possible Extensions One very useful extension is scanning. Scanning is an operation to visit all elements in the collection. Scanning is useful in listing all Person objects in the address book. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
463
Chapter 11 Sorting and Searching
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
464
Intro to OOP with Java, C. Thomas Wu
Chapter 10 Objectives After you have read and studied this chapter, you should be able to Perform linear and binary search algorithms on small arrays. Determine whether a linear or binary search is more effective for a given situation. Perform selection and bubble sort algorithms. Describe the heapsort algorithm and show how its performance is superior to the other two algorithms. Apply basic sorting algorithms to sort an array of objects. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
465
Intro to OOP with Java, C. Thomas Wu
Searching When we maintain a collection of data, one of the operations we need is a search routine to locate desired data quickly. Here’s the problem statement: Given a value X, return the index of X in the array, if such X exists. Otherwise, return NOT_FOUND (-1). We assume there are no duplicate entries in the array. We will count the number of comparisons the algorithms make to analyze their performance. The ideal searching algorithm will make the least possible number of comparisons to locate the desired data. Two separate performance analyses are normally done, one for successful search and another for unsuccessful search. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
466
Intro to OOP with Java, C. Thomas Wu
Search Result Unsuccessful Search: NOT_FOUND search( 45 ) Successful Search: search( 12 ) 4 number 23 17 5 90 12 44 38 1 2 3 4 6 7 8 84 77 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
467
Intro to OOP with Java, C. Thomas Wu
Linear Search Search the array from the first to the last position in linear progression. public int linearSearch ( int[] number, int searchValue ) { int loc = 0; while (loc < number.length && number[loc] != searchValue) { loc++; } if (loc == number.length) { //Not found return NOT_FOUND; } else { return loc; //Found, return the position ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
468
Linear Search Performance
Intro to OOP with Java, C. Thomas Wu Linear Search Performance We analyze the successful and unsuccessful searches separately. We count how many times the search value is compared against the array elements. Successful Search Best Case – 1 comparison Worst Case – N comparisons (N – array size) Unsuccessful Search Best Case = Worst Case – N comparisons Note: In the case of unsuccessful search, all elements in the array are compared against the search value, so the total number of comparisons is N. However, the actual number of times the while loop is executed is N+1 because we need one more go around to determine that loc becomes equal to number.length. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
469
Intro to OOP with Java, C. Thomas Wu
Binary Search If the array is sorted, then we can apply the binary search technique. The basic idea is straightforward. First search the value in the middle position. If X is less than this value, then search the middle of the left half next. If X is greater than this value, then search the middle of the right half next. Continue in this manner. number 5 12 17 23 38 44 77 1 2 3 4 6 7 8 84 90 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
470
Sequence of Successful Search - 1
Intro to OOP with Java, C. Thomas Wu Sequence of Successful Search - 1 low high mid search( 44 ) 0 8 #1 high low mid 4 5 12 17 23 38 44 77 1 2 3 4 6 7 8 84 90 38 < 44 low = mid+1 = 5 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
471
Sequence of Successful Search - 2
Intro to OOP with Java, C. Thomas Wu Sequence of Successful Search - 2 low high mid search( 44 ) 0 8 #1 4 high low 5 8 #2 mid 6 5 12 17 23 38 44 77 1 2 3 4 6 7 8 84 90 high = mid-1=5 44 < 77 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
472
Sequence of Successful Search - 3
Intro to OOP with Java, C. Thomas Wu Sequence of Successful Search - 3 low high mid search( 44 ) 0 8 #1 4 5 8 #2 6 high low 5 5 #3 mid 5 5 12 17 23 38 44 77 1 2 3 4 6 7 8 84 90 Successful Search!! 44 == 44 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
473
Sequence of Unsuccessful Search - 1
Intro to OOP with Java, C. Thomas Wu Sequence of Unsuccessful Search - 1 low high mid search( 45 ) 0 8 #1 high low mid 4 5 12 17 23 38 44 77 1 2 3 4 6 7 8 84 90 38 < 45 low = mid+1 = 5 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
474
Sequence of Unsuccessful Search - 2
Intro to OOP with Java, C. Thomas Wu Sequence of Unsuccessful Search - 2 low high mid search( 45 ) 0 8 #1 4 high low 5 8 #2 mid 6 5 12 17 23 38 44 77 1 2 3 4 6 7 8 84 90 high = mid-1=5 45 < 77 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
475
Sequence of Unsuccessful Search - 3
Intro to OOP with Java, C. Thomas Wu Sequence of Unsuccessful Search - 3 low high mid search( 45 ) 0 8 #1 4 5 8 #2 6 high low 5 5 #3 mid 5 5 12 17 23 38 44 77 1 2 3 4 6 7 8 84 90 44 < 45 low = mid+1 = 6 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
476
Sequence of Unsuccessful Search - 4
Intro to OOP with Java, C. Thomas Wu Sequence of Unsuccessful Search - 4 low high mid search( 45 ) 0 8 #1 4 5 8 #2 6 5 5 #3 5 high low 6 5 #4 5 12 17 23 38 44 77 1 2 3 4 6 7 8 84 90 Unsuccessful Search no more elements to search low > high ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
477
Intro to OOP with Java, C. Thomas Wu
Binary Search Routine public int binarySearch (int[] number, int searchValue) { int low = 0, high = number.length - 1, mid = (low + high) / 2; while (low <= high && number[mid] != searchValue) { if (number[mid] < searchValue) { low = mid + 1; } else { //number[mid] > searchValue high = mid - 1; } mid = (low + high) / 2; //integer division will truncate if (low > high) { mid = NOT_FOUND; return mid; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
478
Binary Search Performance
Intro to OOP with Java, C. Thomas Wu Binary Search Performance Successful Search Best Case – 1 comparison Worst Case – log2N comparisons Unsuccessful Search Best Case = Since the portion of an array to search is cut into half after every comparison, we compute how many times the array can be divided into halves. After K comparisons, there will be N/2K elements in the list. We solve for K when N/2K = 1, deriving K = log2N. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
479
Comparing N and log2N Performance
Intro to OOP with Java, C. Thomas Wu Comparing N and log2N Performance Array Size Linear – N Binary – log2N Note: The value of log2N is a real number. Since the number of comparisons done is an integer, the result of log2N is rounded up to an integer in the third column. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
480
Intro to OOP with Java, C. Thomas Wu
Sorting When we maintain a collection of data, many applications call for rearranging the data in certain order, e.g. arranging Person information in ascending order of age. Here’s the problem statement: Given an array of N integer values, arrange the values into ascending order. We will count the number of comparisons the algorithms make to analyze their performance. The ideal sorting algorithm will make the least possible number of comparisons to arrange data in a designated order. We will compare different sorting algorithms by analyzing their worst-case performance. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
481
Intro to OOP with Java, C. Thomas Wu
Selection Sort first exchange min Find the smallest element in the list. Exchange the element in the first position and the smallest element. Now the smallest element is in the first position. Repeat Step 1 and 2 with the list having one less element (i.e., the smallest element is discarded from further processing). 1 2 3 4 5 6 7 8 23 17 90 12 44 38 84 77 1 2 3 4 5 6 7 8 17 23 90 12 44 38 84 77 sorted unsorted This is the result of one pass. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
482
Intro to OOP with Java, C. Thomas Wu
Selection Sort Passes 1 Pass # 1 2 3 4 5 6 7 8 17 23 90 12 44 38 84 77 sorted Result AFTER one pass is completed. 2 5 12 23 90 17 44 38 84 77 3 5 12 17 90 23 44 38 84 77 The figure shows the whole eight passes. The illustration for each pass shows the state right BEFORE the exchange was made for that pass. The illustrations in the slide show the state AFTER the exchange was made for that pass. 7 5 12 17 23 38 44 77 84 90 8 5 12 17 23 38 44 77 84 90 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
483
Selection Sort Routine
Intro to OOP with Java, C. Thomas Wu Selection Sort Routine public void selectionSort(int[] number) { int startIndex, minIndex, length, temp; length = number.length; for (startIndex = 0; startIndex <= length-2; startIndex++){ //each iteration of the for loop is one pass minIndex = startIndex; //find the smallest in this pass at position minIndex for (int i = startIndex+1; i <= length-1; i++) { if (number[i] < number[minIndex]) minIndex = i; } //exchange number[startIndex] and number[minIndex] temp = number[startIndex]; number[startIndex] = number[minIndex]; number[minIndex] = temp; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
484
Selection Sort Performance
Intro to OOP with Java, C. Thomas Wu Selection Sort Performance We derive the total number of comparisons by counting the number of times the inner loop is executed. For each execution of the outer loop, the inner loop is executed length – start times. The variable length is the size of the array. Replacing length with N, the array size, the sum is derived as… ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
485
Intro to OOP with Java, C. Thomas Wu
Bubble Sort With the selection sort, we make one exchange at the end of one pass. The bubble sort improves the performance by making more than one exchange during its pass. By making multiple exchanges, we will be able to move more elements toward their correct positions using the same number of comparisons as the selection sort makes. The key idea of the bubble sort is to make pairwise comparisons and exchange the positions of the pair if they are out of order. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
486
Intro to OOP with Java, C. Thomas Wu
One Pass of Bubble Sort 1 2 3 4 5 6 7 8 23 17 90 12 44 38 84 77 17 5 23 12 44 90 38 84 77 exchange exchange 17 23 5 90 12 44 38 84 77 17 5 23 12 44 38 90 84 77 exchange exchange 17 5 23 90 12 44 38 84 77 17 5 23 12 44 38 84 90 77 exchange What is the meaning behind the name “bubble” sort? Notice the effect of one pass is to migrate the largest element to the last position of the array. In addition, because we are exchanging the pairs if they are out of order, other elements migrate toward the end of the array. If we view the array vertically with the first position at the bottom and the last position at the top, the data movements we see is like bubbles moving toward the surface of water. ok exchange 17 5 23 12 90 44 38 84 77 17 5 23 12 44 38 84 77 90 exchange The largest value 90 is at the end of the list. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
487
Intro to OOP with Java, C. Thomas Wu
Bubble Sort Routine public void bubbleSort(int[] number) { int temp, bottom, i; boolean exchanged = true; bottom = number.length - 2; while (exchanged) { exchanged = false; for (i = 0; i <= bottom; i++) { if (number[i] > number[i+1]) { temp = number[i]; //exchange number[i] = number[i+1]; number[i+1] = temp; exchanged = true; //exchange is made } bottom--; The bubble sort routine is implemented by exploiting the following two properties: 1. After one pass through the array, the largest element will be at the end of the array. 2. During one pass, if no pair of consecutive entries is out of order, then the array is sorted. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
488
Bubble Sort Performance
Intro to OOP with Java, C. Thomas Wu Bubble Sort Performance In the worst case, the outer while loop is executed N-1 times for carrying out N-1 passes. For each execution of the outer loop, the inner loop is executed bottom+1 times. The number of comparisons in each successive pass is N-1, N-2, … , 1. Summing these will result in the total number of comparisons. So the performances of the bubble sort and the selection sort are approximately equivalent. However, on the average, the bubble sort performs much better than the selection sort because it can finish the sorting without doing all N-1 passes. The selection sort will carry out N-1 passes no matter what. Whether the array is already sorted or very close to being sorted does not matter to the selection sort. It will carry out the same number of comparisons in sorting a given array. The bubble sort, on the other hand, can detect if the array is or has become sorted during the sorting process. So the bubble sort is adaptable, it does fewer comparisons for the arrays that are closer to being sorted than those that are not. In addition to the larger number of data movements during a single pass, the capability of checking the “sortedness” of the array enables the bubble sort routine to complete the whole sorting process much quicker than the selection sort. Indeed, the only situation that causes the bubble sort routine to execute the worst case number of comparisons is when the original array is in the reverse order (i.e., in descending order). ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
489
Intro to OOP with Java, C. Thomas Wu
Heapsort Selection and bubble sorts are two fundamental sorting algorithms that take approximately N2 comparisons to sort an array of N elements. One sorting algorithm that improves the performance to approximately 1.5Nlog2N is called heapsort. The heapsort algorithm uses a special data structure called a heap. A heap structure can be implemented very effectively by using an array. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
490
Intro to OOP with Java, C. Thomas Wu
Sample Heap Level # 1 2 3 4 90 84 44 12 5 38 77 17 23 1 2 3 4 6 7 8 root index We use integers as data values for the examples in this section. The topmost node is called the root of a heap. Nodes in a heap are indexed 0, 1, 2, and so forth in the top-to-bottom, left-to-right order starting from the root. A node in a heap has either zero, one, or two children. The children of a node are distinguished as the node’s left and right children. If a node has only one child, then it is the left child of the node. left child of 44 right child of 44 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
491
Intro to OOP with Java, C. Thomas Wu
Heap Constraints A heap must satisfy the following two constraints: Structural Constraint: Nodes in a heap with N nodes must occupy the positions numbered 0, 1, ..., N-1. Value Relationship Constraint: A value stored in a node must be larger than the maximum of the values stored in its left and right children. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
492
Structural Constraints
Intro to OOP with Java, C. Thomas Wu Structural Constraints Sample heaps and nonheaps that violate the structural constraints: Heaps Nonheaps ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
493
Value Relationship Constraints
Intro to OOP with Java, C. Thomas Wu Value Relationship Constraints Sample heaps and nonheaps that violate the value relationship constraints: Heaps 45 25 16 3 12 22 45 12 34 11 22 9 90 35 24 13 16 12 Nonheaps 45 55 16 3 12 58 45 25 33 34 23 22 45 25 55 3 12 22 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
494
Intro to OOP with Java, C. Thomas Wu
Heapsort Algorithm How can we use the heap structure to sort N elements? Heapsort is carried out in two phases: Construction Phase: Construct a heap with given N elements. Extraction Phase: Pull out the value in the root successively, creating a new heap with one less element after each extraction. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
495
Intro to OOP with Java, C. Thomas Wu
Extraction Phase After each extraction, a heap must be rebuilt with one less element. One sample extraction step: 90 84 44 12 5 38 77 17 23 1 2 3 4 6 7 8 84 77 44 12 5 38 23 17 1 2 3 4 6 7 8 90 84 23 44 12 5 38 77 17 1 2 3 4 6 7 8 90 84 77 44 12 5 38 23 17 1 2 3 4 6 7 8 90 23 84 44 12 5 38 77 17 1 2 3 4 6 7 8 90 90 84 44 12 5 38 77 17 23 1 2 3 4 6 7 8 90 90 23 > max{84, 44}? 23 > max{77, 12}? 23 > max{17}? NO, so swap. NO, so swap. YES, so stop. Before After ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
496
Intro to OOP with Java, C. Thomas Wu
Rebuild Steps A sequence of rebuild steps to sort the list. 90 84 44 12 5 38 77 17 23 1 2 3 4 6 7 8 Before 5 1 2 3 4 6 7 8 90 84 77 44 38 23 17 12 38 23 5 12 17 1 2 3 4 6 7 8 90 84 77 44 23 17 5 12 1 2 3 4 6 7 8 90 84 77 44 38 17 12 5 1 2 3 4 6 7 8 90 84 77 44 38 23 12 5 1 2 3 4 6 7 8 90 84 77 44 38 23 17 77 23 44 12 5 38 17 1 2 3 4 6 7 8 90 84 44 23 38 12 5 17 1 2 3 4 6 7 8 90 84 77 1 2 3 4 5 6 7 8 90 84 77 44 38 23 17 12 Done 90 84 44 12 5 38 77 17 23 1 2 3 4 6 7 8 84 77 44 12 5 38 23 17 1 2 3 4 6 7 8 90 5 12 17 23 38 44 77 84 90 5 12 17 23 38 90 77 84 44 Sorting was completed after 8 rebuild steps. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
497
Intro to OOP with Java, C. Thomas Wu
Construction Phase Rebuild steps are applied from position (N-2)/2 to position 0. 23 17 5 12 44 38 90 84 77 1 2 3 4 6 7 8 23 90 44 12 5 38 84 17 77 1 2 3 4 6 7 8 23 17 44 12 5 38 90 84 77 1 2 3 4 6 7 8 90 84 44 12 5 38 77 17 23 1 2 3 4 6 7 8 Done 23 17 5 12 44 38 90 84 77 1 2 3 4 6 7 8 23 17 5 12 44 38 90 84 77 1 2 3 4 6 7 8 3 (9-2)/2 = 3 1 2 Before ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
498
Intro to OOP with Java, C. Thomas Wu
Heap Implementation We need to implement the abstract data structure heap into a concrete data structure. 90 84 44 12 5 38 77 17 23 1 2 3 4 6 7 8 Abstract Heap Structure Concrete Implementation 1 2 3 4 5 6 7 8 23 17 38 12 77 44 84 90 The heap structure can be characterized as an abstract data structure because the Java language (and others) does not include such data structure as a part of its language definition. An array is a concrete data structure that is a part of the Java language and the one which we can use effectively here to implement the abstract data structure heap. This slide shows the correspondence between the heap and the array representation. An important aspect in deciding which data structure to use is the ease of locating a given node’s left and right child. With an array implementation, we can locate any node’s left and right child easily. A node with index I has its left child at index 2ÞI + 1 and right child at index 2ÞI + 2. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
499
Intro to OOP with Java, C. Thomas Wu
The construct Method private void construct( ) { for (int i = (heap.length-2) / 2; i >= 0; i--) { current = i; done = false; while ( !done ) { if ( current has no children ) { done = true; } else { if (current node < larger child) { swap the two nodes; set current points to the larger child; } { private void construct( ) int current, maxChildIndex; boolean done; for (int i = (heap.length-2) / 2; i >= 0; i--) { current = i; done = false; while ( !done ) {//perform one rebuild step //with the node at index i if ( 2*current+1 > heap.length-1 ) { //current node has no children, so stop done = true; } else { //current node has at least one child, //get the index of larger child maxChildIndex = maxChild( current, heap.length-1 ); if ( heap[current] < heap[maxChildIndex] ) { //a child is larger, so swap and continue swap( current, maxChildIndex ); current = maxChildIndex; else { //the value relationship constraint //is satisfied, so stop testPrint( heap.length ); //TEMP ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
500
Intro to OOP with Java, C. Thomas Wu
The extract Method private void extract( ) { for (int size = heap.length-1; size >= 0; size--) { remove the root node data; move the last node to the root; done = false; //rebuild the heap with one less element while (!done) { if (current has no children) { done = true; } else { if (current node < larger child) { swap the two nodes; set current points to the larger child; } { private void extract( ) int current, maxChildIndex; boolean done; for (int size = heap.length-1; size >= 0; size--) { //remove the root node data sortedList[size] = heap[ 0 ]; //move the last node to the root heap[ 0 ] = heap[size]; //rebuild the heap with one less element current = 0; done = false; while ( !done ) { if ( 2*current+1 > size ) {//current node has no children, so stop done = true; } else { //current node has at least one child, //get the index of larger child maxChildIndex = maxChild( current, size ); if ( heap[current] < heap[maxChildIndex] ) { //a child is larger, so swap and continue swap( current, maxChildIndex ); current = maxChildIndex; else { //value relationship constraint //is satisfied, so stop testPrint( size ); //TEMP ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
501
Intro to OOP with Java, C. Thomas Wu
Heapsort Performance The total number of comparisons in the extraction phase is (N-1)K where K is the depth of a heap. We solve for K using the fact that the heap must satisfy the structural constraint: total # nodes in a heap with depth K this holds because of the structural constraint Therefore, ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
502
Heapsort Performance (cont'd)
Intro to OOP with Java, C. Thomas Wu Heapsort Performance (cont'd) There are N/2 rebuild steps in the construction phase. Each rebuild step will take no more than K comparisons. The total number of comparisons in the construction phase is approximately Therefore, the total number of comparisons for both phases is ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
503
Intro to OOP with Java, C. Thomas Wu
Problem Statement Problem statement: Add the sorting capability to the AddressBook class from Chapter 10. The new AddressBook class will include a method that sort Person objects in alphabetical order of their names or in ascending order of their ages. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
504
Overall Plan Instead of going through the development steps, we will present three different implementations. The three versions are named AddressBookVer1, AddressBookVer2, and AddressBookVer3. These classes will implement the AddressBook interface. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
505
The AddressBook Interface
interface AddressBook { public void add(Person newPerson); public boolean delete(String searchName); public Person search(String searchName); public Person[ ] sort (int attribute); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
506
AddressBookVer1 Design
We use an array of Person objects We provide our own sorting method in the AddressBookVer1 class We define the Person class so we can compare Person objects by name or by age ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
507
Comparing Person Objects
Intro to OOP with Java, C. Thomas Wu Comparing Person Objects First, we need to determine how to compare Person objects The following does not make sense: Person p1 = …; Person p2 = …; if ( p1 < p2 ) { … } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
508
Modify the Person Class
Intro to OOP with Java, C. Thomas Wu Modify the Person Class Modify the Person class to include a variable that tells which attribute to compare. class Person { … public static final int NAME = 0; public static final int AGE = 1; public static int compareAttribute = NAME; public static void setCompareAttribute(int attribute) { compareAttribute = attribute; } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
509
Intro to OOP with Java, C. Thomas Wu
The compareTo Method To compare Person objects, first set the comparison attribute and then call the compareTo Method. Person.setCompareAttribute (Person.NAME); int compResult = p1.compareTo(p2); if (compResult < 0) { //p1 “less than” p2 } else if (compResult == 0) { //p1 “equals” pw } else { //p2 “greater than” p2 } public int compareTo(Person p) { int compResult; if ( comparisonAttribute == AGE ) { int p2age = p.getAge(); if ( this.age < p2age ) { compResult = LESS; } … } else { //compare Name String p2Name = p.getName(); compResult = this.name. compareTo(p2Name); return compResult; public int compareTo( Person person ) { int comparisonResult; if ( compareAttribute == AGE ) { int p2age = person.getAge( ); if (this.age < p2age) { comparisonResult = LESS; } else if (this.age == p2age) { comparisonResult = EQUAL; else { //this.age > p2age comparisonResult = MORE; else { //compare names with String’s compareTo String p2name = person.getName( ); comparisonResult = this.name.compareTo( p2name ); return comparisonResult; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
510
Intro to OOP with Java, C. Thomas Wu
The sort Method public Person[ ] sort (int attribute) { Person[ ] sortedList = new Person[count]; Person p1, p2, temp; //copy references to sortedList for (int i = 0; i < count; i++) { sortedList[i] = entry[i]; } //Set the comparison attribute Person.setCompareAttribute(attribute); //begin the bubble sort on sortedList … return sortedList; { public Person[ ] sort ( int attribute ) Person[ ] sortedList = new Person[ count ]; Person p1, p2, temp; //copy references to sortedList; see Figure 10.17 for (int i = 0; i < count; i++) { sortedList[i] = entry[i]; } //Set the comparison attribute Person.setCompareAttribute( attribute ); //begin the bubble sort on sortedList int bottom, i, comparisonResult; boolean exchanged = true; bottom = sortedList.length - 2; while ( exchanged ) { exchanged = false; for (i = 0; i <= bottom; i++) { p1 = sortedList[i]; p2 = sortedList[i+1]; comparisonResult = p1.compareTo(p2, attribute); if ( comparisonResult > 0 ) { //p1 is 'larger' sortedList[i] = p2; //than p2,so sortedList[i+1] = p1; //exchange exchanged = true; //exchange is made bottom--; return sortedList; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
511
The Use of sortedList in the sort Method
Intro to OOP with Java, C. Thomas Wu The Use of sortedList in the sort Method ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
512
Intro to OOP with Java, C. Thomas Wu
AddressBookVer1 Code Directory: Chapter11/ Source Files: AddressBookVer1.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Please use your Java IDE to view the source files and run the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
513
AddressBookVer2 Design
We use the java.util.Arrays class to sort an array of Person objects The Person class does not include any comparison methods. Instead, we implement the Comparator interface. We can define the implementation class so we can compare Person objects using any combination of their attributes For example, we can define a comparator that compares Person objects by using both name and age ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
514
The AgeComparator Class
This class compares the age attributes of Person objects class AgeComparator implements Comparator { private final int LESS = -1; private final int EQUAL = 0; private final int MORE = 1; public int compare(Object p1, Object p2) { int comparisonResult; int p1age = ((Person)p1).getAge( ); int p2age = ((Person)p2).getAge( ); if (p1age < p2age) { comparisonResult = LESS; } else if (p1age == p2age) { comparisonResult = EQUAL; } else { assert p1age > p2age; comparisonResult = MORE; } return comparisonResult; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
515
The NameComparator Class
This class compares the age attributes of Person objects Because the name attribute is a string we can use the compareTo method of the String class class NameComparator implements Comparator { public int compare(Object p1, Object p2) { String p1name = ((Person)p1).getName( ); String p2name = ((Person)p2).getName( ); return p1name.compareTo(p2name); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
516
The sort Method We use the sort method of the java.util.Arrays class
public Person[ ] sort ( int attribute ) { if (!(attribute == Person.NAME || attribute == Person.AGE) ) { throw new IllegalArgumentException( ); } Person[ ] sortedList = new Person[ count ]; //copy references to sortedList for (int i = 0; i < count; i++) { sortedList[i] = entry[i]; Arrays.sort(sortedList, getComparator(attribute)); return sortedList; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
517
Intro to OOP with Java, C. Thomas Wu
AddressBookVer2 Code Directory: Chapter11/ Source Files: AddressBookVer2.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Please use your Java IDE to view the source files and run the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
518
AddressBookVer3 Design
In the previous two versions, we used an array data structure to maintain a collection of Person objects In the third version, we don't use an array at all. Instead, we use a Map from the Java Collection Framework to maintain a collection of Person objects. We use the person's name as the key of a Map entry and the person object as the value of a Map entry. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
519
The sort Method We retrieve a collection of values in the map, converts it to an array, and use the sort method of the java.util.Arrays class to sort this array. public Person[ ] sort ( int attribute ) { if (!(attribute == Person.NAME || attribute == Person.AGE) ) { throw new IllegalArgumentException( ); } Person[ ] sortedList = new Person[entry.size()]; entry.values().toArray(sortedList); Arrays.sort(sortedList, getComparator(attribute)); return sortedList; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
520
Intro to OOP with Java, C. Thomas Wu
AddressBookVer3 Code Directory: Chapter11/ Source Files: AddressBookVer3.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Please use your Java IDE to view the source files and run the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
521
Chapter 12 File Input and Output
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
522
Chapter 12 Objectives After you have read and studied this chapter, you should be able to Include a JFileChooser object in your program to let the user specify a file. Write bytes to a file and read them back from the file, using FileOutputStream and FileInputStream. Write values of primitive data types to a file and read them back from the file, using DataOutputStream and DataInputStream. Write text data to a file and read them back from the file, using PrintWriter and BufferedReader Read a text file using Scanner Write objects to a file and read them back from the file, using ObjectOutputStream and ObjectInputStream ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
523
Intro to OOP with Java, C. Thomas Wu
The File Class To operate on a file, we must first create a File object (from java.io). Opens the file sample.dat in the current directory. File inFile = new File(“sample.dat”); File inFile = new File (“C:/SamplePrograms/test.dat”); Opens the file test.dat in the directory C:\SamplePrograms using the generic file separator / and providing the full pathname. When a program that manipulates a large amount of data practical, we must save the data to a file. If we don’t, then the user must reenter the same data every time he or she runs the program because any data used by the program will be erased from the main memory at program termination. If the data were saved, then the program can read them back from the file and rebuild the information so the user can work on the data without reentering them. In this chapter you will learn how to save data to and read data from a file. We call the action of saving data to a file file output and the action of reading data from a file file input. Note: The statements new File( “C:\\SamplePrograms”, “one.txt”); and new File(“C:\\SamplePrograms\\one.text”); will open the same file. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
524
Intro to OOP with Java, C. Thomas Wu
Some File Methods if ( inFile.exists( ) ) { To see if inFile is associated to a real file correctly. if ( inFile.isFile() ) { To see if inFile is associated to a file or not. If false, it is a directory. File directory = new File("C:/JavaPrograms/Ch12"); String filename[] = directory.list(); for (int i = 0; i < filename.length; i++) { System.out.println(filename[i]); } List the name of all files in the directory C:\JavaProjects\Ch12 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
525
The JFileChooser Class
Intro to OOP with Java, C. Thomas Wu The JFileChooser Class A javax.swing.JFileChooser object allows the user to select a file. JFileChooser chooser = new JFileChooser( ); chooser.showOpenDialog(null); To start the listing from a specific directory: We can start the listing from a current directory by writing String current = System.getProperty("user.dir"); JFileChooser chooser = new JFileChooser(current); or equivalently JFileChooser chooser = new JFileChooser( ); chooser.setCurrentDirectory(new File(current)); JFileChooser chooser = new JFileChooser("D:/JavaPrograms/Ch12"); chooser.showOpenDialog(null); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
526
Getting Info from JFileChooser
int status = chooser.showOpenDialog(null); if (status == JFileChooser.APPROVE_OPTION) { JOptionPane.showMessageDialog(null, "Open is clicked"); } else { //== JFileChooser.CANCEL_OPTION JOptionPane.showMessageDialog(null, "Cancel is clicked"); } File selectedFile = chooser.getSelectedFile(); File currentDirectory = chooser.getCurrentDirectory(); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
527
Intro to OOP with Java, C. Thomas Wu
Applying a File Filter A file filter may be used to restrict the listing in JFileChooser to only those files/directories that meet the designated filtering criteria. To apply a file, we define a subclass of the javax.swing.filechooser.FileFilter class and provide the accept and getDescription methods. public boolean accept(File file) public String getDescription( ) See the JavaFilter class that restricts the listing to directories and Java source files. The accept method returns true if the parameter file is a file to be included in the list. The getDescription method returns a text that will be displayed as one of the entries for the “Files of Type:” drop-down list. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
528
A stream is a sequence of data items, usually 8-bit bytes.
12.2 Low-Level File I/O To read data from or write data to a file, we must create one of the Java stream objects and attach it to the file. A stream is a sequence of data items, usually 8-bit bytes. Java has two types of streams: an input stream and an output stream. An input stream has a source form which the data items come, and an output stream has a destination to which the data items are going. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
529
Streams for Low-Level File I/O
Intro to OOP with Java, C. Thomas Wu Streams for Low-Level File I/O FileOutputStream and FileInputStream are two stream objects that facilitate file access. FileOutputStream allows us to output a sequence of bytes; values of data type byte. FileInputStream allows us to read in an array of bytes. Data is saved in blocks of bytes to reduce the time it takes to save all of our data. The operation of saving data as a block is called data caching. To carry out data caching, part of memory is reserved as a data buffer or cache, which is used as a temporary holding place. Data are first written to a buffer. When the buffer becomes full, the data in the buffer are actually written to a file. If there are any remaining data in the buffer and the file is not closed, those data will be lost. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
530
Sample: Low-Level File Output
Intro to OOP with Java, C. Thomas Wu Sample: Low-Level File Output //set up file and stream File outFile = new File("sample1.data"); FileOutputStream outStream = new FileOutputStream( outFile ); //data to save byte[] byteArray = {10, 20, 30, 40, 50, 60, 70, 80}; //write data to the stream outStream.write( byteArray ); //output done, so close the stream outStream.close(); class TestFileOutputStream { public static void main (String[] args) throws IOException //set up file and stream File outFile = new File("sample1.data"); FileOutputStream outStream = new FileOutputStream(outFile); //data to output byte[] byteArray = {10, 20, 30, 40, 50, 60, 70, 80}; //write data to the stream outStream.write(byteArray); //output done, so close the stream outStream.close(); } The main method throws an exception. Exception handling is described in Section 11.4. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
531
Sample: Low-Level File Input
Intro to OOP with Java, C. Thomas Wu Sample: Low-Level File Input //set up file and stream File inFile = new File("sample1.data"); FileInputStream inStream = new FileInputStream(inFile); //set up an array to read data in int fileSize = (int)inFile.length(); byte[] byteArray = new byte[fileSize]; //read data in and display them inStream.read(byteArray); for (int i = 0; i < fileSize; i++) { System.out.println(byteArray[i]); } //input done, so close the stream inStream.close(); import javabook.*; import java.io.*; class TestFileInputStream { public static void main (String[] args) throws IOException MainWindow mainWindow = new MainWindow(); OutputBox outputBox = new OutputBox(mainWindow); mainWindow.setVisible( true ); outputBox.setVisible( true ); //set up file and stream File inFile = new File("sample1.data"); FileInputStream inStream = new FileInputStream(inFile); //set up an array to read data in int fileSize = (int)inFile.length(); byte[] byteArray = new byte[fileSize]; //read data in and display them inStream.read(byteArray); for (int i = 0; i < fileSize; i++) { outputBox.printLine(byteArray[i]); } //input done, so close the stream inStream.close(); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
532
Streams for High-Level File I/O
FileOutputStream and DataOutputStream are used to output primitive data values FileInputStream and DataInputStream are used to input primitive data values To read the data back correctly, we must know the order of the data stored and their data types ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
533
Setting up DataOutputStream
A standard sequence to set up a DataOutputStream object: ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
534
Sample Output import java.io.*; class Ch12TestDataOutputStream {
public static void main (String[] args) throws IOException { . . . //set up outDataStream //write values of primitive data types to the stream outDataStream.writeInt( ); outDataStream.writeLong( L); outDataStream.writeFloat( F); outDataStream.writeDouble( D); outDataStream.writeChar('A'); outDataStream.writeBoolean(true); //output done, so close the stream outDataStream.close(); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
535
Setting up DataInputStream
A standard sequence to set up a DataInputStream object: ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
536
Sample Input import java.io.*; class Ch12TestDataInputStream {
public static void main (String[] args) throws IOException { . . . //set up inDataStream //read values back from the stream and display them System.out.println(inDataStream.readInt()); System.out.println(inDataStream.readLong()); System.out.println(inDataStream.readFloat()); System.out.println(inDataStream.readDouble()); System.out.println(inDataStream.readChar()); System.out.println(inDataStream.readBoolean()); //input done, so close the stream inDataStream.close(); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
537
Reading Data Back in Right Order
The order of write and read operations must match in order to read the stored primitive data back correctly. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
538
Textfile Input and Output
Instead of storing primitive data values as binary data in a file, we can convert and store them as a string data. This allows us to view the file content using any text editor To output data as a string to file, we use a PrintWriter object To input data from a textfile, we use FileReader and BufferedReader classes From Java 5.0 (SDK 1.5), we can also use the Scanner class for inputting textfiles ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
539
Sample Textfile Output
import java.io.*; class Ch12TestPrintWriter { public static void main (String[] args) throws IOException { //set up file and stream File outFile = new File("sample3.data"); FileOutputStream outFileStream = new FileOutputStream(outFile); PrintWriter outStream = new PrintWriter(outFileStream); //write values of primitive data types to the stream outStream.println( ); outStream.println("Hello, world."); outStream.println(true); //output done, so close the stream outStream.close(); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
540
Sample Textfile Input import java.io.*; class Ch12TestBufferedReader {
public static void main (String[] args) throws IOException { //set up file and stream File inFile = new File("sample3.data"); FileReader fileReader = new FileReader(inFile); BufferedReader bufReader = new BufferedReader(fileReader); String str; str = bufReader.readLine(); int i = Integer.parseInt(str); //similar process for other data types bufReader.close(); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
541
Sample Textfile Input with Scanner
import java.io.*; class Ch12TestScanner { public static void main (String[] args) throws IOException { //open the Scanner Scanner scanner = new Scanner(new File("sample3.data")); //get integer int i = scanner.nextInt(); //similar process for other data types scanner.close(); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
542
Intro to OOP with Java, C. Thomas Wu
Object File I/O It is possible to store objects just as easily as you store primitive data values. We use ObjectOutputStream and ObjectInputStream to save to and load objects from a file. To save objects from a given class, the class declaration must include the phrase implements Serializable. For example, class Person implements Serializable { . . . } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
543
Intro to OOP with Java, C. Thomas Wu
Saving Objects File outFile = new File("objects.data"); FileOutputStream outFileStream = new FileOutputStream(outFile); ObjectOutputStream outObjectStream = new ObjectOutputStream(outFileStream); Person person = new Person("Mr. Espresso", 20, 'M'); outObjectStream.writeObject( person ); You can even mix objects and primitive data type values. For example, outObjectStream.writeInt ( ); outObjectStream.writeObject( account1 ); outObjectStream.writeChar ( 'X' ); account1 = new Account(); bank1 = new Bank(); outObjectStream.writeObject( account1 ); outObjectStream.writeObject( bank1 ); Could save objects from the different classes. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
544
Intro to OOP with Java, C. Thomas Wu
Reading Objects File inFile = new File("objects.data"); FileInputStream inFileStream = new FileInputStream(inFile); ObjectInputStream inObjectStream = new ObjectInputStream(inFileStream); Person person = (Person) inObjectStream.readObject( ); Must type cast to the correct object type. You can even mix objects and primitive data type values. For example, outObjectStream.writeInt ( ); outObjectStream.writeObject( account1 ); outObjectStream.writeChar ( 'X' ); Account account1 = (Account) inObjectStream.readObject( ); Bank bank1 = (Bank) inObjectStream.readObject( ); Must read in the correct order. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
545
Saving and Loading Arrays
Intro to OOP with Java, C. Thomas Wu Saving and Loading Arrays Instead of processing array elements individually, it is possible to save and load the whole array at once. Person[] people = new Person[ N ]; //assume N already has a value //build the people array . . . //save the array outObjectStream.writeObject ( people ); { class FindSum private int sum; private boolean success; public int getSum() return sum; } public boolean isSuccess() return success; void computeSum (String fileName ) success = true; try { File inFile = new File(fileName); FileInputStream inFileStream = new FileInputStream(inFile); DataInputStream inDataStream = new DataInputStream(inFileStream); //read three integers int i = inDataStream.readInt(); int j = inDataStream.readInt(); int k = inDataStream.readInt(); sum = i + j + k; inDataStream.close(); catch (IOException e) { success = false; //read the array Person[ ] people = (Person[]) inObjectStream.readObject( ); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
546
Intro to OOP with Java, C. Thomas Wu
Problem Statement Problem statement: Write a class that manages file I/O of an AddressBook object. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
547
Intro to OOP with Java, C. Thomas Wu
Development Steps We will develop this program in four steps: Implement the constructor and the setFile method. Implement the write method. Implement the read method. Finalize the class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
548
Intro to OOP with Java, C. Thomas Wu
Step 1 Design We identify the data members and define a constructor to initialize them. Instead of storing individual Person objects, we will deal with a AddressBook object directly using Object I/O techniques. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
549
Intro to OOP with Java, C. Thomas Wu
Step 1 Code Directory: Chapter12/Step1 Source Files: AddressBookStorage.java TestAddressBookStorage.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Please use your Java IDE to view the source files and run the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
550
Intro to OOP with Java, C. Thomas Wu
Step 1 Test We include a temporary output statement inside the setFile method. We run the test main class and verify that the setFile method is called correctly. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
551
Intro to OOP with Java, C. Thomas Wu
Step 2 Design Design and implement the write method The data member filename stores the name of the object file to store the address book. We create an ObjectOutputStream object from the data member filename in the write method. The write method will propagate an IOException when one is thrown. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
552
Intro to OOP with Java, C. Thomas Wu
Step 2 Code Directory: Chapter12/Step2 Source Files: AddressBookStorage.java TestAddressBookWrite.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
553
Intro to OOP with Java, C. Thomas Wu
Step 2 Test We run the test program several times with different sizes for the address book. We verify that the resulting files indeed have different sizes. At this point, we cannot check whether the data are saved correctly or not. We can do so only after finishing the code to read the data back. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
554
Intro to OOP with Java, C. Thomas Wu
Step 3 Design Design and implement the read method. The method returns an AddressBook object read from a file (if there's no exception) The method will propagate an IOException when one is thrown. Here's the pseudocode to locate a person with the designated name. Notice that for this routine to work correctly, the array must be packed with the real pointers in the first half and null pointers in the last half. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
555
Intro to OOP with Java, C. Thomas Wu
Step 3 Code Directory: Chapter12/Step3 Source Files: AddressBookStorage.java TestAddressBookRead.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
556
Intro to OOP with Java, C. Thomas Wu
Step 3 Test We will write a test program to verify that the data can be read back correctly from a file. To test the read operation, the file to read the data from must already exist. We will make this test program save the data first by using the TestAddressBookWrite class from . ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
557
Intro to OOP with Java, C. Thomas Wu
Step 4: Finalize We perform the critical review of the final program. We run the final test ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
558
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
Chapter 13 Inheritance and Polymorphism ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
559
Intro to OOP with Java, C. Thomas Wu
Chapter 13 Objectives After you have read and studied this chapter, you should be able to Write programs that are easily extensible and modifiable by applying polymorphism in program design. Define reusable classes based on inheritance and abstract classes and abstract methods. Differentiate the abstract classes and Java interfaces. Define methods, using the protected modifier. Parse strings, using a String Tokenizer object. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
560
Defining Classes with Inheritance
Intro to OOP with Java, C. Thomas Wu Defining Classes with Inheritance Case Study: Suppose we want implement a class roster that contains both undergraduate and graduate students. Each student’s record will contain his or her name, three test scores, and the final course grade. The formula for determining the course grade is different for graduate students than for undergraduate students. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
561
Modeling Two Types of Students
Intro to OOP with Java, C. Thomas Wu Modeling Two Types of Students There are two ways to design the classes to model undergraduate and graduate students. We can define two unrelated classes, one for undergraduates and one for graduates. We can model the two kinds of students by using classes that are related in an inheritance hierarchy. Two classes are unrelated if they are not connected in an inheritance relationship. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
562
Classes for the Class Roster
Intro to OOP with Java, C. Thomas Wu Classes for the Class Roster For the Class Roster sample, we design three classes: Student UndergraduateStudent GraduateStudent The Student class will incorporate behavior and data common to both UndergraduateStudent and GraduateStudent objects. The UndergraduateStudent class and the GraduateStudent class will each contain behaviors and data specific to their respective objects. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
563
Inheritance Hierarchy
Intro to OOP with Java, C. Thomas Wu Inheritance Hierarchy ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
564
The Protected Modifier
Intro to OOP with Java, C. Thomas Wu The Protected Modifier The modifier protected makes a data member or method visible and accessible to the instances of the class and the descendant classes. Public data members and methods are accessible to everyone. Private data members and methods are accessible only to instances of the class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
565
Intro to OOP with Java, C. Thomas Wu
Polymorphism Polymorphism allows a single variable to refer to objects from different subclasses in the same inheritance hierarchy For example, if Cat and Dog are subclasses of Pet, then the following statements are valid: Pet myPet; myPet = new Dog(); . . . myPet = new Cat(); A variable of class X may not refer to an object from the superclass or sibling classes of X. Sibling classes are those that share the common ancestor class. For example, the following statements are invalid: Dog myDog = new Cat(); Cat myCat = new Pet(); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
566
Creating the roster Array
Intro to OOP with Java, C. Thomas Wu Creating the roster Array We can maintain our class roster using an array, combining objects from the Student, UndergraduateStudent, and GraduateStudent classes. Student roster = new Student[40]; . . . roster[0] = new GraduateStudent(); roster[1] = new UndergraduateStudent(); roster[2] = new UndergraduateStudent(); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
567
State of the roster Array
Intro to OOP with Java, C. Thomas Wu State of the roster Array The roster array with elements referring to instances of GraduateStudent or UndergraduateStudent classes. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
568
Sample Polymorphic Message
Intro to OOP with Java, C. Thomas Wu Sample Polymorphic Message To compute the course grade using the roster array, we execute If roster[i] refers to a GraduateStudent, then the computeCourseGrade method of the GraduateStudent class is executed. If roster[i] refers to an UndergraduateStudent, then the computeCourseGrade method of the UndergraduateStudent class is executed. for (int i = 0; i < numberOfStudents; i++) { roster[i].computeCourseGrade(); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
569
The instanceof Operator
Intro to OOP with Java, C. Thomas Wu The instanceof Operator The instanceof operator can help us learn the class of an object. The following code counts the number of undergraduate students. int undergradCount = 0; for (int i = 0; i < numberOfStudents; i++) { if ( roster[i] instanceof UndergraduateStudent ) { undergradCount++; } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
570
Inheritance and Member Accessibility
Intro to OOP with Java, C. Thomas Wu Inheritance and Member Accessibility We use the following visual representation of inheritance to illustrate data member accessibility. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
571
The Effect of Three Visibility Modifiers
Intro to OOP with Java, C. Thomas Wu The Effect of Three Visibility Modifiers ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
572
Accessibility of Super from Sub
Intro to OOP with Java, C. Thomas Wu Accessibility of Super from Sub Everything except the private members of the Super class is visible from a method of the Sub class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
573
Accessibility from Another Instance
Intro to OOP with Java, C. Thomas Wu Accessibility from Another Instance Data members accessible from an instance are also accessible from other instances of the same class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
574
Inheritance and Constructors
Intro to OOP with Java, C. Thomas Wu Inheritance and Constructors Unlike members of a superclass, constructors of a superclass are not inherited by its subclasses. You must define a constructor for a class or use the default constructor added by the compiler. The statement super(); calls the superclass’s constructor. If the class declaration does not explicitly designate the superclass with the extends clause, then the class’s superclass is the Object class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
575
Abstract Superclasses and Abstract Methods
Intro to OOP with Java, C. Thomas Wu Abstract Superclasses and Abstract Methods When we define a superclass, we often do not need to create any instances of the superclass. Depending on whether we need to create instances of the superclass, we must define the class differently. We will study examples based on the Student superclass defined earlier. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
576
Definition: Abstract Class
Intro to OOP with Java, C. Thomas Wu Definition: Abstract Class An abstract class is a class defined with the modifier abstract OR that contains an abstract method OR that does not provide an implementation of an inherited abstract method An abstract method is a method with the keyword abstract, and it ends with a semicolon instead of a method body. Private methods and static methods may not be declared abstract. No instances can be created from an abstract class. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
577
Intro to OOP with Java, C. Thomas Wu
Case 1 Student Must Be Undergraduate or Graduate If a student must be either an undergraduate or a graduate student, we only need instances of UndergraduateStudent or GraduateStudent. Therefore, we must define the Student class so that no instances may be created of it. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
578
Intro to OOP with Java, C. Thomas Wu
Case 2 Student Does Not Have to Be Undergraduate or Graduate. In this case, we may design the Student class in one of two ways. We can make the Student class instantiable. We can leave the Student class abstract and add a third subclass, OtherStudent, to handle a student who does not fall into the UndergraduateStudent or GraduateStudent categories. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
579
Intro to OOP with Java, C. Thomas Wu
Which Approach to Use The best approach depends on the particular situation. When considering design options, we can ask ourselves which approach allows easier modification and extension. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
580
Inheritance versus Interface
Intro to OOP with Java, C. Thomas Wu Inheritance versus Interface The Java interface is used to share common behavior (only method headers) among the instances of different classes. Inheritance is used to share common code (including both data members and methods) among the instances of related classes. In your program designs, remember to use the Java interface to share common behavior. Use inheritance to share common code. If an entity A is a specialized form of another entity B, then model them by using inheritance. Declare A as a subclass of B. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
581
Intro to OOP with Java, C. Thomas Wu
Problem Statement Problem statement: Write an application that reads in a text file organized in the manner shown below and displays the final course grades.The course grades are computed differently for the undergraduate and graduate students based on the formulas listed on page 710. The input text file format is as follows: • A single line is used for information on one student. • Each line uses the format <Type> <Name> <Test 1> <Test 2> <Test 3> where <Type> designates either a graduate or an undergraduate student,<Name> designates the student’s first and last name, and <Test i> designates the ith test score. • End of input is designated by the word END. The case of the letters is insignificant. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
582
Intro to OOP with Java, C. Thomas Wu
Overall Plan Tasks 1. Read an input text file. 2. Compute the course grades. 3. Print out the result. Input File Format ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
583
Intro to OOP with Java, C. Thomas Wu
Development Steps We will develop this program in five steps: 1. Start with the program skeleton.Define the skeleton ComputeGrades classes. 2. Implement the printResult method.Define any other methods necessary to implement printResult. 3. Implement the computeGrade method.Define any other methods necessary to implement computeGrade. 4. Implement the readData method.Define any other methods necessary to implement readData. 5. Finalize and look for improvements. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
584
Intro to OOP with Java, C. Thomas Wu
Step 1 Design We start with a program skeleton. We will define two constructors so the programmer can create a roster of default size or the size of her choice. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
585
Intro to OOP with Java, C. Thomas Wu
Step 1 Code Directory: Chapter13/Step1 Source Files: ComputeGrades.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Please use your Java IDE to view the source files and run the program. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
586
Intro to OOP with Java, C. Thomas Wu
Step 1 Test We include a temporary output statement inside the (currently stub) method we define. We run the test main class and verify that the methods are called correctly. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
587
Intro to OOP with Java, C. Thomas Wu
Step 2 Design We design and implement the printResult method We use the helper class OutputBox for displaying the result. for each element i in the roster array { output the name of roster[i]; output the test scores of roster[i]; output the course grade of roster[i]; skip to the next line; } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
588
Intro to OOP with Java, C. Thomas Wu
Step 2 Code Directory: Chapter13/Step2 Source Files: ComputeGrades.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
589
Intro to OOP with Java, C. Thomas Wu
Step 2 Test We verify the temporary readData method is working correctly. This confirms that we are using the correct student classes and using their methods correctly. We verify the printResult method does indeed display the data in our desired format. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
590
Intro to OOP with Java, C. Thomas Wu
Step 3 Design We design and implement the computeGrade method. The code for actually determining the course grade is embedded in individual student classes So the code to add to the ComputeGrades class is very simplistic. This is a direct benefit of using polymorphism effectively. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
591
Intro to OOP with Java, C. Thomas Wu
Step 3 Code Directory: Chapter13/Step3 Source Files: ComputeGrades.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
592
Intro to OOP with Java, C. Thomas Wu
Step 3 Test We will repeat the same test routines from Step 2. Instead of seeing four asterisks, we should be seeing the correct grades. We test both the passing and not passing test scores. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
593
Intro to OOP with Java, C. Thomas Wu
Step 4 Design We design and implement the core functionality of the program—the readData method We can express its logic as get the filename from the user; if (the filename is provided) read in data and build the roster array; else output an error message; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
594
The buildRoster Method
Intro to OOP with Java, C. Thomas Wu The buildRoster Method The logic of the workhorse private method buildRoster is as follows: set bufReader for input; while ( !done ) { line = get next line; if (line is END) { done = true; } else { student = createStudent( line ); if (student != null) { roster[studentCount] = student; //add to roster studentCount++; } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
595
The createStudent Method
Intro to OOP with Java, C. Thomas Wu The createStudent Method We use the StringTokenizer class to break down items in a single line of input StringTokenizer parser = new StringTokenizer( line ); String type; try { type = parser.nextToken(); if (type.equals(UNDER_GRAD) || type.equals(GRAD)) { student = newStudentWithData(type, parser); } else { //invalid type is encountered student = null; } } catch (NoSuchElementException e) { //no token return student; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
596
Intro to OOP with Java, C. Thomas Wu
Step 4 Code Directory: Chapter13/Step4 Source Files: ComputeGrades.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
597
Intro to OOP with Java, C. Thomas Wu
Step 4 Test We run through a more complete testing routine in this step.We need to run the program for various types of input files. Some of the possible file contents are as follows: ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
598
Step 5: Finalize and Improve
Intro to OOP with Java, C. Thomas Wu Step 5: Finalize and Improve We finalize the program by correcting any remaining errors, inconsistency, or unfinished methods. We want to review the methods and improve them as necessarily. One problem (which would have been identified in step 4 testing) we need to correct is the missing method for expanding the roster array when the input file includes more student entries than the set default size of 25. We leave this method as Exercise 3. We also leave some of the possible improvements as exercises. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
599
GUI and Event-Driven Programming
Chapter 14 GUI and Event-Driven Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
600
Intro to OOP with Java, C. Thomas Wu
Objectives After you have read and studied this chapter, you should be able to Define a subclass of JFrame to implement a customized frame window. Write event-driven programs using Java's delegation-based event model Arrange GUI objects on a window using layout managers and nested panels Write GUI application programs using JButton, JLabel, ImageIcon, JTextField, JTextArea, JCheckBox, JRadioButton, JComboBox, JList, and JSlider objects from the javax.swing package Write GUI application programs with menus Write GUI application programs that process mouse events We will learn how to create a customized frame window by defining a subclass of the JFrame class. Among the many different types of GUI objects, arguably the buttons are most common. We will learn how to create and place buttons on a frame in this lesson. ©The McGraw-Hill Companies, Inc.
601
Graphical User Interface
Intro to OOP with Java, C. Thomas Wu Graphical User Interface In Java, GUI-based programs are implemented by using classes from the javax.swing and java.awt packages. The Swing classes provide greater compatibility across different operating systems. They are fully implemented in Java, and behave the same on different operating systems. Classes we use to develop GUI-based programs are located in two packages javax.swing and java.awt. Many of the classes in the java.awt package are replaced by Swing counterparts, and for the most part, using the Swing classes over the AWT classes is the preferred approach because the newer Swing classes are better implementation. We still have to refer to java.awt package because there are some classes that are defined only in the java.awt package. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
602
Intro to OOP with Java, C. Thomas Wu
Sample GUI Objects Various GUI objects from the javax.swing package. Here's a sample frame that includes a number of common Swing components. We will see examples using JFrame and JButton in this lesson. We will see other components in the later lessons of this module. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
603
Intro to OOP with Java, C. Thomas Wu
Subclassing JFrame To create a customized frame window, we define a subclass of the JFrame class. The JFrame class contains rudimentary functionalities to support features found in any frame window. The standard JFrame class includes only most basic functionalities. When we need a frame window in our application, it is typical for us to define a subclass of JFrame to create a frame window that is customized to our needs. We will study the basics of this customization. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
604
Creating a Plain JFrame
Intro to OOP with Java, C. Thomas Wu Creating a Plain JFrame import javax.swing.*; class Ch7DefaultJFrame { public static void main( String[] args ) { JFrame defaultJFrame; defaultJFrame = new JFrame(); defaultJFrame.setVisible(true); } Before we start to explore how to customize a frame window, let's see the behavior of a plain standard JFrame object. This sample program creates a default JFrame object. When you run this program, a very tiny window appears at the top left corner of the screen. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
605
Creating a Subclass of JFrame
Intro to OOP with Java, C. Thomas Wu Creating a Subclass of JFrame To define a subclass of another class, we declare the subclass with the reserved word extends. import javax.swing.*; class Ch7JFrameSubclass1 extends JFrame { . . . } A subclass of any class is declared by including the keyword 'extends' the class definition header. The example here defines a subclass of JFrame named Ch7JFrameSubclass1. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
606
Customizing Ch14JFrameSubclass1
Intro to OOP with Java, C. Thomas Wu Customizing Ch14JFrameSubclass1 An instance of Ch14JFrameSubclass1 will have the following default characteristics: The title is set to My First Subclass. The program terminates when the close box is clicked. The size of the frame is 300 pixels wide by 200 pixels high. The frame is positioned at screen coordinate (150, 250). These properties are set inside the default constructor. Open the sample Ch7JFrameSubclass1 class and see how the constructor includes a number of statements such as setTitle and setLocation to set the properties. These methods are all inherited from the superclass JFrame. The last statement is setDefaultCloseOperation that defines the frame's behavior when the close box of the frame is clicked. Passing the class constant EXIT_ON_CLOSE specifies to stop the application when the close box of a frame is clicked. Remove this statement and see what happens. Source File: Ch14JFrameSubclass1.java ©The McGraw-Hill Companies, Inc.
607
Displaying Ch14JFrameSubclass1
Intro to OOP with Java, C. Thomas Wu Displaying Ch14JFrameSubclass1 Here's how a Ch14JFrameSubclass1 frame window will appear on the screen. This diagram illustrates how the arguments to the setSize and setLocation methods affect the frame window appearance on the screen. The top left corner of the screen has coordinate (0,0). The value of x increases as you move toward right and the value of y increases as you move down. Notice that the screen coordinate is different from the coordinate system of a mathematical 2-D graph. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
608
The Content Pane of a Frame
Intro to OOP with Java, C. Thomas Wu The Content Pane of a Frame The content pane is where we put GUI objects such as buttons, labels, scroll bars, and others. We access the content pane by calling the frame’s getContentPane method. This gray area is the content pane of this frame. A frame window is composed of four borders, a title bar, and a content area. The content area is called a content pane in Java, and this is the area we can use to place GUI components. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
609
Changing the Background Color
Intro to OOP with Java, C. Thomas Wu Changing the Background Color Here's how we can change the background color of a content pane to blue: Container contentPane = getContentPane(); contentPane.setBackground(Color.BLUE); Source File: Ch14JFrameSubclass2.java We access the content pane of a frame by calling the JFrame method called getContentPane. We declare the data type for the object returned by the getContentPane method to Container. Once we get the content pane object, we can call its methods. The example here calls the setBackground method to change the default background color of gray to white. The complete sample code can be found in the file Ch7JFrameSubclass2.java. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
610
Placing GUI Objects on a Frame
Intro to OOP with Java, C. Thomas Wu Placing GUI Objects on a Frame There are two ways to put GUI objects on the content pane of a frame: Use a layout manager FlowLayout BorderLayout GridLayout Use absolute positioning null layout manager The content pane of a frame is where we can place GUI components. Among the approaches available to us to place components, we will study the easier one here. The easier absolute positioning is not a recommended approach for practical applications, but our objective here is to learn the basic handling of events and placement of GUI objects, we will use the easier approach. Chapter 12 of the textbook discusses different layout managers. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
611
Intro to OOP with Java, C. Thomas Wu
Placing a Button A JButton object a GUI component that represents a pushbutton. Here's an example of how we place a button with FlowLayout. contentPane.setLayout( new FlowLayout()); okButton = new JButton("OK"); cancelButton = new JButton("CANCEL"); contentPane.add(okButton); contentPane.add(cancelButton); The key point to remember in using absolute positioning: Set the layout manager of the content pane to null as conentPane.setLayout(null) Set the bounds to a GUI object. For example okButton.setBounds(70, 125, 80, 20); Add a GUI object to the content pane by calling the add method as contentPane.add(okButton); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
612
Intro to OOP with Java, C. Thomas Wu
Event Handling An action involving a GUI object, such as clicking a button, is called an event. The mechanism to process events is called event handling. The event-handling model of Java is based on the concept known as the delegation-based event model. With this model, event handling is implemented by two types of objects: event source objects event listener objects JButton and other GUI objects are event source objects. Any object can be designated as event listener objects. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
613
Intro to OOP with Java, C. Thomas Wu
Event Source Objects An event source is a GUI object where an event occurs. We say an event source generates events. Buttons, text boxes, list boxes, and menus are common event sources in GUI-based applications. Although possible, we do not, under normal circumstances, define our own event sources when writing GUI-based applications. A single event source can generate more than one type of events. When an event is generated, a corresponding event listener is notified. Whether there is a designated listener or not, event sources generates events. If there's a no matching listeners, generated events are simply ignored. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
614
Event Listener Objects
Intro to OOP with Java, C. Thomas Wu Event Listener Objects An event listener object is an object that includes a method that gets executed in response to the generated events. A listener must be associated, or registered, to a source, so it can be notified when the source generates events. A listener can listen to a single type of events. If an event source generates two types of events, then we need two different listeners if we want process both types of events. A single listener, however, can be set to listen to single type of events from more than one event source. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
615
Connecting Source and Listener
Intro to OOP with Java, C. Thomas Wu Connecting Source and Listener event source event listener notify JButton Handler register This diagram shows the relationship between the event source and listener. First we register a listener to an event source. Once registered, whenever an event is generated, the event source will notify the listener. A listener must be registered to a event source. Once registered, it will get notified when the event source generates events. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
616
Intro to OOP with Java, C. Thomas Wu
Event Types Registration and notification are specific to event types Mouse listener handles mouse events Item listener handles item selection events and so forth Among the different types of events, the action event is the most common. Clicking on a button generates an action event Selecting a menu item generates an action event Action events are generated by action event sources and handled by action event listeners. There are different types of events. Some event sources generate only one type of events, while others generate three or four different types of events. For example, a button can generate an action event, a change event, and a item event. The most common type of event we are interested in processing for various types of GUI components is the action event. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
617
Handling Action Events
Intro to OOP with Java, C. Thomas Wu Handling Action Events action event source actionPerformed action event listener JButton Button Handler addActionListener This code shows how we register an action event listener to a button. The object we register as an action listener must be an instance of a class that implements the ActionListener interface. The class must define a method named actionPerformed. This is the method executed in response to the generated action events. JButton button = new JButton("OK"); ButtonHandler handler = new ButtonHandler( ); button.addActionListener(handler); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
618
Intro to OOP with Java, C. Thomas Wu
The Java Interface A Java interface includes only constants and abstract methods. An abstract method has only the method header, or prototype. There is no method body. You cannot create an instance of a Java interface. A Java interface specifies a behavior. A class implements an interface by providing the method body to the abstract methods stated in the interface. Any class can implement the interface. Before we give the definition of the ButtonHandler class, we need to describe the concept of Java interface. We use the term "Java interface" to distinguish it from the "graphical user interface" when necessary. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
619
ActionListener Interface
Intro to OOP with Java, C. Thomas Wu ActionListener Interface When we call the addActionListener method of an event source, we must pass an instance of a class that implements the ActionListener interface. The ActionListener interface includes one method named actionPerformed. A class that implements the ActionListener interface must therefore provide the method body of actionPerformed. Since actionPerformed is the method that will be called when an action event is generated, this is the place where we put a code we want to be executed in response to the generated events. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
620
The ButtonHandler Class
Intro to OOP with Java, C. Thomas Wu The ButtonHandler Class import javax.swing.*; import java.awt.*; import java.awt.event.*; class ButtonHandler implements ActionListener { . . . public void actionPerformed(ActionEvent event) { JButton clickedButton = (JButton) event.getSource(); JRootPane rootPane = clickedButton.getRootPane( ); Frame frame = (JFrame) rootPane.getParent(); frame.setTitle("You clicked " + clickedButton.getText()); } This actionPerformed method is programmed to change the title of the frame to 'You clicked OK' or 'You clicked Cancel'. The actionPerformed method accepts one parameter of type ActionEvent. The getSource method of ActionEvent returns the event source source object. Because the object can be of any type, we type cast it to JButton. The next two statements are necessary to get a frame object that contains this event source. Once we have a reference to this frame object, we call its setTitle method to change the frame's title. More discussion on this actionPerformed method is presented on page 397 of the textbook. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
621
Container as Event Listener
Intro to OOP with Java, C. Thomas Wu Container as Event Listener Instead of defining a separate event listener such as ButtonHandler, it is much more common to have an object that contains the event sources be a listener. Example: We make this frame a listener of the action events of the buttons it contains. event listener Because ActionListener is a Java interface and not a class, action event listener objects are not limited to instances of fixed classes. Any class can implement the ActionListener interface, so any object from a class that implements this interface can be an action event listener. This adds flexibility as this example illustrates. Instead of using a ButtonHandler object, we can make the frame object itself to be an action event listener. event source ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
622
Ch14JButtonFrameHandler
Intro to OOP with Java, C. Thomas Wu Ch14JButtonFrameHandler . . . class Ch14JButtonFrameHandler extends JFrame implements ActionListener { public void actionPerformed(ActionEvent event) { JButton clickedButton = (JButton) event.getSource(); String buttonText = clickedButton.getText(); setTitle("You clicked " + buttonText); } This is how a frame that contains the buttons can be made to be their event listeners. Notice that because the actionPerformed method is defined in the frame class, setting the title is matter of calling its setTitle method. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
623
GUI Classes for Handling Text
Intro to OOP with Java, C. Thomas Wu GUI Classes for Handling Text The Swing GUI classes JLabel, JTextField, and JTextArea deal with text. A JLabel object displays uneditable text (or image). A JTextField object allows the user to enter a single line of text. A JTextArea object allows the user to enter multiple lines of text. It can also be used for displaying multiple lines of uneditable text. Notice that JLabel objects are not limited to text. Using them is actually the easiest and quickest way to display an image. JTextArea has dual pursposes. It can be used to display noneditable multi-line text, similar to using multiple JLabel objects. It can also be used to allow the user to enter multiple lines of text, similar to using multiple JTextField objects. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
624
Intro to OOP with Java, C. Thomas Wu
JTextField We use a JTextField object to accept a single line to text from a user. An action event is generated when the user presses the ENTER key. The getText method of JTextField is used to retrieve the text that the user entered. JTextField input = new JTextField( ); input.addActionListener(eventListener); contentPane.add(input); The getText method is most commonly used inside the actionPerformed method of an action listener. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
625
Intro to OOP with Java, C. Thomas Wu
JLabel We use a JLabel object to display a label. A label can be a text or an image. When creating an image label, we pass ImageIcon object instead of a string. JLabel textLabel = new JLabel("Please enter your name"); contentPane.add(textLabel); JLabel imgLabel = new JLabel(new ImageIcon("cat.gif")); contentPane.add(imgLabel); A JLabel is strictly for displaying noneditable text or image. A JLabel object does not generate any events. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
626
Intro to OOP with Java, C. Thomas Wu
Ch14TextFrame2 JLabel (with a text) JLabel (with an image) JTextField The sample Ch7TextFrame2 class includes five GUI components: two JLabel objects, one JTextField object, and two JButton objects. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
627
Intro to OOP with Java, C. Thomas Wu
JTextArea We use a JTextArea object to display or allow the user to enter multiple lines of text. The setText method assigns the text to a JTextArea, replacing the current content. The append method appends the text to the current text. JTextArea textArea = new JTextArea( ); . . . textArea.setText("Hello\n"); textArea.append("the lost "); textArea.append("world"); Hello the lost world JTextArea Notice how the append method works. If you want to place the text to be appended on a new line, you have ouput the newline control character \n at the appropriate point. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
628
Intro to OOP with Java, C. Thomas Wu
Ch14TextFrame3 The state of a Ch14TextFrame3 window after six words are entered. Run the program and explore it. This frame has one JTextField object and one JTextArea object. Every time a text is entered in the text field and the ENTER key is pressed or the ADD button is clicked, the entered text is append to the text area. The border of red color is adorned to the text area to demarcate the region. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
629
Adding Scroll Bars to JTextArea
Intro to OOP with Java, C. Thomas Wu Adding Scroll Bars to JTextArea By default a JTextArea does not have any scroll bars. To add scroll bars, we place a JTextArea in a JScrollPane object. JTextArea textArea = new JTextArea(); . . . JScrollPane scrollText = new JScrollPane(textArea); contentPane.add(scrollText); Here's a sample to wrap the text area with scroll bars. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
630
Ch14TextFrame3 with Scroll Bars
Intro to OOP with Java, C. Thomas Wu Ch14TextFrame3 with Scroll Bars A sample Ch14TextFrame3 window when a JScrollPane is used. Initially, there will be no scroll bars. Run the program and confirm this behavior. When the displayed text goes beyond the horizontal or vertical boundary, the corresponding scroll bar appears. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
631
Layout Managers The layout manager determines how the GUI components are added to the container (such as the content pane of a frame) Among the many different layout managers, the common ones are FlowLayout (see Ch14FlowLayoutSample.java) BorderLayout (see Ch14BorderLayoutSample.java) GridLayout (see Ch14GridLayoutSample.java) ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
632
FlowLayout In using this layout, GUI componentsare placed in left-to-right order. When the component does not fit on the same line, left-to-right placement continues on the next line. As a default, components on each line are centered. When the frame containing the component is resized, the placement of components is adjusted accordingly. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
633
FlowLayout Sample This shows the placement of five buttons by using FlowLayout. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
634
BorderLayout This layout manager divides the container into five regions: center, north, south, east, and west. The north and south regions expand or shrink in height only The east and west regions expand or shrink in width only The center region expands or shrinks on both height and width. Not all regions have to be occupied. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
635
Intro to OOP with Java, C. Thomas Wu
BorderLayout Sample contentPane.setLayout(new BorderLayout()); contentPane.add(button1, BorderLayout.NORTH); contentPane.add(button2, BorderLayout.SOUTH); contentPane.add(button3, BorderLayout.EAST); contentPane.add(button4, BorderLayout.WEST); contentPane.add(button5, BorderLayout.CENTER); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
636
GridLayout This layout manager placesGUI components on equal-size N by M grids. Components are placed in top-to-bottom, left-to-right order. The number of rows and columns remains the same after the frame is resized, but the width and height of each region will change. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
637
GridLayout Sample ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
638
Nesting Panels It is possible, but very difficult, to place all GUI components on a single JPanel or other types of containers. A better approach is to use multiple panels, placing panels inside other panels. To illustrate this technique, we will create two sample frames that contain nested panels. Ch14NestedPanels1.java provides the user interface for playing Tic Tac Toe. Ch14NestedPanels2.java provides the user interface for playing HiLo. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
639
Other Common GUI Components
JCheckBox see Ch14JCheckBoxSample1.java and Ch14JCheckBoxSample2.java JRadioButton see Ch14JRadioButtonSample.java JComboBox see Ch14JComboBoxSample.java JList see Ch14JListSample.java JSlider see Ch14JSliderSample.java ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
640
Intro to OOP with Java, C. Thomas Wu
Menus The javax.swing package contains three menu-related classes: JMenuBar, JMenu, and JMenuItem. JMenuBar is a bar where the menus are placed. There is one menu bar per frame. JMenu (such as File or Edit) is a group of menu choices. JMenuBar may include many JMenu objects. JMenuItem (such as Copy, Cut, or Paste) is an individual menu choice in a JMenu object. Only the JMenuItem objects generate events. Almost all nontrivial GUI programs support menus. By using these three menu-related classes, we can easily add menus to our Java programs. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
641
Intro to OOP with Java, C. Thomas Wu
Menu Components Edit View Help JMenuBar Edit View Help File The diagram shows how the menu-related objects correspond to the actual menus. JMenu JMenuItem separator ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
642
Sequence for Creating Menus
Intro to OOP with Java, C. Thomas Wu Sequence for Creating Menus Create a JMenuBar object and attach it to a frame. Create a JMenu object. Create JMenuItem objects and add them to the JMenu object. Attach the JMenu object to the JMenuBar object. This is not the only valid sequence. Other sequences are possible. We list this sequence as one possible sequence you can follow in creating menus. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
643
Handling Mouse Events Mouse events include such user interactions as
moving the mouse dragging the mouse (moving the mouse while the mouse button is being pressed) clicking the mouse buttons. The MouseListener interface handles mouse button mouseClicked, mouseEntered, mouseExited, mousePressed, and mouseReleased The MouseMotionListener interface handles mouse movement mouseDragged and mouseMoved. See Ch14TrackMouseFrame and Ch14SketchPad ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
644
Chapter 15 Recursive Algorithms
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
645
Intro to OOP with Java, C. Thomas Wu
Objectives After you have read and studied this chapter, you should be able to Write recursive algorithms for mathematical functions and nonnumerical operations. Decide when to use recursion and when not to. Describe the recursive quicksort algorithm and explain how its performance is better than selection and bubble sort algorithms. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
646
Intro to OOP with Java, C. Thomas Wu
Recursion The factorial of N is the product of the first N positive integers: N * (N – 1) * (N – 2 ) * * 2 * 1 The factorial of N can be defined recursively as 1 if N = 1 factorial( N ) = N * factorial( N-1 ) otherwise The two most important concepts in object-oriented programming are the class and the object. In the broadest term, an object is a thing, both tangible and intangible, which we can imagine. A program written in object-oriented style will consist of interacting objects. For a program to maintain bank accounts for a bank, we may have many Account, Customer, Transaction, and ATM objects. An object is comprised of data and operations that manipulate these data. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
647
Intro to OOP with Java, C. Thomas Wu
Recursive Method An recursive method is a method that contains a statement (or statements) that makes a call to itself. Implementing the factorial of N recursively will result in the following method. public int factorial( int N ) { if ( N == 1 ) { return 1; } else { return N * factorial( N-1 ); } } Test to stop or continue. End case: recursion stops. The two most important concepts in object-oriented programming are the class and the object. In the broadest term, an object is a thing, both tangible and intangible, which we can imagine. A program written in object-oriented style will consist of interacting objects. For a program to maintain bank accounts for a bank, we may have many Account, Customer, Transaction, and ATM objects. An object is comprised of data and operations that manipulate these data. Recursive case: recursion continues. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
648
Intro to OOP with Java, C. Thomas Wu
Directory Listing List the names of all files in a given directory and its subdirectories. public void directoryListing(File dir) { //assumption: dir represents a directory String[] fileList = dir.list(); //get the contents String dirPath = dir.getAbsolutePath(); for (int i = 0; i < fileList.length; i++) { File file = new File(dirPath + "/" + fileList[i]); if (file.isFile()) { //it's a file System.out.println( file.getName() ); } else { directoryListing( file ); //it's a directory } //so make a } //recursive call } Test In pseudocode the above method is expressed as follows: public void directoryListing( File dir ) { //assumption: dir represents a directory fileList = an array of names of files and subdirectories in the directory dir; for (each element in fileList) { if (an element is a file) { output the element’s filename; //end case: it’s //a file. } else { //recursive case: it’s a directory call directoryListing with element as an argument; End case Recursive case ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
649
Intro to OOP with Java, C. Thomas Wu
Anagram List all anagrams of a given word. C A T Word C T A A T C A C T T C A T A C Anagrams In pseudocode the above method is expressed as follows: public void directoryListing( File dir ) { //assumption: dir represents a directory fileList = an array of names of files and subdirectories in the directory dir; for (each element in fileList) { if (an element is a file) { output the element’s filename; //end case: it’s //a file. } else { //recursive case: it’s a directory call directoryListing with element as an argument; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
650
Intro to OOP with Java, C. Thomas Wu
Anagram Solution The basic idea is to make recursive calls on a sub-word after every rotation. Here’s how: C A T C T A C A T Recursion Rotate Left A T C A C T A T C Recursion In pseudocode the above method is expressed as follows: public void directoryListing( File dir ) { //assumption: dir represents a directory fileList = an array of names of files and subdirectories in the directory dir; for (each element in fileList) { if (an element is a file) { output the element’s filename; //end case: it’s //a file. } else { //recursive case: it’s a directory call directoryListing with element as an argument; Rotate Left T C A T A C T C A Recursion ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
651
Intro to OOP with Java, C. Thomas Wu
Anagram Method public void anagram( String prefix, String suffix ) { String newPrefix, newSuffix; int numOfChars = suffix.length(); if (numOfChars == 1) { //End case: print out one anagram System.out.println( prefix + suffix ); } else { for (int i = 1; i <= numOfChars; i++ ) { newSuffix = suffix.substring(1, numOfChars); newPrefix = prefix + suffix.charAt(0); anagram( newPrefix, newSuffix ); //recursive call //rotate left to create a rearranged suffix suffix = newSuffix + suffix.charAt(0); } Test End case Recursive case In pseudocode the above method is expressed as follows: public void directoryListing( File dir ) { //assumption: dir represents a directory fileList = an array of names of files and subdirectories in the directory dir; for (each element in fileList) { if (an element is a file) { output the element’s filename; //end case: it’s //a file. } else { //recursive case: it’s a directory call directoryListing with element as an argument; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
652
Towers of Hanoi The goal of the Towers of Hanoi puzzle is to move N disks from peg 1 to peg 3: You must move one disk at a time. You must never place a larger disk on top of a smaller disk. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
653
Towers of Hanoi Solution
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
654
Intro to OOP with Java, C. Thomas Wu
towersOfHanoi Method public void towersOfHanoi(int N, //number of disks int from, //origin peg int to, //destination peg int spare ){//"middle" peg if ( N == 1 ) { moveOne( from, to ); } else { towersOfHanoi( N-1, from, spare, to ); towersOfHanoi( N-1, spare, to, from ); } private void moveOne( int from, int to ) { System.out.println( from + " ---> " + to ); Test End case Recursive case In pseudocode the above method is expressed as follows: public void directoryListing( File dir ) { //assumption: dir represents a directory fileList = an array of names of files and subdirectories in the directory dir; for (each element in fileList) { if (an element is a file) { output the element’s filename; //end case: it’s //a file. } else { //recursive case: it’s a directory call directoryListing with element as an argument; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
655
Quicksort To sort an array from index low to high, we first select a pivot element p. Any element may be used for the pivot, but for this example we will user number[low]. Move all elements less than the pivot to the first half of an array and all elements larger than the pivot to the second half. Put the pivot in the middle. Recursively apply quicksort on the two halves. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
656
Quicksort Partition ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
657
quicksort Method public void quickSort( int[] number,
int low, int high ) { if ( low < high ) { int mid = partition( number, low, high ); quickSort( number, low, mid-1 ); quickSort( number, mid+1, high ); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
658
Quicksort Performance
Intro to OOP with Java, C. Thomas Wu Quicksort Performance In the worst case, quicksort executes roughly the same number of comparisons as the selection sort and bubble sort. On average, we can expect a partition process to split the array into two roughly equal subarrays. When the size of all subarrays becomes 1, the array is sorted. The total number of comparisons for sorting the whole array is K * N N = 2K log2N = K KN = N log2N ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
659
When Not to Use Recursion
When recursive algorithms are designed carelessly, it can lead to very inefficient and unacceptable solutions. For example, consider the following: public int fibonacci( int N ) { if (N == 0 || N == 1) { return 1; } else { return fibonacci(N-1) + fibonacci(N-2); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
660
Excessive Repetition Recursive Fibonacci ends up repeating the same computation numerous times. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
661
Nonrecursive Fibonacci
Intro to OOP with Java, C. Thomas Wu Nonrecursive Fibonacci public int fibonacci( int N ) { int fibN, fibN1, fibN2, cnt; if (N == 0 || N == 1 ) { return 1; } else { fibN1 = fibN2 = 1; cnt = 2; while ( cnt <= N ) { fibN = fibN1 + fibN2; //get the next fib no. fibN1 = fibN2; fibN2 = fibN; cnt ++; } return fibN; A nonrecursive version is just as easy to understand and has much better performance. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
662
When Not to Use Recursion
In general, use recursion if A recursive solution is natural and easy to understand. A recursive solution does not result in excessive duplicate computation. The equivalent iterative solution is too complex. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.