- •CONTENTS
- •1.1 Introduction
- •1.2 What Is a Computer?
- •1.3 Programs
- •1.4 Operating Systems
- •1.5 Java, World Wide Web, and Beyond
- •1.6 The Java Language Specification, API, JDK, and IDE
- •1.7 A Simple Java Program
- •1.8 Creating, Compiling, and Executing a Java Program
- •1.9 (GUI) Displaying Text in a Message Dialog Box
- •2.1 Introduction
- •2.2 Writing Simple Programs
- •2.3 Reading Input from the Console
- •2.4 Identifiers
- •2.5 Variables
- •2.7 Named Constants
- •2.8 Numeric Data Types and Operations
- •2.9 Problem: Displaying the Current Time
- •2.10 Shorthand Operators
- •2.11 Numeric Type Conversions
- •2.12 Problem: Computing Loan Payments
- •2.13 Character Data Type and Operations
- •2.14 Problem: Counting Monetary Units
- •2.15 The String Type
- •2.16 Programming Style and Documentation
- •2.17 Programming Errors
- •2.18 (GUI) Getting Input from Input Dialogs
- •3.1 Introduction
- •3.2 boolean Data Type
- •3.3 Problem: A Simple Math Learning Tool
- •3.4 if Statements
- •3.5 Problem: Guessing Birthdays
- •3.6 Two-Way if Statements
- •3.7 Nested if Statements
- •3.8 Common Errors in Selection Statements
- •3.9 Problem: An Improved Math Learning Tool
- •3.10 Problem: Computing Body Mass Index
- •3.11 Problem: Computing Taxes
- •3.12 Logical Operators
- •3.13 Problem: Determining Leap Year
- •3.14 Problem: Lottery
- •3.15 switch Statements
- •3.16 Conditional Expressions
- •3.17 Formatting Console Output
- •3.18 Operator Precedence and Associativity
- •3.19 (GUI) Confirmation Dialogs
- •4.1 Introduction
- •4.2 The while Loop
- •4.3 The do-while Loop
- •4.4 The for Loop
- •4.5 Which Loop to Use?
- •4.6 Nested Loops
- •4.7 Minimizing Numeric Errors
- •4.8 Case Studies
- •4.9 Keywords break and continue
- •4.10 (GUI) Controlling a Loop with a Confirmation Dialog
- •5.1 Introduction
- •5.2 Defining a Method
- •5.3 Calling a Method
- •5.4 void Method Example
- •5.5 Passing Parameters by Values
- •5.6 Modularizing Code
- •5.7 Problem: Converting Decimals to Hexadecimals
- •5.8 Overloading Methods
- •5.9 The Scope of Variables
- •5.10 The Math Class
- •5.11 Case Study: Generating Random Characters
- •5.12 Method Abstraction and Stepwise Refinement
- •6.1 Introduction
- •6.2 Array Basics
- •6.3 Problem: Lotto Numbers
- •6.4 Problem: Deck of Cards
- •6.5 Copying Arrays
- •6.6 Passing Arrays to Methods
- •6.7 Returning an Array from a Method
- •6.8 Variable-Length Argument Lists
- •6.9 Searching Arrays
- •6.10 Sorting Arrays
- •6.11 The Arrays Class
- •7.1 Introduction
- •7.2 Two-Dimensional Array Basics
- •7.3 Processing Two-Dimensional Arrays
- •7.4 Passing Two-Dimensional Arrays to Methods
- •7.5 Problem: Grading a Multiple-Choice Test
- •7.6 Problem: Finding a Closest Pair
- •7.7 Problem: Sudoku
- •7.8 Multidimensional Arrays
- •8.1 Introduction
- •8.2 Defining Classes for Objects
- •8.3 Example: Defining Classes and Creating Objects
- •8.4 Constructing Objects Using Constructors
- •8.5 Accessing Objects via Reference Variables
- •8.6 Using Classes from the Java Library
- •8.7 Static Variables, Constants, and Methods
- •8.8 Visibility Modifiers
- •8.9 Data Field Encapsulation
- •8.10 Passing Objects to Methods
- •8.11 Array of Objects
- •9.1 Introduction
- •9.2 The String Class
- •9.3 The Character Class
- •9.4 The StringBuilder/StringBuffer Class
- •9.5 Command-Line Arguments
- •9.6 The File Class
- •9.7 File Input and Output
- •9.8 (GUI) File Dialogs
- •10.1 Introduction
- •10.2 Immutable Objects and Classes
- •10.3 The Scope of Variables
- •10.4 The this Reference
- •10.5 Class Abstraction and Encapsulation
- •10.6 Object-Oriented Thinking
- •10.7 Object Composition
- •10.8 Designing the Course Class
- •10.9 Designing a Class for Stacks
- •10.10 Designing the GuessDate Class
- •10.11 Class Design Guidelines
- •11.1 Introduction
- •11.2 Superclasses and Subclasses
- •11.3 Using the super Keyword
- •11.4 Overriding Methods
- •11.5 Overriding vs. Overloading
- •11.6 The Object Class and Its toString() Method
- •11.7 Polymorphism
- •11.8 Dynamic Binding
- •11.9 Casting Objects and the instanceof Operator
- •11.11 The ArrayList Class
- •11.12 A Custom Stack Class
- •11.13 The protected Data and Methods
- •11.14 Preventing Extending and Overriding
- •12.1 Introduction
- •12.2 Swing vs. AWT
- •12.3 The Java GUI API
- •12.4 Frames
- •12.5 Layout Managers
- •12.6 Using Panels as Subcontainers
- •12.7 The Color Class
- •12.8 The Font Class
- •12.9 Common Features of Swing GUI Components
- •12.10 Image Icons
- •13.1 Introduction
- •13.2 Exception-Handling Overview
- •13.3 Exception-Handling Advantages
- •13.4 Exception Types
- •13.5 More on Exception Handling
- •13.6 The finally Clause
- •13.7 When to Use Exceptions
- •13.8 Rethrowing Exceptions
- •13.9 Chained Exceptions
- •13.10 Creating Custom Exception Classes
- •14.1 Introduction
- •14.2 Abstract Classes
- •14.3 Example: Calendar and GregorianCalendar
- •14.4 Interfaces
- •14.5 Example: The Comparable Interface
- •14.6 Example: The ActionListener Interface
- •14.7 Example: The Cloneable Interface
- •14.8 Interfaces vs. Abstract Classes
- •14.9 Processing Primitive Data Type Values as Objects
- •14.10 Sorting an Array of Objects
- •14.11 Automatic Conversion between Primitive Types and Wrapper Class Types
- •14.12 The BigInteger and BigDecimal Classes
- •14.13 Case Study: The Rational Class
- •15.1 Introduction
- •15.2 Graphical Coordinate Systems
- •15.3 The Graphics Class
- •15.4 Drawing Strings, Lines, Rectangles, and Ovals
- •15.5 Case Study: The FigurePanel Class
- •15.6 Drawing Arcs
- •15.7 Drawing Polygons and Polylines
- •15.8 Centering a String Using the FontMetrics Class
- •15.9 Case Study: The MessagePanel Class
- •15.10 Case Study: The StillClock Class
- •15.11 Displaying Images
- •15.12 Case Study: The ImageViewer Class
- •16.1 Introduction
- •16.2 Event and Event Source
- •16.3 Listeners, Registrations, and Handling Events
- •16.4 Inner Classes
- •16.5 Anonymous Class Listeners
- •16.6 Alternative Ways of Defining Listener Classes
- •16.7 Problem: Loan Calculator
- •16.8 Window Events
- •16.9 Listener Interface Adapters
- •16.10 Mouse Events
- •16.11 Key Events
- •16.12 Animation Using the Timer Class
- •17.1 Introduction
- •17.2 Buttons
- •17.3 Check Boxes
- •17.4 Radio Buttons
- •17.5 Labels
- •17.6 Text Fields
- •17.7 Text Areas
- •17.8 Combo Boxes
- •17.9 Lists
- •17.10 Scroll Bars
- •17.11 Sliders
- •17.12 Creating Multiple Windows
- •18.1 Introduction
- •18.2 Developing Applets
- •18.3 The HTML File and the <applet> Tag
- •18.4 Applet Security Restrictions
- •18.5 Enabling Applets to Run as Applications
- •18.6 Applet Life-Cycle Methods
- •18.7 Passing Strings to Applets
- •18.8 Case Study: Bouncing Ball
- •18.9 Case Study: TicTacToe
- •18.10 Locating Resources Using the URL Class
- •18.11 Playing Audio in Any Java Program
- •18.12 Case Study: Multimedia Animations
- •19.1 Introduction
- •19.2 How is I/O Handled in Java?
- •19.3 Text I/O vs. Binary I/O
- •19.4 Binary I/O Classes
- •19.5 Problem: Copying Files
- •19.6 Object I/O
- •19.7 Random-Access Files
- •20.1 Introduction
- •20.2 Problem: Computing Factorials
- •20.3 Problem: Computing Fibonacci Numbers
- •20.4 Problem Solving Using Recursion
- •20.5 Recursive Helper Methods
- •20.6 Problem: Finding the Directory Size
- •20.7 Problem: Towers of Hanoi
- •20.8 Problem: Fractals
- •20.9 Problem: Eight Queens
- •20.10 Recursion vs. Iteration
- •20.11 Tail Recursion
- •APPENDIXES
- •INDEX
320 Chapter 9 Strings and Text I/O
Enter a string: ab<c>cb?a Ignoring nonalphanumeric characters, is ab<c>cb?a a palindrome? true
Enter a string: abcc><?cab Ignoring nonalphanumeric characters, is abcc><?cab a palindrome? false
The filter(String s) method (lines 31–44) examines each character in string s and copies it to a string builder if the character is a letter or a numeric character. The filter method returns the string in the builder. The reverse(String s) method (lines 47–52) creates a new string that reverses the specified string s. The filter and reverse methods both return a new string. The original string is not changed.
The program in Listing 9.1 checks whether a string is a palindrome by comparing pairs of characters from both ends of the string. Listing 9.4 uses the reverse method in the StringBuilder class to reverse the string, then compares whether the two strings are equal to determine whether the original string is a palindrome.
9.5 Command-Line Arguments
Perhaps you have already noticed the unusual declarations for the main method, which has parameter args of String[] type. It is clear that args is an array of strings. The main method is just like a regular method with a parameter. You can call a regular method by passing actual parameters. Can you pass arguments to main? Yes, of course you can. For example, the main method in class TestMain is invoked by a method in A, as shown below:
public class A { |
|
public class TestMain { |
||||
public static void main(String[] args) { |
|
|
public static void main(String[] args) |
{ |
||
String[] strings = {"New York", |
|
|
for (int i = 0; i < args.length; i++) |
|
||
|
"Boston", "Atlanta"}; |
|
|
System.out.println(args[i]); |
||
|
TestMain.main(strings); |
|
|
} |
|
|
} |
|
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
A main method is just a regular method. Furthermore, you can pass arguments from the command line.
9.5.1Passing Strings to the main Method
You can pass strings to a main method from the command line when you run the program. The following command line, for example, starts the program TestMain with three strings: arg0, arg1, and arg2:
java TestMain arg0 arg1 arg2
arg0, arg1, and arg2 are strings, but they don’t have to appear in double quotes on the command line. The strings are separated by a space. A string that contains a space must be enclosed in double quotes. Consider the following command line:
java TestMain "First num" alpha 53
It starts the program with three strings: "First num", alpha, and 53, a numeric string. Since "First num" is a string, it is enclosed in double quotes. Note that 53 is actually treated as a string. You can use "53" instead of 53 in the command line.
9.5 Command-Line Arguments 321
When the main method is invoked, the Java interpreter creates an array to hold the com- mand-line arguments and pass the array reference to args. For example, if you invoke a program with n arguments, the Java interpreter creates an array like this one:
args = new String[n];
The Java interpreter then passes args to invoke the main method.
Note
If you run the program with no strings passed, the array is created with new String[0]. In this case, the array is empty with length 0. args references to this empty array. Therefore, args is not null, but args.length is 0.
9.5.2Problem: Calculator
Suppose you are to develop a program that performs arithmetic operations on integers. The program receives three arguments: an integer followed by an operator and another integer. For example, to add two integers, use this command:
java Calculator 2 + 3
The program will display the following output:
2 + 3 = 5
Figure 9.14 shows sample runs of the program.
Add
Subtract
Multiply
Divide
Video Note
Command-line argument
FIGURE 9.14 The program takes three arguments (operand1 operator operand2) from the command line and displays the expression and the result of the arithmetic operation.
The strings passed to the main program are stored in args, which is an array of strings. The first string is stored in args[0], and args.length is the number of strings passed.
Here are the steps in the program:
■Use args.length to determine whether three arguments have been provided in the command line. If not, terminate the program using System.exit(0).
■Perform a binary arithmetic operation on the operands args[0] and args[2] using the operator specified in args[1].
The program is shown in Listing 9.5.
LISTING 9.5 Calculator.java
1 public class Calculator {
2/** Main method */
3 public static void main(String[] args) {
322 Chapter 9 |
Strings and Text I/O |
||||||||||||
|
4 |
// Check number of strings passed |
|||||||||||
|
5 |
if |
(args.length |
!= 3) { |
|||||||||
|
6 |
System.out.println( |
|||||||||||
|
7 |
|
"Usage: java Calculator operand1 operator operand2"); |
||||||||||
|
8 |
System.exit(0); |
|||||||||||
|
9 |
} |
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
// The result of the operation |
|||||||||||
|
12 |
int result = 0; |
|||||||||||
|
13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
// Determine the operator |
|||||||||||
check operator |
15 |
switch |
(args[1].charAt(0) |
) { |
|||||||||
|
16 |
case '+': result = Integer.parseInt(args[ |
0]) + |
||||||||||
|
17 |
|
|
|
|
Integer.parseInt(args[ |
2] |
); |
|||||
|
18 |
|
|
break; |
|||||||||
|
19 |
case '-': result = Integer.parseInt(args[ |
0] |
) - |
|||||||||
|
20 |
|
|
|
|
Integer.parseInt(args[ |
2] |
); |
|||||
|
21 |
|
|
break; |
|||||||||
|
22 |
case '*': result = Integer.parseInt(args[ |
0] |
) * |
|||||||||
|
23 |
|
|
|
|
Integer.parseInt(args[ |
2] |
); |
|||||
|
24 |
|
|
break; |
|||||||||
|
25 |
case '/': result = Integer.parseInt(args[ |
0] |
) / |
|||||||||
|
26 |
|
|
|
|
Integer.parseInt(args[ |
2] |
); |
|||||
|
27 |
} |
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
// Display result |
|||||||||||
|
30 |
System.out.println(args[ |
0] |
+ ' ' + |
args[1] |
+ ' ' + |
args[2] |
||||||
|
31 |
+ " = " + result); |
|||||||||||
|
32 |
} |
|
|
|
|
|
|
|
|
|
|
|
|
33 |
} |
|
|
|
|
|
|
|
|
|
|
|
Integer.parseInt(args[0]) (line 16) converts a digital string into an integer. The string must consist of digits. If not, the program will terminate abnormally.
|
Note |
special * character |
In the sample run, "*" had to be used instead of * for the command |
java Calculator 63 "*" 40
The * symbol refers to all the files in the current directory when it is used on a command line. Therefore, in order to specify the multiplication operator, the * must be enclosed in quote marks in the command line. The following program displays all the files in the current directory when issuing the command java Test *:
public class Test {
public static void main(String[] args) { for (int i = 0; i < args.length; i++)
System.out.println(args[i]);
}
}
9.6 The File Class
Data stored in variables, arrays, and objects are temporary; they are lost when the program terminates. To permanently store the data created in a program, you need to save them in a file on a disk or a CD. The file can be transported and can be read later by other programs. Since
why file? data are stored in files, this section introduces how to use the File class to obtain file properties and to delete and rename files. The next section introduces how to read/write data from/to text files.
9.6 The File Class 323
Every file is placed in a directory in the file system. An absolute file name contains a file name with its complete path and drive letter. For example, c:\book\Welcome.java is the absolute file name for the file Welcome.java on the Windows operating system. Here c:\book is referred to as the directory path for the file. Absolute file names are machine dependent. On the Unix platform, the absolute file name may be /home/liang/book/Welcome.java, where /home/liang/book is the directory path for the file Welcome.java.
The File class is intended to provide an abstraction that deals with most of the machinedependent complexities of files and path names in a machine-independent fashion. The File class contains the methods for obtaining file properties and for renaming and deleting files, as shown in Figure 9.15. However, the File class does not contain the methods for reading and writing file contents.
absolute file name
directory path
java.io.File |
|
|
|
|
|
+File(pathname: String) |
|
Creates a File object for the specified path name. The path name may be a |
|
|
directory or a file. |
+File(parent: String, child: String) |
|
Creates a File object for the child under the directory parent. The child may be |
|
|
a file name or a subdirectory. |
+File(parent: File, child: String) |
|
Creates a File object for the child under the directory parent. The parent is a |
|
|
File object. In the preceding constructor, the parent is a string. |
+exists(): boolean |
|
Returns true if the file or the directory represented by the File object exists. |
+canRead(): boolean |
|
Returns true if the file represented by the File object exists and can be read. |
+canWrite(): boolean |
|
Returns true if the file represented by the File object exists and can be written. |
+isDirectory(): boolean |
|
Returns true if the File object represents a directory. |
+isFile(): boolean |
|
Returns true if the File object represents a file. |
+isAbsolute(): boolean |
|
Returns true if the File object is created using an absolute path name. |
+isHidden(): boolean |
|
Returns true if the file represented in the File object is hidden. The exact |
|
|
definition of hidden is system dependent. On Windows, you can mark a file |
|
|
hidden in the File Properties dialog box. On Unix systems, a file is hidden if |
|
|
its name begins with a period character '.'. |
+getAbsolutePath(): String |
|
Returns the complete absolute file or directory name represented by the File |
|
|
object. |
+getCanonicalPath(): String |
|
Returns the same as getAbsolutePath() except that it removes redundant |
|
|
names, such as "." and "..", from the path name, resolves symbolic links (on |
|
|
Unix platforms), and converts drive letters to standard uppercase (on Win32 |
|
|
platforms). |
+getName(): String |
|
Returns the last name of the complete directory and file name represented by |
|
|
the File object. For example, new File("c:\\book\\test.dat").getName() returns |
|
|
test.dat. |
+getPath(): String |
|
Returns the complete directory and file name represented by the File object. |
|
|
For example, new File("c:\\book\\test.dat").getPath() returns c:\book\test.dat. |
+getParent(): String |
|
Returns the complete parent directory of the current directory or the file |
|
|
represented by the File object. For example, new |
|
|
File("c:\\book\\test.dat").getParent() returns c:\book. |
+lastModified(): long |
|
Returns the time that the file was last modified. |
+length(): long |
|
Returns the size of the file, or 0 if it does not exist or if it is a directory. |
+listFile(): File[] |
|
Returns the files under the directory for a directory File object. |
+delete(): boolean |
|
Deletes this file. The method returns true if the deletion succeeds. |
+renameTo(dest: File): boolean |
|
Renames this file. The method returns true if the operation succeeds. |
|
|
|
FIGURE 9.15 The File class can be used to obtain file and directory properties and to delete and rename files.
The file name is a string. The File class is a wrapper class for the file name and its directory path. For example, new File("c:\\book") creates a File object for the directory c:\book, and new File("c:\\book\\test.dat") creates a File object for the file c:\\book\\test.dat, both on Windows. You can use the File class’s isDirectory() method to check whether the object represents a directory, and the isFile() method to check whether the object represents a file.
Caution
The directory separator for Windows is a backslash (\). The backslash is a special character in |
|
Java and should be written as \\ in a string literal (see Table 2.6). |
\ in file names |
324 Chapter 9 Strings and Text I/O
Note
Constructing a File instance does not create a file on the machine. You can create a File instance for any file name regardless whether it exists or not. You can invoke the exists() method on a File instance to check whether the file exists.
|
Do not use absolute file names in your program. If you use a file name such as |
|
"c:\\book\\Welcome.java", it will work on Windows but not on other platforms. You |
relative file name |
should use a file name relative to the current directory. For example, you may create a File |
|
object using new File("Welcome.java") for the file Welcome.java in the current direc- |
|
tory. You may create a File object using new File("image/us.gif") for the file us.gif |
Java directory separator (/) |
under the image directory in the current directory. The forward slash (/) is the Java directory |
|
separator, which is the same as on Unix. The statement new File("image/us.gif") works |
|
on Windows, Unix, and any other platform. |
|
Listing 9.6 demonstrates how to create a File object and use the methods in the File |
|
class to obtain its properties. The program creates a File object for the file us.gif. This file is |
|
stored under the image directory in the current directory. |
LISTING 9.6 TestFileClass.java
|
1 |
public class TestFileClass { |
||||
|
2 |
public static void main(String[] args) { |
||||
create a File |
3 |
|
java.io.File file = new java.io.File("image/us.gif"); |
|
||
exists() |
4 |
|
System.out.println("Does it exist? " + |
file.exists() |
); |
|
length() |
5 |
|
System.out.println("The file has " + file.length() + " bytes"); |
|||
canRead() |
6 |
|
System.out.println("Can it be read? " + file.canRead()); |
|||
canWrite() |
7 |
|
System.out.println("Can it be written? " + file.canWrite()); |
|||
isDirectory() |
8 |
|
System.out.println("Is it a directory? " + file.isDirectory()); |
|||
isFile() |
9 |
|
System.out.println("Is it a file? " + file.isFile()); |
|||
isAbsolute() |
10 |
|
System.out.println("Is it absolute? " + file.isAbsolute()); |
|||
isHidden() |
11 |
|
System.out.println("Is it hidden? " + file.isHidden()); |
|||
|
12 |
|
System.out.println("Absolute path is " + |
|||
getAbsolutePath() |
13 |
|
file.getAbsolutePath()); |
|||
|
14 |
|
System.out.println("Last modified on " + |
|||
lastModified() |
15 |
|
new java.util.Date(file.lastModified())); |
|||
|
16 |
} |
|
|
|
|
|
17 |
} |
|
|
|
|
The lastModified() method returns the date and time when the file was last modified, measured in milliseconds since the beginning of Unix time (00:00:00 GMT, January 1, 1970). The Date class is used to display it in a readable format in lines 14–15.
(a) On Windows |
(b) On Unix |
FIGURE 9.16 The program creates a File object and displays file properties.