LiveLab is a programming course assessment and management system. Students can .... B MySQL Tutorial. C Oracle Tutorial.
INTRODUCTION TO
JAVA TM
PROGRAMMING
This page intentionally left blank
INTRODUCTION TO
JAVA TM
PROGRAMMING BRIEF VERSION Eighth Edition
Y. Daniel Liang Armstrong Atlantic State University
Prentice Hall Boston Columbus Indianapolis New York San Francisco Upper Saddle River Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
Vice President and Editorial Director, ECS: Marcia J. Horton Editor in Chief, Computer Science: Michael Hirsch Executive Editor: Tracy Dunkelberger Assistant Editor: Melinda Haggerty Editorial Assistant: Allison Michael Vice President, Production: Vince O’Brien Senior Managing Editor: Scott Disanno Production Editor: Irwin Zucker Senior Operations Specialist: Alan Fischer Marketing Manager: Erin Davis Marketing Assistant: Mack Patterson Art Director: Kenny Beck Cover Image: Male Ruby-throated Hummingbird / Steve Byland / Shutterstock; Hummingbird, Nazca Lines / Gary Yim / Shutterstock Art Editor: Greg Dulles Media Editor: Daniel Sandin
Copyright © 2011, 2009, 2007, 2004 by Pearson Higher Education. Upper Saddle River, New Jersey, 07458. All right reserved. Manufactured in the United States of America. This publication is protected by Copyright and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission(s) to use materials from this work, please submit a written request to Pearson Higher Education, Permissions Department, 1 Lake Street, Upper Saddle River, NJ 07458. The author and publisher of this book have used their best efforts in preparing this book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The author and publisher make no warranty of any kind, expressed or implied, with regard to these programs or the documentation contained in this book. The author and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs. Library of Congress Cataloging-in-Publication correct" : " wrong"); } long endTime = System.currentTimeMillis(); long testTime = endTime - startTime; System.out.println("Correct count is " + correctCount + "\nTest time is " + testTime / 1000 + " seconds\n" + output);
What is 9 – 2? 7 You are correct! What is 3 – 0? 3 You are correct! What is 3 – 2? 1 You are correct! What is 7 – 4? 4 Your answer is wrong. 7 – 4 should be 3 What is 7 – 5? 4 Your answer is wrong. 7 – 5 should be 2 Correct count is 3 Test time is 1021 seconds 9–2=7 3–0=3 3–2=1 7–4=4 7–5=4
correct correct correct wrong wrong
The program uses the control variable count to control the execution of the loop. count is initially 0 (line 7) and is increased by 1 in each iteration (line 39). A subtraction question is displayed and processed in each iteration. The program obtains the time before the test starts in line 8 and the time after the test ends in line 45, and computes the test time in line 46. The test time is in milliseconds and is converted to seconds in line 49.
4.2.4 sentinel value
Controlling a Loop with a Sentinel Value
Another common technique for controlling a loop is to designate a special value when reading and processing a set of values. This special input value, known as a sentinel value, signifies the end of the loop. A loop that uses a sentinel value to control its execution is called a sentinel-controlled loop. Listing 4.4 writes a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input. Do you need to declare a new variable for each input value? No. Just use one variable named ; System.out.println(s.charAt(3)); }
454 Chapter 13
Exception Handling catch (RuntimeException ex) { System.out.println("RuntimeException in method()"); } catch (Exception ex) { System.out.println("Exception in method()"); } } }
13.14 What does the method getMessage() do? 13.15 What does the method printStackTrace do? 13.16 Does the presence of a try-catch block impose overhead when no exception occurs?
13.17 Correct a compile error in the following code: public void m(int value) { if (value < 40) throw new Exception("value is too small"); }
Sections 13.4–13.10
13.18 Suppose that statement2 causes an exception in the following statement: try { statement1; statement2; statement3; } catch (Exception1 ex1) { } catch (Exception2 ex2) { } catch (Exception3 ex3) { throw ex3; } finally { statement4; }; statement5;
Answer the following questions: ■ ■
Will statement5 be executed if the exception is not caught? If the exception is of type Exception3, will statement4 be executed, and will statement5 be executed?
13.19 Suppose the setRadius method throws the RadiusException defined in §13.7. What is displayed when the following program is run? public class Test { public static void main(String[] args) { try { method(); System.out.println("After the method call"); } catch (RuntimeException ex) { System.out.println("RuntimeException in main"); }
Programming Exercises 455 catch (Exception ex) { System.out.println("Exception in main"); } } static void method() throws Exception { try { Circle c1 = new Circle(1); c1.setRadius(-1); System.out.println(c1.getRadius()); } catch (RuntimeException ex) { System.out.println("RuntimeException in method()"); } catch (Exception ex) { System.out.println("Exception in method()"); throw ex; } } }
13.20 The following method checks whether a string is a numeric string: public static boolean isNumeric(String token) { try { Double.parseDouble(token); return true; } catch (java.lang.NumberFormatException ex) { return false; } }
Is it correct? Rewrite it without using exceptions.
PROGRAMMING EXERCISES Sections 13.2–13.10
13.1* (NumberFormatException) Listing 9.5, Calculator.java, is a simple commandline calculator. Note that the program terminates if any operand is nonnumeric. Write a program with an exception handler that deals with nonnumeric operands; then write another program without using an exception handler to achieve the same objective. Your program should display a message that informs the user of the wrong operand type before exiting (see Figure 13.6).
FIGURE 13.6
The program performs arithmetic operations and detects input errors.
456 Chapter 13
Exception Handling 13.2* (NumberFormatException) Write a program that prompts the user to read two 13.3*
integers and displays their sum. Your program should prompt the user to read the number again if the input is incorrect. (ArrayIndexOutBoundsException) Write a program that meets the following requirements: ■ ■
Create an array with 100 randomly chosen integers. Prompt the user to enter the index of the array, then display the corresponding element value. If the specified index is out of bounds, display the message Out of Bounds.
13.4* (IllegalArgumentException) Modify the Loan class in Listing 10.2 to throw IllegalArgumentException if the loan amount, interest rate, or number of years is less than or equal to zero.
13.5* (IllegalTriangleException) Exercise 11.1 defined the Triangle class with three sides. In a triangle, the sum of any two sides is greater than the other side. The Triangle class must adhere to this rule. Create the IllegalTriangleException class, and modify the constructor of the Triangle class to throw an IllegalTriangleException object if a triangle is created with sides that violate
the rule, as follows: /** Construct a triangle with the specified sides */ public Triangle(double side1, double side2, double side3) throws IllegalTriangleException { // Implement it }
13.6* (NumberFormatException) Listing 9.2 implements the hexToDecimal(String hexString) method, which converts a hex string into a decimal number. Implement the hexToDecimal method to throw a NumberFormatException if the
Video Note HexFormatException
string is not a hex string. 13.7* (NumberFormatException) Exercise 9.8 specifies the binaryToDecimal(String binaryString) method, which converts a binary string into a decimal number. Implement the binaryToDecimal method to throw a NumberFormatException if the string is not a binary string. 13.8* (HexFormatException) Exercise 13.6 implements the hexToDecimal method to throw a NumberFormatException if the string is not a hex string. Define a custom exception called HexFormatException. Implement the hexToDecimal method to throw a HexFormatException if the string is not a hex string. 13.9* (BinaryFormatException) Exercise 13.7 implements the binaryToDecimal method to throw a BinaryFormatException if the string is not a binary string. Define a custom exception called BinaryFormatException. Implement the binaryToDecimal method to throw a BinaryFormatException if the string is not a binary string. 13.10* (OutOfMemoryError) Write a program that causes the JVM to throw an OutOfMemoryError and catches and handles this error.
CHAPTER 14 ABSTRACT CLASSES AND INTERFACES Objectives ■
To design and use abstract classes (§14.2).
■
To process a calendar using the Calendar and GregorianCalendar classes (§14.3).
■
To specify common behavior for objects using interfaces (§14.4).
■
To define interfaces and define classes that implement interfaces (§14.4).
■
To define a natural order using the Comparable interface (§14.5).
■
To enable objects to listen for action events using the ActionListener interface (§14.6).
■
To make objects cloneable using the Cloneable interface (§14.7).
■
To explore the similarities and differences between an abstract class and an interface (§14.8).
■
To create objects for primitive values using the wrapper classes (Byte, Short, Integer, Long, Float, Double, Character, and Boolean) (§14.9).
■
To create a generic sort method (§14.10).
■
To simplify programming using automatic conversion between primitive types and wrapper class types (§14.11).
■
To use the BigInteger and BigDecimal classes for computing very large numbers with arbitrary precisions (§14.12).
■
To design the Rational class for defining the Rational type (§14.13).
458 Chapter 14
Abstract Classes and Interfaces
14.1 Introduction problem
You have learned how to write simple programs to create and display GUI components. Can you write the code to respond to user actions, such as clicking a button? As shown in Figure 14.1, when a button is clicked, a message is displayed on the console.
FIGURE 14.1 The program responds to button-clicking action events. In order to write such code, you have to know interfaces. An interface is for defining common behavior for classes (especially unrelated classes). Before discussing interfaces, we introduce a closely related subject: abstract classes.
14.2 Abstract Classes Video Note Abstract GeometricObject Class
abstract class
abstract method abstract modifier
In the inheritance hierarchy, classes become more specific and concrete with each new subclass. If you move from a subclass back up to a superclass, the classes become more general and less specific. Class design should ensure that a superclass contains common features of its subclasses. Sometimes a superclass is so abstract that it cannot have any specific instances. Such a class is referred to as an abstract class. In Chapter 11, GeometricObject was defined as the superclass for Circle and Rectangle. GeometricObject models common features of geometric objects. Both Circle and Rectangle contain the getArea() and getPerimeter() methods for computing the area and perimeter of a circle and a rectangle. Since you can compute areas and perimeters for all geometric objects, it is better to define the getArea() and getPerimeter() methods in the GeometricObject class. However, these methods cannot be implemented in the GeometricObject class, because their implementation depends on the specific type of geometric object. Such methods are referred to as abstract methods and are denoted using the abstract modifier in the method header. After you define the methods in GeometricObject, it becomes an abstract class. Abstract classes are denoted using the abstract modifier in the class header. In UML graphic notation, the names of abstract classes and their abstract methods are italicized, as shown in Figure 14.2. Listing 14.1 gives the source code for the new GeometricObject class.
LISTING 14.1 GeometricObject.java abstract class
1 public abstract class GeometricObject { 2 private String color = "white"; 3 private boolean filled; 4 private java.util.Date dateCreated; 5 6 /** Construct a default geometric object */ 7 protected GeometricObject() { 8 dateCreated = new java.util.Date(); 9 } 10 11 /** Construct a geometric object with color and filled value */ 12 protected GeometricObject(String color, boolean filled) { 13 dateCreated = new java.util.Date();
14.2 Abstract Classes 459 GeometricObject
Abstract class
-color: String -filled: boolean -dateCreated: java.util.Date The # sign indicates protected modifier
#GeometricObject() #GeometricObject(color: string, filled: boolean) +getColor(): String +setColor(color: String): void +isFilled(): boolean +setFilled(filled: boolean): void +getDateCreated(): java.util.Date +toString(): String
Abstract methods are italicized
+getArea(): double +getPerimeter(): double
Circle
-radius: double +Circle() +Circle(radius: double) +Circle(radius: double, color. string, filled: boolean) +getRadius(): double
Methods getArea and getPerimeter are overridden in Circle and Rectangle. Superclass methods are generally omitted in the UML diagram for subclasses. Rectangle
-width: double -height: double +Rectangle() +Rectangle(width: double, height: double)
+setRadius(radius: double): void
+Rectangle(width: double, height: double, color: string, filled: boolean) +getWidth(): double
+getDiameter(): double
+setWidth(width: double): void +getHeight(): double +setHeight(height: double): void
FIGURE 14.2
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
The new GeometricObject class contains abstract methods.
this.color = color; this.filled = filled; } /** Return color */ public String getColor() { return color; } /** Set a new color */ public void setColor(String color) { this.color = color; } /** Return filled. Since filled is boolean, * the get method is named isFilled */ public boolean isFilled() { return filled; }
460 Chapter 14
abstract method
abstract method
why protected constructor?
implementing Circle implementing Rectangle
Abstract Classes and Interfaces 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 }
/** Set a new filled */ public void setFilled(boolean filled) { this.filled = filled; } /** Get dateCreated */ public java.util.Date getDateCreated() { return dateCreated; } /** Return a string representation of this object */ public String toString() { return "created on " + dateCreated + "\ncolor: " + color + " and filled: " + filled; } /** Abstract method getArea */ public abstract double getArea(); /** Abstract method getPerimeter */ public abstract double getPerimeter();
Abstract classes are like regular classes, but you cannot create instances of abstract classes using the new operator. An abstract method is defined without implementation. Its implementation is provided by the subclasses. A class that contains abstract methods must be defined abstract. The constructor in the abstract class is defined protected, because it is used only by subclasses. When you create an instance of a concrete subclass, its superclass’s constructor is invoked to initialize =>"); public static void main(String[] args) { ButtonDemo frame = new ButtonDemo(); frame.setTitle("ButtonDemo"); frame.setSize(250, 100); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public ButtonDemo() { // Set the background color of messagePanel messagePanel.setBackground(Color.white); // Create Panel jpButtons to hold two Buttons "" JPanel jpButtons = new JPanel(); jpButtons.add(jbtLeft); jpButtons.add(jbtRight); // Set keyboard mnemonics jbtLeft.setMnemonic('L'); jbtRight.setMnemonic('R');
// // //
// Set icons and remove text jbtLeft.setIcon(new ImageIcon("image/left.gif")); jbtRight.setIcon(new ImageIcon("image/right.gif")); jbtLeft.setText(null);
17.2 Buttons 577 41 // 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 } 64 }
jbtRight.setText(null); // Set tool tip text on the buttons jbtLeft.setToolTipText("Move message to left"); jbtRight.setToolTipText("Move message to right");
tool tip
// Place panels in the frame setLayout(new BorderLayout()); add(messagePanel, BorderLayout.CENTER); add(jpButtons, BorderLayout.SOUTH); // Register listeners with the buttons jbtLeft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { messagePanel.moveLeft(); } }); jbtRight.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { messagePanel.moveRight(); } });
register listener
register listener
messagePanel (line 8) is deliberately declared protected so that it can be referenced by a subclass in future examples. You can set an icon image on the button by using the setIcon method. If you uncomment the following code in lines 38–41: // // // //
jbtLeft.setIcon(new ImageIcon("image/left.gif")); jbtRight.setIcon(new ImageIcon("image/right.gif")); jbtLeft.setText(null); jbtRight.setText(null);
the texts are replaced by the icons, as shown in Figure 17.10(a). "image/left.gif" is located in "c:\book\image\left.gif". Note that the backslash is the Windows file-path notation. In Java, the forward slash should be used.
(a)
FIGURE 17.10
(b)
(c)
You can set an icon on a JButton and access a button using its mnemonic key.
You can set text and an icon on a button at the same time, if you wish, as shown in Figure 17.10(b). By default, the text and icon are centered horizontally and vertically. The button can also be accessed by using the keyboard mnemonics. Pressing Alt+L is equivalent to clicking the = 'A') && (character = 'a') && (character