Java Programming
Java Programming
Chapter 1
An Overview of Computers and Programming Languages
Java Programming 2
Chapter Objectives
Learn about different types of computers Explore the hardware and software components of a computer system Learn about the language of a computer Learn about the evolution of programming languages Examine high-level programming languages
Java Programming 3
Chapter Objectives (continued)
Discover what a compiler is and what it does Examine how a Java program is processed Learn what an algorithm is and explore problem-solving techniques Become aware of structured and objectoriented programming design methodologies
Java Programming 4
Introduction
Computers have greatly affected our daily lives helping us complete many tasks Computer programs (software) are designed specifically for each task Software is created with programming languages Java is an example of a programming language
Java Programming 5
An Overview of the History of Computers
The first device known to carry out calculations was the abacus The abacus uses a system of sliding beads on a rack for addition and subtraction Blaise Pascal invented the calculating device called the Pascaline
Java Programming
An Overview of the History of Computers (continued)
In 1819, Joseph Jacquard, a French weaver, discovered that the weaving instructions for his looms could be stored on cards with holes punched in them In the early and mid-1800s, Charles Babbage, an English mathematician and physical scientist, designed two calculating machines: the difference engine and the analytical engine
Java Programming 7
An Overview of the History of Computers (continued)
The first computer-like machine was the Mark I
Built in 1944 Used punched cards to feed data into the machine 52 feet long, weighed 50 tons, and had 750,000 parts
In 1946, ENIAC (Electronic Numerical Integrator and Calculator) was built at the University of Pennsylvania
Contained 18,000 vacuum tubes and weighed some 30 tons
Java Programming 8
An Overview of the History of Computers (continued)
In 1956, the invention of the transistors resulted in smaller, faster, more reliable, and more energy-efficient computers This era also saw the emergence of the software development industry with the introduction of FORTRAN and COBOL, two early programming languages In 1970, the microprocessor, an entire CPU on a single chip, was invented
Java Programming 9
An Overview of the History of Computers (continued)
In 1977, Stephen Wozniak and Steven Jobs designed and built the first Apple computer in their garage In 1981, IBM introduced its personal computer (PC) Modern-day computers are very powerful, reliable, and easy to use
Can accept spoken-word instructions and imitate human reasoning through artificial intelligence
Java Programming 10
An Overview of the History of Computers (continued)
Although there are several categories of computers, such as mainframe, midsize, and micro, all computers share some basic elements
Java Programming
11
Elements of a Computer System
A computer has two components
Hardware Software
Java Programming
12
Hardware Components of a Computer
Central Processing Unit (CPU) Main Memory
Java Programming
13
Central Processing Unit
Arithmetic and logical operations are carried out inside the CPU
Java Programming
14
Central Processing Unit and Main Memory
Java Programming
15
Main Memory
Ordered sequence of cells (memory cells) Directly connected to CPU All programs must be brought into main memory before execution When power is turned off, everything in main memory is lost
Java Programming
16
Secondary Storage
Provides permanent storage for information Examples of secondary storage:
Hard disks Floppy disks Flash memory ZIP disks CD-ROMs Tapes
17
Java Programming
Input Devices
Definition: devices that feed data and computer programs into computers Examples
Keyboard Mouse Secondary storage
Java Programming
18
Output Devices
Definition: devices that the computer uses to display results Examples
Printer Monitor Secondary storage
Java Programming
19
Input/Output Devices
Java Programming Programming: From Problem Analysis to Program Design, 4e
20
Software
Software consists of programs written to perform specific tasks Two types of programs
System programs Application programs
Java Programming
21
System Programs
System programs control the computer The operating system is first to load when you turn on a computer
Java Programming
22
Operating System (OS)
OS monitors overall activity of the computer and provides services Example services
Memory management Input/output Activities Storage management
23
Java Programming
Application Programs
Written using programming languages Perform a specific task Run by the OS Example programs
Word processors Spreadsheets Games
Java Programming 24
Language of a Computer
Machine language: the most basic language of a computer A sequence of 0s and 1s Every computer directly understands its own machine language A bit is a binary digit, 0 or 1 A byte is a sequence of eight bits
Java Programming 25
Language of a Computer (continued)
Java Programming
26
Evolution of Programming Languages
Early computers programmed in machine language Assembly languages were developed to make programmers job easier In assembly language, an instruction is an easy-to-remember form called a mnemonic Assembler: translates assembly language instructions into machine language
Java Programming 27
Instructions in Assembly and Machine Language
Java Programming
28
Evolution of Programming Languages
High-level languages make programming easier Closer to spoken languages Examples
Basic FORTRAN COBOL C/C++ Java
29
Java Programming
Evolution of Programming Languages (continued)
To run a Java program:
1. Java instructions need to be translated into an intermediate language called bytecode 2. Then the bytecode is interpreted into a particular machine language
Java Programming
30
Evolution of Programming Languages (continued)
Compiler: a program that translates a program written in a high-level language into the equivalent machine language In the case of Java, this machine language is the bytecode Java Virtual Machine (JVM): hypothetical computer developed to make Java programs machine independent
Java Programming 31
A Java Program
Output:
Java Programming
32
Processing a Java Program
Two types of Java programs: applications and applets Source program: written in a high-level language Loader: transfers the compiled code (bytecode) into main memory Interpreter: reads and translates each bytecode instruction into machine language and then executes it
Java Programming
33
Processing a Java Program (continued)
Java Programming
34
Internet, World Wide Web, Browser, and Java
The Internet is an interconnection of networks that allows computers around the world to communicate with each other In 1969, the U.S. Department of Defenses Advanced Research Project Agency (ARPA) funded research projects to investigate and develop techniques and technologies to interlink networks This was called the internetting project, and the funding resulted in ARPANET, which eventually became known as the Internet The Internet allows computers to be connected and communicate with each other
Java Programming 35
Internet, World Wide Web, Browser, and Java (continued)
World Wide Web (WWW) or Web uses software programs that enable computer users to access documents and files (including images, audio, and video) on almost any subject over the Internet with the click of a mouse Computers around the world communicate via the Internet; the World Wide Web makes that communication a fun activity
Java Programming Programming: From Problem Analysis to Program Design, 4e 36
Internet, World Wide Web, Browser, and Java (continued)
The primary language for the Web is known as Hypertext Markup Language (HTML) Java applets are programs that run from a Web browser and make the Web responsive and interactive Two well-known browsers are Mozilla Firefox and Internet Explorer Java applets can run in either browser Through the use of applets, the Web becomes responsive, interactive, and fun to use
Java Programming Programming: From Problem Analysis to Program Design, 4e 37
Problem-Analysis-CodingExecution Cycle
Algorithm: a step-by-step problem-solving process in which a solution is arrived at in a finite amount of time
Java Programming Programming: From Problem Analysis to Program Design, 4e
38
Problem-Solving Process
1. Analyze the problem and outline the problem and its solution requirements 2. Design an algorithm to solve the problem 3. Implement the algorithm in a programming language, such as Java 4. Verify that the algorithm works 5. Maintain the program by using and improving it and modifying it if the problem domain changes
Java Programming 39
Problem-Analysis-CodingExecution Cycle (continued)
Java Programming
40
Programming Methodologies
Two basic approaches to programming design
Structured design Object-oriented design
Java Programming
41
Structured Design
1. A problem is divided into smaller subproblems 2. Each subproblem is solved 3. The solutions of all subproblems are then combined to solve the problem
Java Programming
42
Object-Oriented Design (OOD)
In OOD, a program is a collection of interacting objects An object consists of data and operations Steps in OOD
1. Identify objects 2. Form the basis of the solution 3. Determine how these objects interact
Java Programming
43
Chapter Summary
A computer system is made up of hardware and software components Computers understand machine language; it is easiest for programmers to write in high-level languages A compiler translates high-level language into machine language Java steps to execute a program: edit, compile, load, and execute
Java Programming 44
Chapter Summary (continued)
Algorithm: step-by-step problem-solving process in which a solution is arrived at in a finite amount of time Three steps to problem solving: analyze the problem and design an algorithm, implement the algorithm in a programming language, and maintain the program Two basic approaches to programming design: structured and object-oriented
Java Programming 45
Java Programming
Chapter 2 Basic Elements of Java
Chapter Objectives
Become familiar with the basic components of a Java program, including methods, special symbols, and identifiers Explore primitive data types Discover how to use arithmetic operators Examine how a program evaluates arithmetic expressions Explore how mixed expressions are evaluated
Java Programming 47
Chapter Objectives (continued)
Learn about type casting Become familiar with the String type Learn what an assignment statement is and what it does Discover how to input data into memory by using input statements Become familiar with the use of increment and decrement operators
Java Programming
48
Chapter Objectives (continued)
Examine ways to output results using output statements Learn how to import packages and why they are necessary Discover how to create a Java application program Explore how to properly structure a program, including using comments to document a program
Java Programming
49
Introduction
Computer program: a sequence of statements whose objective is to accomplish a task Programming: process of planning and creating a program
Java Programming
50
A Java Program
Sample Run:
Java Programming
51
The Basics of a Java Program
Java program: collection of classes There is a main method in every Java application program Token: smallest individual unit of a program
Java Programming Programming: From Problem Analysis to Program Design, 4e
52
Special Symbols
Java Programming
53
Reserved Words (Keywords)
int float double char void public static throws return
Java Programming
54
Java Identifiers
Names of things Consist of:
Letters Digits The underscore character (_) The dollar sign ($)
Must begin with a letter, underscore, or the dollar sign
Java Programming 55
Illegal Identifiers
Java Programming
56
Data Types
Data type: set of values together with a set of operations
Java Programming
57
Primitive Data Types
Integral, which is a data type that deals with integers, or numbers without a decimal part (and characters) Floating-point, which is a data type that deals with decimal numbers Boolean, which is a data type that deals with logical values
Java Programming
58
Integral Data Types
char byte short int long
Java Programming
59
Values and Memory Allocation for Integral Data Types
Java Programming
60
Primitive Data Types
Floating-point data types
float: precision = 6 or 7 double: precision = 15
boolean: two values
true false
Java Programming
61
Literals (Constants)
Integer literals, integer constants, or integers: 23 and -67 Floating-point literals, floating-point constants, floating-point numbers: 12.34 and 25.60 Character literals, character constants, or characters: 'a' and '5'
Java Programming Programming: From Problem Analysis to Program Design, 4e 62
Arithmetic Operators and Operator Precedence
Five Arithmetic Operators
+ addition - subtraction * multiplication / division % mod (modulus)
Unary operator: operator that has one operand Binary operator: operator that has two operands
Java Programming
63
Order of Precedence
1. * 2. +
/
-
(same precedence) (same precedence)
Operators in 1 have a higher precedence than operators in 2 When operators have the same level of precedence, operations are performed from left to right
64
Java Programming
Expressions
Integral expressions Floating-point or decimal expressions Mixed expressions
Java Programming
65
Integral Expressions
All operands are integers Examples
2 + 3 * 5 3 + x y / 7 x + 2 * (y z) + 18
Java Programming
66
Floating-Point Expressions
All operands are floating-point numbers Examples 12.8 * 17.5 34.50 x * 10.5 + y - 16.2
Java Programming
67
Mixed Expressions
Operands of different types Examples 2 + 3.5 6 / 4 + 3.9 Integer operands yield an integer result; floatingpoint numbers yield floating-point results If both types of operands are present, the result is a floating-point number Precedence rules are followed
Java Programming 68
Type Conversion (Casting)
Used to avoid implicit type coercion Syntax (dataTypeName) expression Expression evaluated first, then type converted to dataTypeName Examples
(int)(7.9 + 6.7) = 14 (int)(7.9) + (int)(6.7) = 13
Java Programming 69
The class String
Used to manipulate strings String
Sequence of zero or more characters Enclosed in double quotation marks Null or empty strings have no characters Numeric strings consist of integers or decimal numbers Length is the number of characters in a string
Java Programming 70
Strings and the Operator +
Operator + can be used to concatenate two strings or a string and a numeric value or character Example 2-10
"The sum = " + 12 + 26
-After this statement executes, the string assigned to str is:
"The sum = 1226";
Java Programming 71
Strings and the Operator + (continued)
Consider the following statement:
"The sum = " + (12 + 26)
In this statement, because of the parentheses, you first evaluate num1 + num2
Because num1 and num2 are both int variables, num1 + num2 = 12 + 26 = 38 After this statement executes, the string assigned to str is:
"The sum = 38";
Java Programming 72
Input
Named constant
Cannot be changed during program execution Declared by using the reserved word final Initialized when it is declared
Example 2-11
double CENTIMETERS_PER_INCH = 2.54; int NO_OF_STUDENTS = 20; char BLANK = ' '; double PAY_RATE = 15.75;
73
final final final final
Java Programming
Input (continued)
Variable (name, value, data type, size)
Content may change during program execution Must be declared before it can be used May not be automatically initialized If new value is assigned, old one is destroyed Value can only be changed by an assignment statement or an input (read) statement
Example 2-12
amountDue; counter; ch; num1, num2;
74
double int char int
Java Programming
Input (continued)
The assignment statement
variable = expression;
Example 2-13
int num1; int num2; double sale; char first; String str; num1 = 4; num2 = 4 * 5 - 11; sale = 0.02 * 1000; first = 'D'; str = "It is a sunny day.";
Java Programming 75
Input (continued)
Example 2-14
1. num1 2. num1 3. num2 4. num3 5. num3 = = = = = 18; num1 + 27; num1; num2 / 5; num3 / 4;
Java Programming Programming: From Problem Analysis to Program Design, 4e
76
Input (continued)
Java Programming Programming: From Problem Analysis to Program Design, 4e
77
Input (continued)
Java Programming Programming: From Problem Analysis to Program Design, 4e
78
Input (continued)
Standard input stream object: System.in
Input numeric data to program
Separate by blanks, lines, or tabs
To read data:
1. Create an input stream object of the class Scanner 2. Use the methods such as next, nextLine, nextInt, and nextDouble
Java Programming 79
Input (continued)
static Scanner console = new Scanner(System.in);
Example 2-16
static Scanner console = new Scanner(System.in);
int feet; int inches;
Suppose the input is 23 7 feet = console.nextInt(); inches = console.nextInt();
Java Programming
//Line 1 //Line 2
80
Increment and Decrement Operators
++ increments the value of its operand by 1 -- decrements the value of its operand by 1 Syntax
Pre-increment: ++variable Post-increment: variable++ Pre-decrement: --variable Post-decrement: variable-Java Programming 81
Output
Standard output object: System.out Methods
print println
Syntax
System.out.print(stringExp); System.out.println(stringExp); System.out.println();
Java Programming 82
Commonly Used Escape Sequences
Java Programming
83
Packages, Classes, Methods, and the import Statement
Package: collection of related classes Class: consists of methods Method: designed to accomplish a specific task
Java Programming
84
import Statement
Used to import the components of a package into a program Reserved word import java.io.*;
Imports the (components of the) package java.io into the program
Primitive data types and the class String
Part of the Java language Dont need to be imported
Java Programming 85
Creating a Java Application Program
Syntax of a class
Syntax of the main method
Java Programming
86
Programming Style and Form
Know common syntax errors and rules Use blanks appropriately Semicolon: statement terminator Important to have well-documented code Good practice to follow traditional rules for naming identifiers
87
Java Programming
More on Assignment Statements
variable = variable * (expression);
is equivalent to
variable *= expression;
Similarly,
variable = variable + (expression);
is equivalent to
variable += expression;
Java Programming
88
Programming Examples
Convert Length program
Input: length in feet and inches Output: equivalent length in centimeters
Make Change program
Input: change in cents Output: equivalent change in half-dollars, quarters, dimes, nickels, and pennies
Java Programming 89
Chapter Summary
Basic Elements of a Java program include:
The main method Reserved words Special symbols Identifiers Data types Expressions Input Output Statements
90
Java Programming
Chapter Summary (continued)
To create a Java application, it is important to understand:
Syntax rules Semantic rules How to manipulate strings and numbers How to declare variables and named constants How to receive input and display output Good programming style and form
Java Programming
91
Java Programming
Chapter 3 Introduction to Objects and Input/Output
Chapter Objectives
Learn about objects and reference variables Explore how to use predefined methods in a program Become familiar with the class String
Learn how to use input and output dialog boxes in a program
Java Programming
93
Chapter Objectives (continued)
Explore how to format the output of decimal numbers with the String method format Become familiar with file input and output
Java Programming
94
Object and Reference Variables
Declare a reference variable of a class type
Allocate memory space for data Instantiate an object of that class type
Store the address of the object in a reference variable
Java Programming
95
Object and Reference Variables (continued) int x; //Line 1
String str; x = 45; str = "Java Programming"; //Line 2 //Line 3 //Line 4
Java Programming
96
Object and Reference Variables (continued)
Java Programming Programming: From Problem Analysis to Program Design, 4e
97
Object and Reference Variables (continued)
Java Programming
98
Object and Reference Variables (continued)
Java Programming
99
Objects and Reference Variables (continued)
Primitive type variables directly store data into their memory space
Reference variables store the address of the object containing the data An object is an instance of a class and the operator new is used to instantiate an object
Java Programming 100
Using Predefined Classes and Methods in a Program
There are many predefined packages, classes, and methods in Java Library: collection of packages Package: contains several classes Class: contains several methods Method: set of instructions
Java Programming 101
Using Predefined Classes and Methods in a Program (continued)
To use a method, you must know:
Name of the class containing method (Math) Name of the package containing class (java.lang) Name of the method - (pow), it has two parameters Math.pow(x, y) = xy
Java Programming
102
Using Predefined Classes and Methods in a Program (continued)
Example method call
import java.lang; //imports package Math.pow(2, 3); //calls power method // in class Math
Dot (.) operator: used to access the method in the class
Java Programming
103
The class String
String variables are reference variables Given:
String name;
Similar Statements
name = new String("Lisa Johnson"); name = "Lisa Johnson";
Java Programming
104
The class String (continued)
A String object is an instance of class String The address of a String object with the value "Lisa Johnson" is stored in name String methods are called using the dot operator
Java Programming
105
The class String (continued)
sentence = "Programming with Java";
Java Programming Programming: From Problem Analysis to Program Design, 4e
106
Some Commonly Used String Methods
Java Programming
107
Some Commonly Used String Methods (continued)
Java Programming
108
Some Commonly Used String Methods (continued)
Java Programming
109
Some Commonly Used String Methods (continued)
Java Programming
110
Some Commonly Used String Methods (continued)
Java Programming Programming: From Problem Analysis to Program Design, 4e
111
Input/Output
Input data Format output Output results Format output Read from and write to files
Java Programming
112
Formatting Output with printf
A syntax to use the method printf to produce output on the standard output device is: System.out.printf(formatString); or: System.out.printf(formatString, argumentList); formatString is a string specifying the format of the output, and argumentList is a list of arguments
Java Programming 113
Formatting Output with printf (continued)
argumentList is a list of arguments that consists of constant values, variables, or expressions If there is more than one argument in argumentList, then the arguments are separated with commas
Java Programming
114
Formatting Output with printf (continued)
System.out.printf("Hello there!"); consists of only the format string, and the statement:
System.out.printf("There are %.2f inches in %d centimeters.%n", centimeters / 2.54, centimeters);
consists of both the format string and argumentList
Java Programming 115
Formatting Output with printf (continued)
%.2f and %d are called format specifiers By default, there is a one-to-one correspondence between format specifiers and the arguments in argumentList The first format specifier %.2f is matched with the first argument, which is the expression centimeters / 2.54 The second format specifier %d is matched with the second argument, which is centimeters
Java Programming 116
Formatting Output with printf (continued)
The format specifier %n positions the insertion point at the beginning of the next line. A format specifier for general, character, and numeric types has the following syntax:
The expressions in square brackets are optional; they may or may not appear in a format specifier
Java Programming 117
Formatting Output with printf (continued)
The option argument_index is a (decimal) integer indicating the position of the argument in the argument list
The first argument is referenced by "1$", the second by "2$", etc.
The option flags is a set of characters that modify the output format The option width is a (decimal) integer indicating the minimum number of characters to be written to the output
Java Programming 118
Formatting Output with printf (continued)
The option precision is a (decimal) integer usually used to restrict the number of characters The required conversion is a character indicating how the argument should be formatted
Java Programming
119
Formatting Output with printf (continued)
Java Programming
120
Parsing Numeric Strings
A string consisting of only integers or decimal numbers is called a numeric string 1. To convert a string consisting of an integer to a value of the type int, we use the following expression:
Integer.parseInt(strExpression)
Integer.parseInt("6723") = 6723 Integer.parseInt("-823") = -823
Java Programming
121
Parsing Numeric Strings (continued)
2. To convert a string consisting of a decimal number to a value of the type float, we use the following expression:
Float.parseFloat(strExpression) Float.parseFloat("34.56") = 34.56 Float.parseFloat("-542.97") = -542.97
Java Programming
122
Parsing Numeric Strings (continued)
3.To convert a string consisting of a decimal number to a value of the type double, we use the following expression:
Double.parseDouble(strExpression) Double.parseDouble("345.78") = 345.78 Double.parseDouble("-782.873") = 782.873
Java Programming
123
Parsing Numeric Strings (continued)
Integer, Float, and Double are classes designed to convert a numeric string into a number These classes are called wrapper classes parseInt is a method of the class Integer, which converts a numeric integer string into a value of the type int
Java Programming
124
Parsing Numeric Strings (continued)
parseFloat is a method of the class Float and is used to convert a numeric decimal string into an equivalent value of the type float parseDouble is a method of the class Double, which is used to convert a numeric decimal string into an equivalent value of the type double
Java Programming 125
Using Dialog Boxes for Input/Output
Use a graphical user interface (GUI) class JOptionPane
Contained in package javax.swing Contains methods: showInputDialog and showMessageDialog
Syntax
str = JOptionPane.showInputDialog(strExpression)
Program must end with System.exit(0);
Java Programming 126
Parameters for the Method showMessageDialog
Java Programming
127
JOptionPane Options for the Parameter messageType
Java Programming
128
JOptionPane Example
Java Programming
129
Formatting the Output Using the String Method format
Example 3-12
double x = 15.674; double y = 235.73; double z = 9525.9864; int num = 83; String str;
Java Programming
130
File Input/Output
File: area in secondary storage used to hold information You can also initialize a Scanner object to input sources other than the standard input device by passing an appropriate argument in place of the object System.in We make use of the class FileReader
Java Programming
131
File Input/Output (continued)
Suppose that the input data is stored in a file, say prog.dat, and this file is on the floppy disk A The following statement creates the Scanner object inFile and initializes it to the file prog.dat
Scanner inFile = new Scanner (new FileReader("prog.dat"));
Java Programming
132
File Input/Output (continued)
Next, you use the object inFile to input data from the file prog.dat just the way you used the object console to input data from the standard input device using the methods next, nextInt, nextDouble, and so on
Java Programming
133
File Input/Output (continued)
Java Programming
134
File Input/Output (continued)
Java file I/O process
1. 2. 3. 4. Import necessary classes from the packages java.util and java.io into the program Create and associate appropriate objects with the input/output sources Use the appropriate methods associated with the variables created in Step 2 to input/output data Close the files
Java Programming
135
File Input/Output (continued)
Example 3-15 Suppose an input file, say employeeData.txt, consists of the following data:
Emily Johnson 45 13.50 Scanner inFile = new Scanner (new FileReader("employeeData.txt")); String firstName; String lastName; double hoursWorked; double payRate; double wages; firstName = inFile.next(); lastName = inFile.next(); hoursWorked = inFile.nextDouble(); payRate = inFile.nextDouble(); wages = hoursWorked * payRate; inFile.close();
Java Programming
//close the input file
136
Storing (Writing) Output to a File
To store the output of a program in a file, you use the class PrintWriter Declare a PrintWriter variable and associate this variable with the destination Suppose the output is to be stored in the file prog.out
Java Programming
137
Storing (Writing) Output to a File (continued)
Consider the following statement:
PrintWriter outFile = new PrintWriter("prog.out");
This statement creates the PrintWriter object outFile and associates it with the file prog.out You can now use the methods print, println, and printf with outFile just the same way they have been used with the object System.out
Java Programming 138
Storing (Writing) Output to a File (continued)
The statement:
outFile.println("The paycheck is: $" + pay);
stores the outputThe paycheck is: $565.78in the file prog.out
-This statement assumes that the value of the variable pay is 565.78
Java Programming
139
Storing (Writing) Output to a File (continued)
Step 4 requires closing the file; you close the input and output files by using the method close inFile.close(); outFile.close(); Closing the output file ensures that the buffer holding the output will be emptied; that is, the entire output generated by the program will be sent to the output file
Java Programming 140
throws Clause
During program execution, various things can happen; for example, division by zero or inputting a letter for a number In such cases, we say that an exception has occurred If an exception occurs in a method, the method should either handle the exception or throw it for the calling environment to handle If an input file does not exist, the program throws a FileNotFoundException
Java Programming 141
throws Clause (continued)
If an output file cannot be created or accessed, the program throws a FileNotFoundException For the next few chapters, we will simply throw the exceptions Because we do not need the method main to handle the FileNotFoundException exception, we will include a command in the heading of the method main to throw the FileNotFoundException exception
Java Programming 142
Skeleton of I/O Program
Java Programming
143
Programming Example: Movie Ticket Sale and Donation to Charity
Input: movie name, adult ticket price, child ticket price, number of adult tickets sold, number of child tickets sold, percentage of gross amount to be donated to charity Output:
Java Programming
144
Programming Example: Movie Ticket Sale and Donation to Charity (continued)
Import appropriate packages Get inputs from user using JOptionPane.showInputDialog
Perform appropriate calculations Display output using JOptionPane.showMessageDialog
Java Programming 145
Programming Example: Student Grade
Input: file containing students first name, last name, five test scores Output: file containing students first name, last name, five test scores, average of five test scores
Java Programming
146
Programming Example: Student Grade (continued)
Import appropriate packages Get input from file using the classes Scanner and FileReader Read and calculate the average of test scores Write to output file using the class PrintWriter Close files
Java Programming 147
Chapter Summary
Primitive type variables store data into their memory space Reference variables store the address of the object containing the data An object is an instance of a class
Java Programming
148
Chapter Summary (continued)
Operator new is used to instantiate an object Garbage collection is reclaiming memory not being used To use a predefined method, you must know its name and the class and package it belongs to The dot (.) operator is used to access a certain method in a class
Java Programming 149
Chapter Summary (continued)
Methods of the class String are used to manipulate input and output data Dialog boxes can be used to input data and output results Data can be read from and written to files Data can be formatted using the String method format
Java Programming 150
Java Programming
Chapter 4 Control Structures I: Selection
Chapter Objectives
Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean) expressions Learn how to use the selection control structures if, ifelse, and switch in a program
Java Programming 152
Control Structures
Three methods of processing a program
In sequence Branching Looping
Branch: altering the flow of program execution by making a selection or choice Loop: altering the flow of program execution by repetition of statement(s)
Java Programming 153
Flow of Execution
Java Programming
154
Relational Operators
Relational operator
Allows you to make comparisons in a program Binary operator
Condition is represented by a logical expression in Java Logical expression: expression that has a value of either true or false
Java Programming 155
Relational Operators in Java
Java Programming
156
Relational Operators and Primitive Data Types
Can be used with integral and floating-point data types Can be used with the char data type Unicode collating sequence
Java Programming
157
Java Programming Programming: From Problem Analysis to Program Design, 4e
158
Java Programming Programming: From Problem Analysis to Program Design, 4e
159
Relational Operators and the Unicode Collating Sequence
Java Programming
160
Logical (Boolean) Operators
Java Programming
161
Logical (Boolean) Operators (continued)
Java Programming
162
Logical (Boolean) Operators (continued)
Java Programming
163
Logical (Boolean) Operators (continued)
Java Programming
164
Precedence of Operators
Java Programming
165
Precedence of Operators (continued)
Java Programming Programming: From Problem Analysis to Program Design, 4e
166
Short-Circuit Evaluation
Definition: a process in which the computer evaluates a logical expression from left to right and stops as soon as the value of the expression is known
Java Programming
167
Selection
One-way selection Two-way selection Compound (block of) statements Multiple selections (nested if) Conditional operator switch structures
Java Programming 168
One-Way Selection
Syntax
if (expression) statement
Expression referred to as decision maker Statement referred to as action statement
Java Programming
169
One-Way Selection (continued)
Java Programming
170
One-Way Selection (continued)
Example 4-10 //Program to determine the absolute value of an integer import javax.swing.JOptionPane; public class AbsoluteValue { public static void main(String[] args) { int number; int temp; String numString; numString = JOptionPane.showInputDialog ("Enter an integer:"); //Line 1 number = Integer.parseInt(numString); //Line 2 temp = number; //Line 3
Java Programming 171
One-Way Selection (continued)
if (number < 0) number = -number;
//Line 4 //Line 5
JOptionPane.showMessageDialog(null, "The absolute value of " + temp + " is " + number, "Absolute Value", JOptionPane.INFORMATION_MESSAGE); //Line 6 System.exit(0); }
Java Programming
172
Two-Way Selection
Syntax if (expression) statement1 else statement2 else statement must be paired with an if
Java Programming 173
Two-Way Selection (continued)
Java Programming
174
Two-Way Selection (continued)
Example 4-14
if (hours > 40.0) wages = 40.0 * rate + 1.5 * rate * (hours - 40.0); else wages = hours * rate;
Java Programming
175
Two-Way Selection (continued)
Example 4-14 (continued)
if (hours > 40.0); //Line 1 wages = 40.0 * rate + 1.5 * rate * (hours - 40.0); //Line 2 else //Line 3 wages = hours * rate; //Line 4
Because a semicolon follows the closing parenthesis of the if statement (Line 1), the else statement stands alone The semicolon at the end of the if statement (see Line 1) ends the if statement, so the statement at Line 2 separates the else clause from the if statement; that is, else is by itself Since there is no separate else statement in Java, this code generates a syntax error
Java Programming 176
Compound (Block of) Statements
Syntax
Java Programming
177
Compound (Block of) Statements (continued)
if (age > 18) { System.out.println("Eligible to vote."); System.out.println("No longer a minor."); } else { System.out.println("Not eligible to vote."); System.out.println("Still a minor."); }
Java Programming
178
Multiple Selection: Nested if
Syntax
if (expression1) statement1 else if (expression2) statement2 else statement3
Else associated with most recent incomplete if Multiple if statements can be used in place of ifelse statements May take longer to evaluate
179
Java Programming
Conditional (? :) Operator
Ternary operator Syntax
expression1 ? expression2 : expression3
If expression1 = true, then the result of the condition is expression 2; otherwise, the result of the condition is expression 3
Java Programming
180
switch Structures
Java Programming
181
switch Structures (continued)
In Java, switch, case, break, and default are reserved words In a switch structure, the expression is evaluated first The value of the expression is then used to perform the actions specified in the statements that follow the reserved word case The expression is usually an identifier The value of the identifier or the expression can be only of type int, byte, short, or char
Java Programming Programming: From Problem Analysis to Program Design, 4e 182
switch Structures (continued)
The expression is sometimes called the selector; its value determines which statements are selected for execution A particular case value must appear only once One or more statements may follow a case label, so you do not need to use braces to turn multiple statements into a single compound statement
Java Programming Programming: From Problem Analysis to Program Design, 4e
183
switch Structures (continued)
The break statement may or may not appear after each statements1, statements2, ..., statementsn A switch structure may or may not have the default label
Java Programming Programming: From Problem Analysis to Program Design, 4e
184
switch Structures (continued)
Java Programming
185
switch Structures (continued)
Java Programming
186
switch Structures (continued)
Example 4-23 switch (grade) { case 'A': System.out.println("The grade is A."); break; case 'B': System.out.println("The grade is B."); break;
case 'C': System.out.println("The grade is C."); break;
Java Programming
187
switch Structures (continued)
case 'D': System.out.println("The grade is D."); break;
case 'F': System.out.println("The grade is F."); break;
default: System.out.println("The grade is invalid."); }
Java Programming
188
Programming Example: Cable Company Billing
Input: customers account number, customer code, number of premium channels to which customer subscribes, number of basic service connections (in case of business customers) Output: customers account number and the billing amount
Java Programming 189
Programming Example: Cable Company Billing (continued)
Solution
Prompt user for information Use switch statements based on customers type Use an if statement nested within a switch statement to determine amount due by each customer
Java Programming
190
Comparing Strings
class String Method compareTo Method equals
Given string str1 and str2
an integer 0 if string str1 str2 str1.compareTo(str2) 0 if string str1 is equal to string str2 an integer 0 if string str1 str2
Java Programming 191
Comparing Strings (continued)
String String String String String str1 str2 str3 str4 str5 = = = = = "Hello"; "Hi"; "Air"; "Bill"; "Bigger";
Java Programming
192
Comparing Strings (continued)
Java Programming
193
Comparing Strings (continued)
Java Programming
194
Chapter Summary
Control structures are used to process programs Logical expressions and order of precedence of operators are used in expressions If statements ifelse statements switch structures Proper syntax for using control statements Compare strings
Java Programming 195
Java Programming
Chapter 5 Control Structures II: Repetition
Chapter Objectives
Learn about repetition (looping) control structures Explore how to construct and use countcontrolled, sentinel-controlled, flag-controlled, and EOF-controlled repetition structures Examine break and continue statements Discover how to form and use nested control structures
Java Programming
197
Why Is Repetition Needed?
There are many situations in which the same statements need to be executed several times Example
Formulas used to find average grades for students in a class
Java Programming
198
The while Looping (Repetition) Structure
Syntax
while (expression) statement
Expression is always true in an infinite loop Statements must change value of expression to false
Java Programming
199
The while Looping (Repetition) Structure (continued)
Java Programming
200
The while Looping (Repetition) Structure (continued)
Example 5-1
i = 0; while (i <= 20) { System.out.print(i + " "); i = i + 5; } System.out.println(); //Line 1 //Line 2 //Line 3 //Line 4 //Line 5
Output:
0 5 10 15 20
Java Programming 201
The while Looping (Repetition) Structure (continued)
Typically, while loops are written in the following form:
Java Programming
202
Counter-Controlled while Loop
Used when exact number of data or entry pieces is known General form:
Java Programming
203
Sentinel-Controlled while Loop
Used when exact number of entry pieces is unknown but last entry (special/sentinel value) is known General form:
Java Programming
204
Flag-Controlled while Loop
Boolean value used to control loop General form:
Java Programming
205
EOF (End of File)-Controlled while Loop
Used when input is from files Sentinel value is not always appropriate In an EOF-controlled while loop that uses the Scanner object console to input data, console acts at the loop control variable The method hasNext, of the class Scanner, returns true if there is an input in the input stream; otherwise it returns false
Java Programming 206
The expression console.hasNext() evaluates to true if there is an input in the input stream; otherwise it returns false Expressions such as console.nextInt() act as the loop condition A general form of the EOF-controlled while loop that uses the Scanner object console to input data is of the form:
EOF (End of File)-Controlled while Loop (continued)
Java Programming
207
EOF (End of File)-Controlled while Loop (continued)
Suppose that inFile is a Scanner object initialized to the input file; in this case, the EOFcontrolled while loop takes the following form:
Java Programming
208
Java Programming Programming: From Problem Analysis to Program Design, 4e
209
Programming Example: Fibonacci Number
Fibonacci formula for any Fibonacci sequence:
an = an-1 + an-2
Input: first two Fibonacci numbers in sequence, position in sequence of desired Fibonacci number (n)
int previous1 = Fibonacci number 1 int previous2 = Fibonacci number 2 int nthFibonacci = position of nth Fibonacci number
Output: nth Fibonacci number
Java Programming 210
Programming Example: Fibonacci Number (Solution)
if (nthFibonacci == 1) current = previous1; else if (nthFibonacci == 2) current = previous2; else { counter = 3; while (counter <= nthFibonacci) { current = previous2 + previous1; previous1 = previous2; previous2 = current; counter++; }
Final result found in last value of current
Java Programming 211
The for Looping (Repetition) Structure
Specialized form of while loop
Simplifies the writing of count-controlled loops Syntax
for (initial expression; logical expression; update expression)
statement
Java Programming
212
The for Looping (Repetition) Structure (continued)
Execution
Initial statement executes The loop condition is evaluated If loop condition evaluates to true, execute for loop statement and execute update statement Repeat until loop condition is false
Java Programming
213
The for Looping (Repetition) Structure (continued)
Java Programming
214
The for Looping (Repetition) Structure (continued)
Example 5-9
The following for loop prints the first 10 nonnegative integers:
for (i = 0; i < 10; i++) System.out.print(i + " "); System.out.println();
Java Programming
215
The for Looping (Repetition) Structure (continued)
Example 5-10
1. The following for loop outputs the word Hello and a star (on separate lines) five times: for (i = 1; i <= 5; i++) { System.out.println("Hello"); System.out.println("*"); } 2.
for (i = 1; i <= 5; i++) System.out.println("Hello"); System.out.println("*");
This loop outputs the word Hello five times and the star only once
Java Programming 216
The for Looping (Repetition) Structure (continued)
Does not execute if initial condition is false Update expression changes value of loop control variable, eventually making it false If logical expression is always true, result is an infinite loop Infinite loop can be specified by omitting all three control statements
Java Programming 217
The for Looping (Repetition) Structure (continued)
If logical expression is omitted, it is assumed to be true for statement ending in semicolon is empty
Java Programming
218
Java Programming Programming: From Problem Analysis to Program Design, 4e
219
Programming Example: Classify Numbers
Input: N integers (positive, negative, and zeros)
int N = 20; //N easily modified
Output: number of 0s, number of even integers, number of odd integers
Java Programming
220
Programming Example: Classify Numbers (Solution)
for (counter = 1; counter <= N; counter++) { number = console.nextInt(); System.out.print(number + " "); switch (number % 2) { case 0: evens++; if (number == 0) zeros++; break; case 1: case -1: odds++; } //end switch } //end for loop
Java Programming 221
Programming Example: Classify Numbers (Solution) (continued)
The switch statement in Step 3c can also be written as an if...else statement as follows:
Java Programming Programming: From Problem Analysis to Program Design, 4e
222
The dowhile Loop (Repetition) Structure
Syntax
Statements executed first, and then logical expression evaluated Statement(s) executed at least once and then continued if logical expression is true
Java Programming 223
dowhile Loop (Post-test Loop)
Java Programming
224
dowhile Loop (Post-test Loop)
Java Programming Programming: From Problem Analysis to Program Design, 4e
225
Choosing the Right Looping Structure
All three loops have a place in Java If you know or the program can determine in advance the number of repetitions needed, the for loop is the correct choice If you do not know and the program cannot determine in advance the number of repetitions needed, and it could be zero, the while loop is the right choice
If you do not know and the program cannot determine in advance the number of repetitions needed, and it is at least one, the do...while loop is the right choice
Java Programming Programming: From Problem Analysis to Program Design, 4e
226
break Statements
Used to exit early from a loop Used to skip remainder of switch structure Can be placed within if statement of a loop
If condition is met, loop exited immediately
Java Programming
227
continue Statements
Used in while, for, and do...while structures When executed in a loop, the remaining statements in the loop are skipped; proceeds with the next iteration of the loop When executed in a while/dowhile structure, expression evaluated immediately after continue statement In a for structure, the update expression is executed after the continue statement; then the loop condition executes
Java Programming 228
Nested Control Structure
Provides new power, subtlety, and complexity if, ifelse, and switch structures can be placed within while loops for loops can be found within other for loops
Java Programming
229
Nested Control Structure (Example)
for (i = 1; i <= 5; i++) { for (j = 1; j <= i; j++) System.out.print(" *"); System.out.println(); }
Output:
* ** *** **** *****
Java Programming 230
Chapter Summary
Looping Mechanisms
Counter-controlled while loop Sentinel-controlled while loop Flag-controlled while loop EOF-controlled while loop for loop dowhile loop
break statements continue statements Nested control structures
Java Programming 231
Java Programming
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Chapter Objectives
Learn about basic GUI components Explore how the GUI components JFrame, JLabel, JTextField, and JButton work Become familiar with the concept of eventdriven programming
Java Programming
233
Chapter Objectives (continued)
Discover events and event handlers Explore object-oriented design Learn how to identify objects, classes, and members of a class
Java Programming
234
Graphical User Interface (GUI) Components
View inputs and outputs simultaneously One graphical window Input values in any order Change input values in window Click on buttons to get output
Java Programming
235
Java GUI Components
Java Programming
236
Graphical User Interface (GUI) Components (continued)
GUI components placed in content pane GUI components
Windows Labels Text areas Buttons
Java Programming
237
GUI Components
Added to content pane of window Not added to window itself Pixel: picture element
Java Programming
238
Windows
Can be created using a JFrame object The class JFrame provides various methods to control attributes of a window Measured in pixels of height and width Attributes associated with windows
Title Width Height
Java Programming 239
class JFrame
GUI window instance created as instance of JFrame
Provides various methods to control window attributes
Java Programming
240
Methods Provided by the class JFrame
Java Programming
241
Methods Provided by the class Jframe (continued)
Java Programming
242
Two Ways to Create a Window
First way
Declare object of type JFrame Instantiate object Use various methods to manipulate window
Second way
Create class containing application program by extending definition of class JFrame Utilizes mechanism of inheritance
Java Programming 243
Content Pane
Inner area of GUI window (below title bar, inside border) To access content pane:
Declare reference variable of type Container Use method getContentPane of class JFrame
Java Programming
244
Methods Provided by the class Container
Java Programming
245
class JLabel
Labels: objects of particular class type class JLabel: used to create labels Label attributes
Title Width Height
To create a label:
Instantiate object of type JLabel Modify attributes to control display of labels
Java Programming 246
class Jlabel (continued)
Java Programming
247
class JTextField
Text fields: objects belonging to class JTextField
To create text field:
Declare reference variable of type JTextField Instantiate object
Java Programming
248
class JTextField (continued)
Java Programming
249
class JTextField (continued)
Java Programming
250
class JButton
Provided to create buttons in Java To create button:
Same technique as creating JLabel and JTextField
Java Programming
251
class Jbutton (continued)
Java Programming
252
Handling an Event
Action event: event created when JButton is clicked
Event listener: object that receives message when JButton is clicked In Java, you must register the listener
Java Programming
253
Handling an Event (continued)
class ActionListener
Handles action event Part of package java.awt.Event The class ActionListener is a special type of class (interface) Must contain actionPerformed method
Java Programming
254
Rectangle Program: Sample Run
Java Programming
255
Programming Example: Temperature Conversion
Input: temperature in Fahrenheit or Celsius Output: temperature in Celsius if input is Fahrenheit; temperature in Fahrenheit if input is Celsius
Java Programming
256
Programming Example: Temperature Conversion (continued)
Solution
Create the appropriate JLabels, JTextFields, JButtons Add them to the created content pane Calculate the appropriate conversions when the buttons are clicked and an event is triggered
Java Programming
257
Sample Run for TempConversion
Java Programming
258
Object-Oriented Design
Simplified methodology
1. Write down detailed description of problem 2. Identify all (relevant) nouns and verbs 3. From list of nouns, select objects 4. Identify data components of each object 5. From list of verbs, select operations
Java Programming
259
Object-Oriented Design Example 1
Problem statement
Write a program to input the length and width of a rectangle, and calculate and print the perimeter and area of the rectangle
Nouns
Length, width, rectangle, perimeter, area
Java Programming
260
class Rectangle with Data Members and Operations
Java Programming
261
Object-Oriented Design Example 2
An inoperable candy machine has a cash register and four dispensers to hold and release items sold by the machine The machine sells: candies, chips, gum, and cookies Write a program for this candy machine so that it can be put into operation
Java Programming 262
Object-Oriented Design Example 2 (continued)
The program should do the following:
Show the customer the different products sold by the candy machine Let the customer make the selection Show the customer the cost of the item selected Accept money from the customer Return change Release the item; that is, make the sale
Java Programming 263
Object-Oriented Design Example 2 (continued)
Java Programming
264
Object-Oriented Design Example 2 (continued)
Java Programming
265
Implementing Classes and Operations
Algorithms are used to implement operations Construct and implement your own methods Classes Integer, Double, Character, Long, Float
Known as wrapper classes Provided so that values of primitive data types can be treated as objects Have limitations (cannot change value stored in objects)
Java Programming 266
The class Integer
Java Programming
267
The class Integer (continued)
Java Programming
268
The class Integer (continued)
Java Programming
269
The class Integer (continued)
Integer num; num = new Integer(86)
Java Programming
270
The class Integer (continued)
int x; Integer num;
num = 25; For the most part, this statement is similar to the statement: num = new Integer(25);
The expression:
num = 25; is referred to as autoboxing of the int type
Java Programming 271
The class Integer (continued)
int x;
Integer num; The statement:
x = num;
This statement is equivalent to the statement:
x = num.intValue();
This statement is referred to as auto-unboxing of the int type
Java Programming
272
The class Integer (continued)
To compare the values of two Integer objects, you can use the method compareTo
If you want to compare the values of two Integer objects only for equality, then you can use the method equals
Java Programming
273
The class Integer (continued)
Java Programming
274
The class Integer (continued)
Java Programming
275
Chapter Summary
Every GUI contains a window Various components are added to content pane of window class JFrame is used to create windows JLabel is used to label GUI components and display information to user JTextFiled is used for input/output JButton generates action event
Action event is sent to action listener
Java Programming 276
Chapter Summary (continued)
Action listener must have method called actionPerformed class: collection of data members and methods associated with those members Object-oriented design (OOD)
Starts with a problem statement Identifies classes required with nouns in problem statement Identifies methods required with verbs in problem specification
Java Programming 277
Java Programming
Chapter 7 User-Defined Methods
Chapter Objectives
Understand how methods are used in Java programming Learn about standard (predefined) methods and discover how to use them in a program Learn about user-defined methods Examine value-returning methods, including actual and formal parameters
Java Programming 279
Chapter Objectives (continued)
Explore how to construct and use a valuereturning, user-defined method in a program Learn how to construct and use user-defined void methods in a program Explore variables as parameters Learn about the scope of an identifier Become aware of method overloading
Java Programming 280
Predefined Classes
Methods already written and provided by Java Organized as a collection of classes (class libraries) To use: import package Method type: data type of value returned by method
Java Programming 281
Predefined Classes (continued)
Java Programming
282
Predefined Classes (continued)
Java Programming
283
Predefined Classes (continued)
Java Programming
284
Predefined Classes (continued)
Java Programming
285
class Character (Package: java.lang)
Java Programming
286
class Character (Package: java.lang) (continued)
Java Programming
287
class Character (Package: java.lang) (continued)
Java Programming
288
Syntax: Value-Returning Method
Java Programming
289
User-Defined Methods
Value-returning methods
Used in expressions Calculate and return a value Can save value for later calculation or print value
modifiers: public, private, protected, static, abstract, final returnType: type of the value that the method calculates and returns (using return statement) methodName: Java identifier; name of method
Java Programming 290
Syntax
Syntax: formal parameter list
-The syntax of the formal parameter list is:
Method call
-The syntax to call a value-returning method is:
Java Programming
291
Syntax (continued)
Syntax: actual parameter list
-The syntax of the actual parameter list is:
Syntax: return statement
-The return statement has the following syntax:
return expr;
Java Programming 292
Equivalent Method Definitions
public static double larger(double x, double y) { double max;
if (x >= y) max = x; else max = y; return max;
}
Java Programming 293
Java Programming Programming: From Problem Analysis to Program Design, 4e
294
Java Programming Programming: From Problem Analysis to Program Design, 4e
295
Equivalent Method Definitions (continued)
public static double larger(double x, double y) { if (x >= y) return x; else return y; }
Java Programming
296
Equivalent Method Definitions (continued)
public static double larger(double x, double y) { if (x >= y) return x; return y; }
Java Programming
297
The int variable num contains the desired sum to be rolled
Java Programming Programming: From Problem Analysis to Program Design, 4e
298
Palindrome Number
Palindrome: integer or string that reads the same forwards and backwards The method isPalindrome takes a string as a parameter and returns true if the string is a palindrome, false otherwise
Java Programming
299
Solution: isPalindrome Method
public static boolean isPalindrome(String str) { int len = str.length(); int i, j; j = len - 1; for (i = 0; i <= (len - 1) / 2; i++) { if (str.charAt(i) != str.charAt(j)) return false; j--; } return true;
}
Java Programming 300
Flow of Execution
Execution always begins with the first statement in the method main User-defined methods execute only when called Call to method transfers control from caller to called method In method call statement, specify only actual parameters, not data type or method type Control goes back to caller when method exits
Java Programming 301
Programming Example: Largest Number
Input: set of 10 numbers Output: largest of 10 numbers Solution
Get numbers one at a time Method largest number: returns the larger of two numbers For loop: calls method largest number on each number received and compares to current largest number
Java Programming 302
Solution: Largest Number
static Scanner console = new Scanner(System.in); public static void main(String[] args) { double num; double max; int count; System.out.println("Enter 10 numbers."); num = console.nextDouble(); max = num; for (count = 1; count < 10; count++) { num = console.nextDouble(); max = larger(max, num); } System.out.println("The largest number is " + max); }
Java Programming 303
Sample Run: Largest Number
Sample Run
Enter 10 numbers: 10.5 56.34 73.3 42 22 67 88.55 26 62 11 The largest number is 88.55
Java Programming
304
Void Methods
Similar in structure to value-returning methods Call to method is always stand-alone statement Can use return statement to exit method early
Java Programming
305
Void Methods with Parameters: Syntax
Java Programming
306
Void Methods with Parameters: Syntax (continued)
Java Programming
307
Primitive Data Type Variables as Parameters
A formal parameter receives a copy of its corresponding actual parameter If a formal parameter is a variable of a primitive data type:
Value of actual parameter is directly stored Cannot pass information outside the method Provides only a one-way link between actual parameters and formal parameters
Java Programming 308
Reference Variables as Parameters
If a formal parameter is a reference variable:
Copies value of corresponding actual parameter Value of actual parameter is address of the object where actual data is stored Both formal and actual parameter refer to same object
Java Programming
309
Uses of Reference Variables as Parameters
Can return more than one value from a method Can change the value of the actual object When passing address, would save memory space and time, relative to copying large amount of data
Java Programming
310
Reference Variables as Parameters: type String
Java Programming
311
Reference Variables as Parameters: type String (continued)
Java Programming
312
Reference Variables as Parameters: type String (continued)
Java Programming
313
Reference Variables as Parameters: type String (continued)
Java Programming
314
Reference Variables as Parameters: type String (continued)
String str = "Hello"; //Line 5
Java Programming Programming: From Problem Analysis to Program Design, 4e
315
Reference Variables as Parameters: type String (continued)
stringParameter(str); //Line 7
Java Programming Programming: From Problem Analysis to Program Design, 4e
316
Reference Variables as Parameters: type String (continued)
pStr = "Sunny Day"; //Line 14
Java Programming Programming: From Problem Analysis to Program Design, 4e
317
Reference Variables as Parameters: type String (continued)
Variables before the statement in Line 8 executes
Java Programming
318
The class StringBuffer contains the method append, which allows you to append a string to an existing string, and the method delete, which allows you to delete all the characters of the string The assignment operator cannot be used with StringBuffer variables; you must use the operator new (initially) to allocate memory space for a string
Java Programming
319
Java Programming Programming: From Problem Analysis to Program Design, 4e
320
Java Programming Programming: From Problem Analysis to Program Design, 4e
321
Java Programming Programming: From Problem Analysis to Program Design, 4e
322
Java Programming Programming: From Problem Analysis to Program Design, 4e
323
Java Programming Programming: From Problem Analysis to Program Design, 4e
324
Primitive Type Wrapper Classes as Parameters
If a formal parameter is of the primitive data type and the corresponding actual parameter is a variable, then the formal parameter cannot change the value of the actual parameter Only reference variables can pass values outside the method (except, of course, for the return value) Corresponding to each primitive data type, Java provides a class so that the values of primitive data types can be wrapped in objects
The class Integer does not provide a method to change the value of an existing Integer object The same is true of other wrapper classes
Java Programming 325
Primitive Type Wrapper Classes as Parameters (continued)
If we want to pass a String object as a parameter and also change that object, we can use the class StringBuffer
Java does not provide any class that wraps primitive type values in objects and when passed as parameters changes their values
If a method returns only one value of a primitive type, then you can write a value-returning method If you encounter a situation that requires you to write a method that needs to pass more than one value of a primitive type, then you should design your own classes
Appendix D provides the definitions of such classes and shows how to use them in a program
Java Programming Programming: From Problem Analysis to Program Design, 4e 326
Scope of an Identifier within a Class
Local identifier: identifier declared within a method or block, which is visible only within that method or block Java does not allow the nesting of methods; you cannot include the definition of one method in the body of another method Within a method or a block, an identifier must be declared before it can be used; a block is a set of statements enclosed within braces
Java Programming 327
Scope of an Identifier within a Class (continued)
A methods definition can contain several blocks
The body of a loop or an if statement also form a block
Within a class, outside of every method definition (and every block), an identifier can be declared anywhere
Java Programming
328
Scope of an Identifier within a Class (continued)
Within a method, an identifier used to name a variable in the outer block of the method cannot be used to name any other variable in an inner block of the method For example, in the method definition on the next slide, the second declaration of the variable x is illegal
Java Programming
329
Scope of an Identifier within a Class (continued)
public static void illegalIdentifierDeclaration() { int x;
//block { double x;
//illegal declaration, //x is already declared
...
} }
Java Programming
330
Scope Rules
Scope rules of an identifier declared within a class and accessed within a method (block) of the class An identifier, say X, declared within a method (block) is accessible:
Only within the block from the point at which it is declared until the end of the block By those blocks that are nested within that block
Java Programming
331
Scope Rules (continued)
Suppose X is an identifier declared within a class and outside of every methods definition (block)
If X is declared without the reserved word static (such as a named constant or a method name), then it cannot be accessed in a static method If X is declared with the reserved word static (such as a named constant or a method name), then it can be accessed within a method (block), provided the method (block) does not have any other identifier named X
Java Programming
332
Scope Rules (continued)
Example 7-11
{ public class ScopeRules
static final double rate = 10.50; static int z; static double t; public static void main(String[] args) { int num; double x, z; char ch; //... } public static void one(int x, char y) { //... }
Java Programming 333
Scope Rules (continued)
public static int w; public static void two(int one, int z) { char ch; int a;
//block three { int x = 12; //... } //end block three //...
}
}
Java Programming 334
Scope Rules: Demonstrated
Java Programming
335
Scope Rules: Demonstrated (continued)
Java Programming
336
Method Overloading: An Introduction
Method overloading: more than one method can have the same name Two methods are said to have different formal parameter lists if both methods have:
A different number of formal parameters, or If the number of formal parameters is the same, then the data type of the formal parameters, in the order you list, must differ in at least one position
Java Programming 337
Method Overloading
public public public public void methodOne(int x) void methodTwo(int x, double y) void methodThree(double y, int x) int methodFour(char ch, int x, double y) public int methodFive(char ch, int x, String name)
These methods all have different formal parameter lists
Java Programming 338
Method Overloading (continued)
public void methodSix(int x, double y, char ch) public void methodSeven(int one, double u, char firstCh)
The methods methodSix and methodSeven both have three formal parameters and the data type of the corresponding parameters is the same These methods all have the same formal parameter lists
Java Programming 339
Method Overloading (continued)
Method overloading: creating several methods, within a class, with the same name The signature of a method consists of the method name and its formal parameter list Two methods have different signatures if they have either different names or different formal parameter lists
Note that the signature of a method does not include the return type of the method
Java Programming 340
Method Overloading (continued)
The following method headings correctly overload the method methodXYZ:
public public public public void void void void methodXYZ() methodXYZ(int x, double y) methodXYZ(double one, int y) methodXYZ(int x, double y, char ch)
Java Programming
341
Method Overloading (continued)
public void methodABC(int x, double y) public int methodABC(int x, double y)
Both these method headings have the same name and same formal parameter list These method headings to overload the method methodABC are incorrect
In this case, the compiler will generate a syntax error
Notice that the return types of these method headings are different
Java Programming 342
Programming Example: Data Comparison
Input: data from two different files Data format: course number followed by scores Output: course number, group number, course average Solution
Read from more than one file, write output to file Generate bar graphs User-defined methods and re-use (calculateAverage and printResult) Parameter passing
Java Programming 343
Programming Example: Data Comparison (continued)
Sample Output
Course No CSC Group No 1 2 Course Average 83.71 80.82
ENG
HIS MTH PHY
1 2
1 2 1 2 1 2
82.00 78.20
77.69 84.15 83.57 84.29 83.22 82.60
Avg for group 1: 82.04 Avg for group 2: 82.01
Java Programming 344
Programming Example: Data Comparison (continued)
Java Programming
345
Chapter Summary
Predefined methods User-defined methods
Value-returning methods Void methods Formal parameters Actual parameters
Flow of Execution
Java Programming 346
Chapter Summary (continued)
Primitive data type variables as parameters
One-way link between actual parameters and formal parameters (limitations caused)
Reference variables as parameters
Can pass one or more variables from a method Can change value of actual parameter
Scope of an identifier within a class Method overloading
Java Programming 347
Java Programming
Chapter 7 Passing Primitive Types As Objects
Java provides the classes Integer, Double, Character, Long, and Float so that the values of the primitive data types can be treated as objects
These classes have limitations
You can create objects of the type, say Integer, to store int values, but you cannot change the values stored in the objects
You can create objects of type IntClass and/or change the values of the objects
Java Programming Programming: From Problem Analysis to Program Design, 4e
349
Java Programming Programming: From Problem Analysis to Program Design, 4e
350
Java Programming Programming: From Problem Analysis to Program Design, 4e
351
Java Programming Programming: From Problem Analysis to Program Design, 4e
352
Java Programming Programming: From Problem Analysis to Program Design, 4e
353
Java Programming Programming: From Problem Analysis to Program Design, 4e
354
Sample Run: In this sample run, the user input is shaded
Line 1: Based on the course score, this program computes the course grade. Line 5: Enter the course score: 90.50 Line 9: The course score is 90.5 Line 10: Your grade for the course is A
Java Programming Java Programming: From Problem Analysis to Program Design, 4e 355
Java Programming Programming: From Problem Analysis to Program Design, 4e
356
Java Programming Programming: From Problem Analysis to Program Design, 4e
357
Java Programming Programming: From Problem Analysis to Program Design, 4e
358
Java Programming Programming: From Problem Analysis to Program Design, 4e
359
Java Programming Programming: From Problem Analysis to Program Design, 4e
360
Java Programming Programming: From Problem Analysis to Program Design, 4e
361
num1 = 10;
//Line 5
Java Programming Programming: From Problem Analysis to Program Design, 4e
362
num1 = 10; //Line 5 num2.setNum(15); //Line 6 ch = 'A'; //Line 7 str = new StringBuffer("Sunny"); //Line 8
Java Programming Programming: From Problem Analysis to Program Design, 4e
363
Java Programming Programming: From Problem Analysis to Program Design, 4e
364
num = b.getNum();
//Line 14
Java Programming Programming: From Problem Analysis to Program Design, 4e
365
Java Programming Programming: From Problem Analysis to Program Design, 4e
366
Java Programming Programming: From Problem Analysis to Program Design, 4e
367
Java Programming Programming: From Problem Analysis to Program Design, 4e
368
Java Programming Programming: From Problem Analysis to Program Design, 4e
369
Java Programming Programming: From Problem Analysis to Program Design, 4e
370
Java Programming Programming: From Problem Analysis to Program Design, 4e
371
Java Programming Programming: From Problem Analysis to Program Design, 4e
372
Java Programming Programming: From Problem Analysis to Program Design, 4e
373
Java Programming
Chapter 8 User-Defined Classes and ADTs
Chapter Objectives
Learn about classes Learn about private, protected, public, and static members of a class Explore how classes are implemented Learn about the various operations on classes
Java Programming
375
Chapter Objectives (continued)
Examine constructors and finalizers Examine the method toString Learn about the abstract data type (ADT)
Java Programming
376
final class String {
Classes
//variables to store a string
... public int compareTo(String anotherString) {
//code to compare two strings
} public String concat(String str) { //code to join two strings } public String toLowerCase() {
//code to convert all the characters of a //string to lowercase
} ... }
Java Programming 377
Classes (continued)
class: reserved word; collection of a fixed number of components Components: members of a class Members accessed by name Class categories/modifiers
private protected public
Java Programming 378
Classes (continued)
private: members of class are not accessible outside class public: members of class are accessible outside class Class members: can be methods or variables Variable members declared like any other variables
Java Programming 379
Syntax
The general syntax for defining a class is:
Java Programming
380
Syntax (continued)
If a member of a class is a named constant, you declare it just like any other named constant If a member of a class is a variable, you declare it just like any other variable If a member of a class is a method, you define it just like any other method
Java Programming
381
Syntax (continued)
If a member of a class is a method, it can (directly) access any member of the classdata members and methods - Therefore, when you write the definition of a
method (of the class), you can directly access any data member of the class (without passing it as a parameter)
Java Programming
382
class Clock:
Data Members (Instance Variables)
private int hr; //store hours private int min; //store minutes private int sec; //store seconds
Java Programming
383
class Clock: (continued)
Methods
public void setTime(int hours, int minutes, int seconds) public int getHours() public int getMinutes() public int getSeconds() public void printTime() public void incrementSeconds() public void incrementMinutes() public void incrementHours() public boolean equals(Clock otherClock) public void makeCopy(Clock otherClock) public Clock getCopy()
Java Programming 384
Constructors
Two types of constructors
- With parameters - Without parameters (default constructor)
Java Programming
385
Constructors (continued)
Constructors have the following properties:
- The name of a constructor is the same as the name of the class - A constructor, even though it is a method, has no type - A class can have more than one constructor; all constructors of a class have the same name - If a class has more than one constructor, any two constructors must have different signatures - Constructors are automatically executed when a class object is instantiated - If there are multiple constructors, which constructor executes depends on the type of values passed to the class object when the class object is instantiated
Java Programming 386
class Clock: Constructors
Default constructor is:
- public Clock()
Constructor with parameters is:
- public Clock(int hours, int minutes, int seconds)
Java Programming
387
Unified Modeling Language Class Diagrams
Java Programming
388
Variable Declaration and Object Instantiation
The general syntax for using the operator new is:
or:
Clock myClock; Clock yourClock;
myClock = new Clock(); yourClock = new Clock(9, 35, 15);
Java Programming 389
Variable Declaration and Object Instantiation (continued)
Java Programming
390
Variable Declaration and Object Instantiation (continued)
Java Programming
391
Accessing Class Members
The syntax to access a data member of a class object or method is: Example 8-1
myClock.setTime(5, 2, 30); myClock.printTime(); yourClock.setTime(x, y, z); if (myClock.equals(yourClock))
. . .
Java Programming 392
Assignment Operator: A Precaution
myClock = yourClock;
Copies the value of the reference variable yourClock into the reference variable myClock
- After this statement executes, both yourClock and myClock refer to the same object
Java Programming 393
Assignment Operator: A Precaution (continued)
Shallow copying: two or more reference variables of the same type point to the same object Deep copying: each reference variable refers to its own object
Java Programming 394
Assignment Operator: A Precaution (continued)
Java Programming
395
Definitions of the Constructors and Methods of the class Clock
Java Programming
396
Definitions of the Constructors and Methods of the class Clock (continued)
Java Programming
397
Definitions of the Constructors and Methods of the class Clock (continued)
Java Programming
398
Definitions of the Constructors and Methods of the class Clock (continued)
Java Programming
399
Definitions of the Constructors and Methods of the class Clock (continued)
Java Programming
400
Definitions of the Constructors and Methods of the class Clock (continued)
Java Programming
401
Definitions of the Constructors and Methods of the class Clock (continued)
Java Programming
402
Definitions of the Constructors and Methods of the class Clock (continued)
Java Programming
403
Definitions of the Constructors and Methods of the class Clock (continued)
Java Programming
404
Definitions of the Constructors and Methods of the class Clock (continued)
Java Programming
405
Definitions of the Constructors and Methods of the class Clock (continued)
Java Programming
406
Definitions of the Constructors and Methods of the class Clock (continued)
Java Programming
407
Default Constructor
or
Java Programming
408
Constructor with Parameters
or
Java Programming
409
The Method toString
public value-returning method Takes no parameters Returns address of a String object Output using print, println, printf methods Default definition creates String with name of objects class name followed by hash code of object
Java Programming 410
Method toString: class Clock
Java Programming
411
The Copy Constructor
Executes when an object is instantiated Initialized using an existing object Syntax
Java Programming
412
The Copy Constructor (continued)
Java Programming
413
The Modifier static
In the method heading, it specifies that the method can be invoked by using the name of the class If used to declare data member, data member invoked by using the class name Static data members of class exist even when no object of class type is instantiated Static variables are initialized to their default values
Java Programming 414
Static Members of a Class
Example 8-5
public class Illustrate { private int x; private static int y; public static int count; public Illustrate() { x = 0; } public Illustrate(int a) { x = a; }
Java Programming 415
Static Members of a Class (continued)
void setX(int a)
{
x = a;
}
public String toString()
{
return("x = " + x + ", y = " + y + ", count = " + count);
}
public static void incrementY()
{
y++;
}
}
Illustrate illusObject = new Illustrate(); Illustrate.incrementY(); Illustrate.count++;
Java Programming 416
Static Members of a Class (continued)
Illustrate illusObject1 = new Illustrate(3); Illustrate illusObject2 = new Illustrate(5);
Java Programming
417
Static Members of a Class (continued)
Illustrate.incrementY(); Illustrate.count++;
Java Programming
418
Finalizers
Automatically execute when class object goes out of scope Have no parameters Only one finalizer per class Name of finalizer: finalize
Java Programming
419
Accessor and Mutator Methods
Accessor Method: a method of a class that only accesses (that is, does not modify) the value(s) of the data member(s) Mutator Method: a method of a class that modifies the value of one or more data member(s)
Java Programming
420
The Reference this
Refers to instance variables and methods of a class Used to implement cascaded method calls
Java Programming
421
Inner Classes
Defined within other classes Can be either a complete class definition or anonymous inner class definition Used to handle events
Java Programming
422
Abstract Data Types
Definition
- A data type that specifies the logical properties without the implementation details
Java Programming
423
Programming Example: Candy Machine (Problem Statement)
A new candy machine is bought for the gym, but it is not working properly
-The machine sells candies, chips, gum, and cookies
Write a two-part program to create a Java application program for this candy machine so that it can be put into operation
- In the first part, design a non-GUI application program - In the second part, design an application program that will create a GUI as described in the second part
Java Programming 424
Programming Example: Candy Machine (Problem Statement) (continued)
The non-GUI application program should do the following:
1. Show the customer the different products sold by the candy machine 2. Let the customer make the selection 3. Show the customer the cost of the item selected 4. Accept money from the customer 5. Release the item
Java Programming 425
Programming Example: Candy Machine (Input and Output)
Input: the item selection and the cost of the item Output: the selected item
Java Programming
426
Programming Example: Candy Machine
Components
Cash Register Dispenser Machine
Java Programming
427
Programming Example: Candy Machine (continued)
Java Programming
428
Programming Example: Candy Machine (continued)
Java Programming
429
Programming Example: Candy Machine (continued)
Java Programming
430
Programming Example: Candy Machine (continued)
Java Programming
431
Programming Example: Candy Machine (continued)
Java Programming
432
Programming Example: Candy Machine (continued)
Java Programming
433
Chapter Summary
Creating classes Members of a class
private protected public static
Implementing classes Various operations on classes
Java Programming 434
Chapter Summary (continued)
Constructors Finalizers Method toString Abstract Data Types
Java Programming
435
Java Programming
Chapter 9 Arrays
Chapter Objectives
Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of array index out of bounds Become familiar with the restrictions on array processing
Java Programming 437
Chapter Objectives (continued)
Discover how to pass an array as a parameter to a method Discover how to manipulate data in a twodimensional array Learn about multidimensional arrays
Java Programming
438
Array
Definition: structured data type with a fixed number of elements Elements of an array are also called components of the array Every element is of the same type Elements are accessed using their relative positions in the array
Java Programming 439
One-Dimensional Arrays
Java Programming
440
One-Dimensional Arrays (continued)
Java Programming
441
One-Dimensional Arrays (continued)
intExp = number of components in array >= 0 0 <= indexExp <= intExp
Java Programming
442
Arrays
Array num: int[] num = new int[5];
Java Programming
443
Arrays (continued)
Array num: int[] num = new int[5];
Java Programming
444
Array List
Java Programming
445
Array List (continued)
Java Programming
446
Array List (continued)
Java Programming
447
Array List (continued)
Java Programming
448
Specifying Array Size During Program Execution
Java Programming
449
Array Initialization During Declaration
The initializer list contains values, called initial values, that are placed between braces and separated by commas sales[0]= 12.25, sales[1]= 32.50, sales[2]= 16.90, sales[3]= 23.00, and sales[4]= 45.68
Java Programming
450
Array Initialization During Declaration (continued)
When declaring and initializing arrays, the size of the array is determined by the number of initial values within the braces If an array is declared and initialized simultaneously, we do not use the operator new to instantiate the array object
Java Programming
451
Arrays and the Instance Variable length
Associated with each array that has been instantiated, there is a public (final) instance variable length The variable length contains the size of the array The variable length can be directly accessed in a program using the array name and the dot operator
int[] list = {10, 20, 30, 40, 50, 60};
Java Programming
452
Arrays and the Instance Variable length (continued)
This statement creates the array list of six components and initializes the components using the values given
Here list.length is 6
int[] numList = new int[10];
This statement creates the array numList of 10 components and initializes each component to 0
Java Programming 453
Arrays and the Instance Variable length (continued)
The value of numList.length is 10
numList[0] numList[1] numList[2] numList[3] = = = = 5; 10; 15; 20;
These statements store 5, 10, 15, and 20, respectively, in the first four components of numList You can store the number of filled elements, that is, the actual number of elements, in the array in a variable, say numOfElement It is a common practice for a program to keep track of the number of filled elements in an array
Java Programming 454
Processing One-Dimensional Arrays
Loops used to step through elements in array and perform operations
int[] list = new int[100]; int i; for (i = 0; i < list.length; i++) //process list[i], the (i + 1)th //element of list
for (i = 0; i < list.length; i++) list[i] = console.nextInt(); for (i = 0; i < list.length; i++) System.out.print(list[i] + " ");
Java Programming 455
Arrays (continued)
Some operations on arrays
Initialize Input data Output stored data Find largest/smallest/sum/average of elements
double[] sales = new double[10]; int index; double largestSale, sum, average;
Java Programming
456
Code to Initialize Array to Specific Value (10.00)
for (int index = 0; index < sales.length; index++) sales[index] = 10.00;
Java Programming
457
Code to Read Data into Array
for (int index = 0; index < sales.length; index++) sales[index] = console.nextDouble();
Java Programming
458
Code to Print Array
for (int index = 0; index < sales.length; index++) System.out.print(sales[index] + " ");
Java Programming
459
Code to Find Sum and Average of Array
sum = 0; for (int index = 0; index < sales.length; index++) sum = sum + sales[index]; if (sales.length != 0) average = sum / sales.length; else average = 0.0;
Java Programming
460
Determining Largest Element in Array
maxIndex = 0; for (int index = 1; index < sales.length; index++) if (sales[maxIndex] < sales[index]) maxIndex = index; largestSale = sales[maxIndex];
Java Programming
461
Determining Largest Element in Array (continued)
Java Programming
462
Determining Largest Element in Array (continued)
Java Programming
463
Array Index Out of Bounds
Array in bounds if:
0 <= index <= arraySize 1
If index < 0 or index > arraySize: ArrayIndexOutOfBoundsException exception is thrown Base address: memory location of first component in array
Java Programming 464
Declaring Arrays as Formal Parameters to Methods
A general syntax to declare an array as a formal parameter
dataType[] arrayName public static void arraysAsFormalParameter(int[] listA, double[] listB, int num) { //... } int[] intList = new int[10]; double[] doubleNumList = new double[15]; int number; arraysAsFormalParameter(intList, doubleNumList, number);
Java Programming 465
The Assignment Operators and Arrays
Java Programming
466
The Assignment Operators and Arrays (continued)
Java Programming
467
The Assignment Operators and Arrays (continued)
Java Programming
468
Relational Operators and Arrays
if (listA == listB)... - The expression listA == listB determines if the values of listA and listB are the same and thus determines whether listA and listB refer to the same array - To determine whether listA and listB contain the same elements, you need to compare them component by component - You can write a method that returns true if two int arrays contain the same elements
Java Programming 469
Relational Operators and Arrays (continued)
boolean { if (firstArray.length != secondArray.length) return false; for (int index = 0; index < firstArray.length; index++) if (firstArray[index] != secondArray[index]) return false; return true; }
areEqualArrays(int[] firstArray,
int[] secondArray)
if (areEqualArrays(listA, listB)) ...
Java Programming 470
Arrays as Parameter Methods
Java Programming
471
Methods for Array Processing
Java Programming
472
Methods for Array Processing (continued)
Java Programming
473
Methods for Array Processing (continued)
Java Programming
474
Methods for Array Processing (continued)
Java Programming
475
Suppose that you want to determine whether 27 is in the list; First you compare 27 with list[0] Because list[0] 27, you then compare 27 with list[1] Because list[1] 27, you compare 27 with list[2]; Because list[2] = 27, the search stops This search is successful
Java Programming 476
Search for 10 Search starts at the first element in the list, that is, at list[0] This time, the search item, which is 10, is compared with every item in the list; eventually, no more data is left in the list to compare with the search item; this is an unsuccessful search
Java Programming 477
public static int seqSearch(int[] list, int listLength, int searchItem) { int loc; boolean found = false; loc = 0; while (loc < listLength && !found) if (list[loc] == searchItem) found = true; else loc++; if (found) return loc; else return -1;
}
Java Programming 478
Arrays of Objects
Can use arrays to manipulate objects Example: create array named array1 with N objects of type T T[] array1 = new T[N] Can instantiate array1 as follows: for (int j = 0; j <array1.length; j++) array1[j] = new T();
Java Programming
479
Array of String Objects
String[] nameList = new String[5]; nameList[0] nameList[1] nameList[2] nameList[3] = = = = "Amanda Green"; "Vijay Arora"; "Sheila Mann"; "Rohit Sharma";
nameList[4] = "Mandy Johnson";
Java Programming
480
Array of String Objects (continued)
Java Programming
481
Arrays of Objects (continued)
Clock[] arrivalTimeEmp = new Clock[100];
Java Programming
482
Instantiating Array Objects
for (int j = 0; j < arrivalTimeEmp.length; j++) arrivalTimeEmp[j] = new Clock();
Java Programming
483
Instantiating Array Objects (continued)
arrivalTimeEmp[49].setTime(8, 5, 10);
Java Programming
484
Arrays and Variable Length Parameter List
The syntax to declare a variable length formal parameter (list) is:
dataType ... identifier
Java Programming
485
Arrays and Variable Length Parameter List (continued)
Java Programming
486
Arrays and Variable Length Parameter List (continued)
Java Programming
487
Arrays and Variable Length Parameter List (continued)
A method can have both a variable length formal parameter and other formal parameters; consider the following method heading:
public static void myMethod(String name, double num, int ... intList)
The formal parameter name is of type String, the formal parameter num is of type double, and the formal parameter intList is of variable length The actual parameter corresponding to intList can be an int array or any number of int variables and/or int values
Java Programming 488
Arrays and Variable Length Parameter List (continued)
A method can have at most one variable length formal parameter If a method has both a variable length formal parameter and other types of formal parameters, then the variable length formal parameter must be the last formal parameter of the formal parameter list
Java Programming 489
foreach Loop
The syntax to use this for loop to process the elements of an array is:
for (dataType identifier : arrayName) statements
identifier is a variable, and the data type of identifier is the same as the data type of the array components
Java Programming
490
foreach loop (continued)
sum = 0; for (double num : list) sum = sum + num;
The for statement in Line 2 is read: for each num in list The identifier num is initialized to list[0] In the next iteration, the value of num is list[1], and so on
for (double num : numList) { if (max < num) max = num; }
Java Programming 491
Two-Dimensional Arrays
Java Programming
492
Two-Dimensional Arrays (continued)
Java Programming
493
Two-Dimensional Arrays (continued)
double[][] sales = new double[10][5];
Java Programming
494
Accessing Array Elements
intExp1, intExp2 >= 0 indexExp1 = row position indexExp2 = column position
Java Programming
495
Accessing Array Elements (continued)
Java Programming
496
Two-Dimensional Arrays and the Instance Variable length
This statement declares and instantiates a twodimensional array matrix of 20 rows and 15 columns The value of the expression: matrix.length is 20, the number of rows
Java Programming 497
Two-Dimensional Arrays and the Instance Variable length (continued)
Each row of matrix is a one-dimensional array; matrix[0], in fact, refers to the first row The value of the expression:
matrix[0].length
is 15, the number of columns in the first row matrix[1].length gives the number of columns in the second row, which in this case is 15, and so on
Java Programming 498
Two-Dimensional Arrays: Special Cases
Java Programming
499
Two-Dimensional Arrays: Special Cases (continued)
Create columns
Java Programming
500
Two-Dimensional Array Initialization During Declaration
Java Programming
501
Two-Dimensional Array Initialization During Declaration (continued)
To initialize a two-dimensional array when it is declared:
- The elements of each row are enclosed within braces and separated by commas - All rows are enclosed within braces
Java Programming
502
Two-Dimensional Array Initialization During Declaration (continued)
Java Programming
503
Two-Dimensional Arrays (continued)
Three ways to process 2-D arrays
Entire array Particular row of array (row processing) Particular column of array (column processing)
Processing algorithms similar to processing algorithms of one-dimensional arrays
Java Programming
504
Two-Dimensional Arrays: Processing
Initialization
for (int row = 0; row < matrix.length; row++) for (int col = 0; col < matrix[row].length; col++) matrix[row][col] = 10;
Print
for (int row = 0; row < matrix.length; row++) { for (int col = 0; col < matrix[row].length; col++)
System.out.printf("%7d", matrix[row][col]);
System.out.println(); }
Java Programming 505
Two-Dimensional Arrays: Processing (continued)
Input
for (int row = 0; row < matrix.length; row++) for (int col = 0; col < matrix[row].length; col++) matrix[row][col] = console.nextInt();
Sum by Row
for (int row = 0; row < matrix.length; row++) { sum = 0; for (int col = 0; col < matrix[row].length; col++) sum = sum + matrix[row][col];
System.out.println("Sum of row " + (row + 1) + " = "+ sum);
}
Java Programming 506
Two-Dimensional Arrays: Processing (continued)
Sum by Column
for (int col = 0; col < matrix[0].length; col++) { sum = 0; for (int row = 0; row < matrix.length; row++) sum = sum + matrix[row][col];
System.out.println("Sum of column " + (col + 1) + " = " + sum);
Java Programming
507
Two-Dimensional Arrays: Processing (continued)
Largest Element in Each Row
for (int row = 0; row < matrix.length; row++) { largest = matrix[row][0]; for (int col = 1; col < matrix[row].length; col++) if (largest < matrix[row][col]) largest = matrix[row][col];
System.out.println("The largest element of row " + (row + 1) + " = " + largest);
}
Java Programming 508
Two-Dimensional Arrays: Processing (continued)
Largest Element in Each Column
for (int col = 0; col < matrix[0].length; col++) { largest = matrix[0][col]; for (int row = 1; row < matrix.length; row++) if (largest < matrix[row][col]) largest = matrix[row][col];
System.out.println("The largest element of col " + (col + 1) + " = " + largest);
}
Java Programming 509
Java Programming
510
Java Programming
511
Java Programming
512
Multidimensional Arrays
Can define three-dimensional arrays or n-dimensional array (n can be any number) Syntax to declare and instantiate array dataType[][][] arrayName = new
dataType[intExp1][intExp2][intExpn];
Syntax to access component
arrayName[indexExp1][indexExp2][indexExpn]
intExp1, intExp2, ..., intExpn = positive integers indexExp1,indexExp2, ..., indexExpn = non-negative integers
Java Programming 513
Loops to Process Multidimensional Arrays
double[][][] carDealers = new double[10][5][7]; for (int i = 0; i < 10; i++) for (int j = 0; j < 5; j++) for (int k = 0; k < 7; k++) carDealers[i][j][k] = 10.00;
Java Programming
514
Programming Example: Text Processing
Program: reads given text; outputs the text as is; prints number of lines and number of times each letter appears in text Input: file containing text to be processed Output: file containing text, number of lines, number of times letter appears in text
Java Programming
515
Programming Example Solution: Text Processing
An array of 26 representing the letters in the alphabet Three methods
copyText characterCount writeTotal
Value in appropriate index incremented using methods and depending on character read from text
Java Programming 516
Chapter Summary
Arrays
Definition Uses
Different Arrays
One-dimensional Two-dimensional Multidimensional (n-dimensional) Arrays of objects Parallel arrays
517
Java Programming
Chapter Summary (continued)
Declaring arrays Instantiating arrays Processing arrays
Entire array Row processing Column processing
Common operations and methods performed on arrays Manipulating data in arrays
Java Programming 518
Java Programming
Chapter 10 Inheritance and Polymorphism
Chapter Objectives
Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses and subclasses work
Java Programming
520
Chapter Objectives (continued)
Learn about polymorphism Examine abstract classes Become aware of interfaces Learn about composition
Java Programming
521
Inheritance
is-a relationship Single inheritance
Subclass is derived from one existing class (superclass)
Multiple inheritance
Subclass is derived from more than one superclass Not supported by Java In Java, a class can only extend the definition of one class
Java Programming 522
Inheritance (continued)
modifier(s) class ClassName extends ExistingClassName modifier(s) { memberList }
Java Programming 523
Inheritance: class Circle Derived from class Shape
public class Circle extends Shape { . . . }
Java Programming
524
Inheritance Rules (continued)
1. The private members of the superclass are private to the superclass 2. The subclass can directly access the public members of the superclass 3. The subclass can include additional data and/or method members
Java Programming
525
Inheritance Rules (continued)
4. The subclass can override, that is, redefine the public methods of the superclass
However, this redefinition applies only to the objects of the subclass, not to the objects of the superclass
5. All data members of the superclass are also data members of the subclass
Similarly, the methods of the superclass (unless overridden) are also the methods of the subclass Remember Rule 1 when accessing a member of the superclass in the subclass
Java Programming 526
Inheritance (continued)
To write a methods definition of a subclass, specify a call to the public method of the superclass
If subclass overrides public method of superclass, specify call to public method of superclass: super.MethodName(parameter list) If subclass does not override public method of superclass, specify call to public method of superclass: MethodName(parameter list)
Java Programming 527
UML Class Diagram: class Rectangle
Java Programming
528
UML Class Diagram: class Box
Java Programming
529
class Box
public String toString() { return super.toString() //retrieve length and width + "; Height = " + height; } public void setDimension(double l, double w, double h) { super.setDimension(l, w); if (h >= 0) height = h; else height = 0; } public double area() { return 2 * (getLength() * getWidth() + getLength() * height + getWidth() * height); }
Java Programming 530
Defining Constructors of the Subclass
Call to constructor of superclass
Must be first statement Specified by: super parameter list
public Box() { super(); height = 0; } public Box(double l, double w, double h) { super(l, w); height = h; }
Java Programming 531
Objects myRectangle and myBox
Rectangle myRectangle = new Rectangle(5, 3); Box myBox = new Box(6, 5, 4);
Java Programming
532
UML Class Diagram
Java Programming
533
Protected Members of a Class
The private members of a class are private to the class and cannot be directly accessed outside the class Only methods of that class can access the private members directly; as discussed previously, the subclass cannot access the private members of the superclass directly If you make a private member public, then anyone can access that member If a member of a superclass needs to be (directly) accessed in a subclass and yet still prevent its direct access outside the class you must declare that member using the modifier protected The accessibility of a protected member of a class falls between public and private A subclass can directly access the protected member of a superclass
Java Programming 534
The class Object
Directly or indirectly becomes the superclass of every class in Java public members of class Object can be overridden/invoked by object of any class type
Java Programming
535
The class Object: Equivalent Definition of a Class public class Clock
{
//Declare instance variables as given in Chapter 8 //Definition of instance methods as given in Chapter 8 //...
public class Clock extends Object {
//Declare instance variables as given in Chapter 8 //Definition of instance methods as given in Chapter 8 //...
Java Programming
536
Some Constructors and Methods of the class Object
Java Programming
537
Hierarchy of Java Stream Classes
Java Programming
538
Polymorphism
Java allows us to treat an object of a subclass as an object of its superclass
In other words, a reference variable of a superclass type can point to an object of its subclass
Person name, nameRef; PartTimeEmployee employee, employeeRef; name = new Person("John", "Blair"); employee = new PartTimeEmployee("Susan", "Johnson",
12.50, 45);
nameRef = employee; System.out.println("nameRef: " + nameRef); nameRef: Susan Johnson wages are: $562.5
Java Programming 539
Polymorphism (continued)
Late binding or dynamic binding (run-time binding)
Method executed determined at execution time, not compile time
The term polymorphism means assigning multiple meanings to the same method name In Java, polymorphism is implemented using late binding The reference variable name or nameRef can point to any object of the class Person or the class PartTimeEmployee
Java Programming 540
Polymorphism (continued)
These reference variables have many forms; that is, they are polymorphic reference variables
They can refer to objects of their own class or objects of the classes inherited from their class
You can declare a method of a class final using the key word final; for example, the following method is final:
public final void doSomeThing() { //... }
Java Programming 541
Polymorphism (continued)
If a method of a class is declared final, it cannot be overridden with a new definition in a derived class In a similar manner, you can also declare a class final using the keyword final If a class is declared final, then no other class can be derived from this class Java does not use late binding for methods that are private, marked final, or static
Java Programming 542
Polymorphism (continued)
You cannot automatically make reference variable of subclass type point to object of its superclass Suppose that supRef is a reference variable of a superclass type; moreover, suppose that supRef points to an object of its subclass You can use an appropriate cast operator on supRef and make a reference variable of the subclass point to the object
Java Programming 543
Polymorphism (continued)
On the other hand, if supRef does not point to a subclass object and you use a cast operator on supRef to make a reference variable of the subclass point to the object, then Java will throw a ClassCastExceptionindicating that the class cast is not allowed
Java Programming 544
Polymorphism (continued)
Operator instanceof: determines whether reference variable that points to object is of particular class type
p instanceof BoxShape
This expression evaluates to true if p points to an object of the class BoxShape; otherwise it evaluates to false
Java Programming 545
Abstract Methods
Abstract method: method that has only the heading with no body
Must be declared abstract
public void abstract print(); public abstract object larger(object, object); void abstract insert(int insertItem);
Java Programming 546
Abstract Classes
Abstract class: class that is declared with the reserved word abstract in its heading
An abstract class can contain instance variables, constructors, finalizer, and nonabstract methods An abstract class can contain abstract method(s) If a class contains an abstract method, then the class must be declared abstract You cannot instantiate an object of an abstract class type; you can only declare a reference variable of an abstract class type You can instantiate an object of a subclass of an abstract class, but only if the subclass gives the definitions of all the abstract methods of the superclass
Java Programming 547
Abstract Class Example
public abstract class AbstractClassExample { protected int x;
public void abstract print();
public void setX(int a) { x = a; }
public AbstractClassExample() { x = 0; } }
Java Programming 548
Interfaces
Definition: class that contains only abstract methods and/or named constants How Java implements multiple inheritance To be able to handle a variety of events, Java allows a class to implement more than one interface
Java Programming
549
Some Interface Definitions
public interface WindowListener { public void windowOpened(WindowEvent e); public void windowClosing(WindowEvent e); public void windowClosed(WindowEvent e); public void windowIconified(WindowEvent e); public void windowDeiconified(WindowEvent e); public void windowActivated(WindowEvent e); public void windowDeactivated(WindowEvent e); }
public interface ActionListener { public void actionPerformed(ActionEvent e); }
Java Programming 550
Polymorphism via Interfaces
An interface can be used in the implementation of abstract data types Define an interface that contains the methods headings and/or named constants You can define the class that implements the interface The user can look at the interface and see what operations are implemented by the class Just as you can create polymorphic references to classes in an inheritance hierarchy, you can also create polymorphic references using interfaces You can use an interface name as the type of a reference variable, and the reference variable can point to any object of any class that implements the interface Because an interface contains only methods headings and/or named constants, you cannot create an object of an interface
Java Programming 551
Composition (Aggregation)
Another way to relate two classes One or more members of a class are objects of another class type has-a relation between classes
e.g., every person has a date of birth
Java Programming
552
Composition (Aggregation) Example
Java Programming
553
Composition (Aggregation) Example (continued)
Java Programming
554
Programming Example: Grade Report
Components: student, course Operations on course
Set course information Print course information Show credit hours Show course number
Java Programming
555
Components Course and Student
Java Programming
556
Components Course and Student (continued)
Java Programming
557
Programming Example: Grade Report
Operations on student
Set student information Print student information Calculate number of credit hours taken Calculate GPA Calculate billing amount Sort the courses according to the course number
558
Java Programming
Programming Example: Grade Report (continued)
Main algorithm
Declare variables Open input file Open output file Get number of students registered and tuition rate Load students data Print grade reports
Java Programming 559
Sample Output: Grade Report Program
Java Programming
560
Chapter Summary
Inheritance
Single and multiple Rules Uses Superclasses/subclasses (objects) Overriding/overloading methods Constructors
The class Object
Java Programming 561
Chapter Summary (continued)
Java stream classes Polymorphism Abstract methods Abstract classes Interfaces Composition
562
Java Programming
Java Programming
Chapter 11 Handling Exceptions and Events
Chapter Objectives
Learn what an exception is See how a try/catch block is used to handle exceptions Become aware of the hierarchy of exception classes Learn about checked and unchecked exceptions
Java Programming 564
Chapter Objectives (continued)
Learn how to handle exceptions within a program Discover how to throw and rethrow an exception Learn how to handle events in a program
Java Programming
565
Exception
Definition: an occurrence of an undesirable situation that can be detected during program execution Examples
Division by zero Trying to open an input file that does not exist An array index that goes out of bounds
Java Programming 566
Handling Exception within a Program
Can use an if statement to handle an exception However, suppose that division by zero occurs in more than one place within the same block
In this case, using if statements may not be the most effective way to handle the exception
Java Programming
567
Javas Mechanism of Exception Handling
When an exception occurs, an object of a particular exception class is created Java provides a number of exception classes to effectively handle certain common exceptions such as division by zero, invalid input, and file not found Division by zero is an arithmetic error and is handled by the class ArithmeticException
Java Programming 568
Javas Mechanism of Exception Handling (continued)
When a division by zero exception occurs, the program creates an object of the class ArithmeticException When a Scanner object is used to input data into a program, any invalid input errors are handled using the class InputMismatchException The class Exception (directly or indirectly) is the superclass of all the exception classes in Java
Java Programming 569
try/catch/finally Block
Statements that might generate an exception are placed in a try block The try block might also contain statements that should not be executed if an exception occurs The try block is followed by zero or more catch blocks A catch block specifies the type of exception it can catch and contains an exception handler
Java Programming 570
try/catch/finally Block (continued)
The last catch block may or may not be followed by a finally block Any code contained in a finally block always executes, regardless of whether an exception occurs, except when the program exits early from a try block by calling the method System.exit If a try block has no catch block, then it must have the finally block
Java Programming 571
try/catch/finally Block (continued)
Java Programming
572
try/catch/finally Block (continued)
If no exception is thrown in a try block, all catch blocks associated with the try block are ignored and program execution resumes after the last catch block If an exception is thrown in a try block, the remaining statements in the try block are ignored
- The program searches the catch blocks in the order in which they appear after the try block and looks for an appropriate exception handler
Java Programming 573
try/catch/finally Block (continued)
If the type of the thrown exception matches the parameter type in one of the catch blocks, the code of that catch block executes and the remaining catch blocks after this catch block are ignored If there is a finally block after the last catch block, the finally block executes regardless of whether an exception occurs
Java Programming 574
Order of catch Blocks
The heading of a catch block specifies the type of exception it handles A catch block can catch either all exceptions of a specific type or all types of exceptions A reference variable of a superclass type can point to an object of its subclass
Java Programming
575
Order of catch Blocks (continued)
If in the heading of a catch block you declare an exception using the class Exception, then that catch block can catch all types of exceptions because the class Exception is the superclass of all exception classes In a sequence of catch blocks following a try block, a catch block declaring an exception of a subclass type should be placed before catch blocks declaring exceptions of a superclass type
Java Programming 576
Java Exception Hierarchy
Java Programming
577
Java Exception Hierarchy (continued)
Java Programming
578
Java Exception Hierarchy (continued)
Java Programming
579
Java Exception Hierarchy (continued)
Java Programming
580
Java Exception Hierarchy (continued)
Java Programming
581
Javas Exception Class
class Exception
Subclass of class Throwable Superclass of classes designed to handle exceptions
Various types of exceptions
I/O exceptions Number format exceptions File not found exceptions Array index out of bounds exceptions
Various exceptions categorized into separate classes and contained in various packages
Java Programming 582
The class Exception and its Constructors
Java Programming
583
Java Exception Classes
Java Programming
584
Java Exception Classes (continued)
Java Programming
585
Java Exception Classes (continued)
Java Programming
586
Java Exception Classes (continued)
Java Programming
587
Java Exception Classes (continued)
Java Programming
588
Java Exception Classes (continued)
Java Programming
589
Java Exception Classes (continued)
Java Programming
590
Java Exception Classes (continued)
Java Programming
591
Checked Exceptions
Definition: any exception that can be recognized by the compiler Examples
FileNotFoundExceptions
Java Programming
592
Unchecked Exceptions
Definition: exceptions that cannot be recognized when the program compiles (must be checked for by programmer) Examples
Division by zero Array index out of bounds
Syntax ExceptionType1, ExceptionType2, and so on are names of exception classes
Java Programming 593
Exceptions Example Code
public static void exceptionMethod() throws InputMismatchException, FileNotFoundException { //statements }
The method exceptionMethod throws exceptions of the type InputMismatchException and FileNotFoundException
Java Programming 594
The class Exception and the Operator instanceof
A reference of a superclass type can point to objects of its subclass You can determine if a reference variable points to an object using the operator instanceof You can combine catch blocks using this facility
Java Programming 595
The class Exception and the Operator instanceof
try
{
System.out.print("Line 4: Enter the " + "dividend: "); dividend = console.nextInt(); System.out.println(); System.out.print("Line 7: Enter the " + "divisor: "); divisor = console.nextInt(); System.out.println(); quotient = dividend / divisor; System.out.println("Line 11: Quotient = " + quotient);
}
catch (Exception eRef)
{
if (eRef instanceof ArithmeticException) System.out.println("Line 14: Exception " + eRef.toString()); else if (eRef instanceof InputMismatchException) System.out.println("Line 16: Exception " + eRef.toString());
}
Java Programming
596
Rethrowing and Throwing an Exception
When an exception occurs in a try block, control immediately passes to one of the catch blocks; typically, a catch block does one of the following:
Completely handles the exception Partially processes the exception; in this case, the catch block either rethrows the same exception or throws another exception for the calling environment to handle the exception Rethrows the same exception for the calling environment to handle the exception
Java Programming 597
Rethrowing and Throwing an Exception (continued)
Useful when:
Catch block catches exception but is unable to handle it Catch block decides exception should be handled by calling environment
Allows programmer to provide exception handling code in one place Syntax
throw exceptionReference;
Java Programming 598
import java.util.*; public class RethrowExceptionExmp1 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { int number; try { number = getNumber(); System.out.println("Line 5: number = " + number); } catch (InputMismatchException imeRef) { System.out.println("Line 7: Exception " + imeRef.toString()); } } } Java Programming
Rethrowing and Throwing an Exception (continued)
599
Rethrowing and Throwing an Exception (continued)
public static int getNumber() throws InputMismatchException { int num; try { System.out.print("Line 11: Enter an + "integer: "); num = console.nextInt(); System.out.println(); return num; } catch (InputMismatchException imeRef) { throw imeRef; } } }
Java Programming 600
The Method printStackTrace
Used to determine the order in which the methods were called and where the exception was handled
Java Programming
601
import java.io.*; public class PrintStackTraceExample1 { public static void main(String[] args) { try { methodA(); } catch (Exception e) { e.printStackTrace(); } }
Java Programming
The Method printStackTrace (continued)
System.out.println(e.toString() + " caught in main");
602
The Method printStackTrace (continued)
public static void methodA() throws Exception { methodB(); } public static void methodB() throws Exception { methodC(); } public static void methodC() throws Exception { throw new Exception("Exception generated " + "in method C"); } }
Java Programming 603
The Method printStackTrace (continued)
Sample Run
java.lang.Exception: Exception generated in method C caught in main java.lang.Exception: Exception generated in method C at PrintStackTraceExample1.methodC (PrintStackTraceExample1.java:30) at PrintStackTraceExample1.methodB (PrintStackTraceExample1.java:25) at PrintStackTraceExample1.methodA (PrintStackTraceExample1.java:20) at PrintStackTraceExample1.main (PrintStackTraceExample1.java:9)
Java Programming
604
Exception-Handling Techniques
Terminate program
Output appropriate error message upon termination
Fix error and continue
Repeatedly get user input Output appropriate error message until valid value is entered
Log error and continue
Write error messages to file and continue with program execution
Java Programming 605
Creating Your Own Exception Classes
Exception class you define extends class Exception or one of its subclasses Syntax to throw your own exception object:
throw new ExceptionClassName(messageString);
Java Programming
606
Creating Your Own Exception Classes (continued)
public class MyDivisionByZeroException extends Exception { public MyDivisionByZeroException() { super("Cannot divide by zero"); } public MyDivisionByZeroException(String strMessage) { super(strMessage); } }
Java Programming 607
Event Handling
Action events
Handled by implementing interface ActionListener
Window events
Handled by implementing interface WindowListener
Mouse events
Handled by implementing interface MouseListener
Key events
Handled by implementing interface KeyListener
Java Programming 608
Event Handling (continued)
class WindowAdapter
Implements interface WindowListener with empty bodies to methods
class MouseAdapter
Implements interface MouseListener with empty bodies to methods
Java Programming
609
Registering Listeners
Registering window listener object to GUI component
Use method addWindowListener Window listener object being registered is passed as parameter to method addWindowListener
Registering mouse listener object to GUI component
Use method addMouseListener Mouse listener object being registered is passed as parameter to method addMouseListener
Java Programming 610
Event Handling (continued)
Java Programming
611
Event Handling (continued)
Java Programming
612
Event Handling (continued)
Java Programming
613
Programming Example: Calculator
Java Programming
614
Chapter Summary
Exception
Definition
Handling exceptions within a program
try/catch/finally block Order of catch blocks Using try/catch blocks in a program The class Exception and the Operator instanceof Rethrowing and throwing an exception
Exception
Hierarchy Classes
Java Programming 615
Chapter Summary (continued)
Checked and unchecked exceptions The method printStackTrace Exception-handling techniques
Terminate program Fix error and continue Log error and continue
Creating your own exception classes Event handling
Java Programming 616
Java Programming
Chapter 12 Advanced GUIs and Graphics
Chapter Objectives
Learn about applets Explore the class Graphics Learn about the class Font Explore the class Color
Java Programming
618
Chapter Objectives (continued)
Learn to use additional layout managers Become familiar with more GUI components Learn how to create menu-based programs Explore how to handle key and mouse events
Java Programming
619
Inheritance Hierarchy of GUI Classes
Java Programming
620
Constructors and Methods of the class Component
Java Programming
621
Constructors and Methods of the class Component (continued)
Java Programming
622
Constructors and Methods of the class Component (continued)
Java Programming
623
Constructors and Methods of the class Component (continued)
Java Programming
624
Constructors and Methods of the class Container
Java Programming
625
Applets
Applet: a Java program that is embedded within a Web page and executed by a Web browser Create an applet by extending the class JApplet class JApplet contained in package javax.swing
Java Programming 626
Members of class JApplet
Java Programming
627
Members of class Japplet (continued)
Java Programming
628
Applets (continued)
No main method Methods init, start, and paint guaranteed to be invoked in sequence To develop an applet:
Override any/all of the methods above
Java Programming
629
Applet Methods
init Method
Initializes variables Gets data from user Places various GUI components
paint Method
Performs output
Java Programming
630
Skeleton of a Java Applet
import java.awt.Graphics; import javax.swing.JApplet; public class WelcomeApplet extends JApplet {
Java Programming
631
Applet Displaying Welcome Message //Welcome Applet
import java.awt.Graphics; import javax.swing.JApplet; public class WelcomeApplet extends JApplet { public void paint(Graphics g) { super.paint(g); //Line 1 g.drawString("Welcome to Java Programming" , 30, 30); //Line 2 } }
Java Programming 632
HTML to Run Applet
Java Programming
633
class Font
Shows text in different fonts Contained in package java.awt Available fonts
Serif/SanSerif Monospaced Dialog/DialogInput
Arguments for constructor
String specifying the Font face name int value specifying Font style int value specifying Font size
Expressed in points (72 points = 1 inch)
Java Programming 634
Constructors and Methods of the class Font
Java Programming
635
Constructors and Methods of the class Font (continued)
Java Programming
636
Constructors and Methods of the class Font (continued)
Java Programming
637
class Color
Shows text in different colors Changes background color of component Contained in package java.awt
Java Programming
638
Constructors of the class Color
Java Programming
639
Constructors of the class Color (continued)
Java Programming
640
Constants Defined in the class Color
Java Programming
641
Constants Defined in the class Color (continued)
Java Programming
642
Constants Defined in the class Color (continued)
Java Programming
643
class Graphics
Provides methods for drawing items such as lines, ovals, and rectangles on the screen Contains methods to set the properties of graphic elements including clipping area, fonts, and colors Contained in the package java.awt
Java Programming
644
Constructors and Methods of the class Graphics
Java Programming
645
Constructors and Methods of the class Graphics (continued)
Java Programming
646
Constructors and Methods of the class Graphics (continued)
Java Programming
647
Constructors and Methods of the class Graphics (continued)
Java Programming
648
Constructors and Methods of the class Graphics (continued)
Java Programming
649
Constructors and Methods of the class Graphics (continued)
Java Programming
650
Constructors and Methods of the class Graphics (continued)
Java Programming
651
Constructors and Methods of the class Graphics (continued)
Java Programming
652
Differences Between Applets and GUI Applications
Applets
Derived from JApplet No main method Uses init method Displayed by HTML Sets title in HTML Size set in HTML Applet closes when HTML doc closes
Java Programming
GUI applications
class extends JFrame Invokes main method Uses constructors Uses method setVisible Uses setTitle method Uses method setSize Closes with Exit button
653
Converting a GUI Application to an Applet
Change JFrame to JApplet Change constructor to method init Remove method calls such as setVisible, setTitle, setSize Remove the method main If applicable, remove Exit button/all code associated with it (e.g., action listener)
Java Programming 654
Additional GUI Components
JTextArea JCheckBox JRadioButton JComboBox JList
Java Programming
655
JTextArea
Can collect multiple lines of input from user Can display multiple lines of output Pressing Enter key separates lines of text Each line ends with newline character \n Derived from class JTextComponent
Java Programming
656
JTextArea (continued)
Java Programming
657
Methods Inherited by class JTextArea from Parent class JTextComponent
Java Programming
658
JTextArea Example
Java Programming
659
JCheckBox
User selects from predefined values Example of a toggle button Clicking JCheckBox generates item event Use interface ItemListener and its abstract method itemStateChanged to handle event
Java Programming
660
Constructors and Methods of class JCheckBox
Java Programming
661
Constructors and Methods of class JCheckBox (continued)
Java Programming
662
Constructors and Methods of class JCheckBox (continued)
Java Programming
663
Constructors and Methods of class JCheckBox (continued)
Java Programming
664
JRadioButton
Created same way as check boxes Placed in content pane of applet Forces user to select only one radio button at a time You create a button group to group radio buttons Generates an ItemEvent interface ItemListener and method itemStateChanged used to handle events
Java Programming 665
JRadioButton (continued)
Java Programming
666
JRadioButton (continued)
Java Programming
667
JRadioButton (continued)
Java Programming
668
JRadioButton (continued)
Java Programming
669
JComboBox
Commonly known as a drop-down list Used to select an item from a list of possibilities Generates an ItemEvent Event monitored by ItemListener ItemListener invokes method itemStateChanged
Java Programming 670
Constructors of class JComboBox
Java Programming
671
Applet with JCheckBox, JComboBox, and JRadioButton
Java Programming
672
Constructors of class JList
Java Programming
673
Constructors of class Jlist (continued)
Java Programming
674
Constructors of class Jlist (continued)
Java Programming
675
Layout Managers
FlowLayout
Default layout manager Places components from left to right, center by default, until no more items can be placed Can align each line left, center, or right Default alignment: LEFT
GridLayout
Similar to FlowLayout All rows (columns) have same number of components All components have the same size
Java Programming 676
Layout Managers (continued)
BorderLayout
Items placed into one of five specific regions
NORTH/SOUTH EAST/WEST CENTER
NORTH and SOUTH components extend horizontally (completely span one edge to the other) EAST and WEST components extend vertically between components in NORTH and SOUTH regions CENTER component expands to occupy any unused regions
Java Programming 677
Menus
Allow for various functions without cluttering GUI with too many components Can be attached to objects such as JFrame and JApplet (setJMenuBar method) To set a menu bar:
private JMenuBar menuMB = new JMenuBar(); setJMenuBar(menuMB);
Add menus to menu bar; add menu items to menu Order of menus added = Order of appearance
Java Programming 678
Key and Mouse Events
Java Programming
679
Chapter Summary
Creating applets class Font class Graphics class Color Differences between applet and GUI application Converting GUI application to applet
Java Programming 680
Chapter Summary (continued)
GUI components
JTextArea JCheckBox JRadioButton
Layout managers Menus Key and mouse events
Java Programming 681
Java Programming
Chapter 13 Recursion
Chapter Objectives
Learn about recursive definitions Explore the base case and the general case of a recursive definition Learn about recursive algorithms
Java Programming
683
Chapter Objectives (continued)
Learn about recursive methods Become aware of direct and indirect recursion Explore how to use recursive methods to implement recursive algorithms
Java Programming
684
Recursive Definitions
Recursion
Process of solving a problem by reducing it to smaller versions of itself
Recursive definition
Definition in which a problem is expressed in terms of a smaller version of itself Has one or more base cases
Java Programming
685
Recursive Definitions (continued)
Java Programming
686
Recursive Definitions (continued)
Recursive algorithm
Algorithm that finds the solution to a given problem by reducing the problem to smaller versions of itself Has one or more base cases Implemented using recursive methods
Recursive method
Method that calls itself
Base case
Case in recursive definition in which the solution is obtained directly Stops the recursion
Java Programming 687
Recursive Definitions (continued)
General solution
Breaks problem into smaller versions of itself
General case
Case in recursive definition in which a smaller version of itself is called Must eventually be reduced to a base case
Java Programming
688
Tracing a Recursive Method
Recursive method
Logically, you can think of a recursive method having unlimited copies of itself Every recursive call has its own:
Code Set of parameters Set of local variables
Java Programming
689
Tracing a Recursive Method (continued)
After completing a recursive call
Control goes back to the calling environment Recursive call must execute completely before control goes back to previous call Execution in previous call begins from point immediately following recursive call
Java Programming
690
Recursive Definitions
Directly recursive: a method that calls itself Indirectly recursive: a method that calls another method and eventually results in the original method call Tail recursive method: recursive method in which the last statement executed is the recursive call Infinite recursion: the case where every recursive call results in another recursive call
Java Programming 691
Designing Recursive Methods
Understand problem requirements Determine limiting conditions Identify base cases
Java Programming
692
Designing Recursive Methods (continued)
Provide direct solution to each base case Identify general case(s) Provide solutions to general cases in terms of smaller versions of general cases
Java Programming
693
Recursive Factorial Method
public static int fact(int num) { if (num = = 0) return 1; else return num * fact(num 1); }
Java Programming
694
Recursive Factorial Method (continued)
Java Programming
695
Largest Value in Array
Java Programming
696
Largest Value in Array (continued)
if the size of the list is 1 the largest element in the list is the only element in the list else to find the largest element in list[a]...list[b] a. find the largest element in list[a + 1]...list[b] and call it max b. compare list[a] and max if (list[a] >= max) the largest element in list[a]...list[b] is list[a] else the largest element in list[a]...list[b] is max
Java Programming 697
Largest Value in Array (continued)
public static int largest(int[] list, int lowerIndex, int upperIndex) { int max; if (lowerIndex == upperIndex) return list[lowerIndex]; else { max = largest(list, lowerIndex + 1, upperIndex); if (list[lowerIndex] >= max) return list[lowerIndex]; else return max; } }
Java Programming 698
Execution of largest (list, 0, 3)
Java Programming
699
Execution of largest (list, 0, 3)
Java Programming
700
Recursive Fibonacci
Java Programming
701
Recursive Fibonacci (continued)
public static int rFibNum(int a, int b, int n) { if (n == 1) return a; else if (n == 2) return b; else return rFibNum(a, b, n -1) + rFibNum(a, b, n - 2); }
Java Programming 702
Recursive Fibonacci (continued)
Java Programming
703
Towers of Hanoi Problem with Three Disks
Java Programming
704
Towers of Hanoi: Three Disk Solution
Java Programming
705
Towers of Hanoi: Three Disk Solution (continued)
Java Programming
706
Towers of Hanoi: Recursive Algorithm
public static void moveDisks(int count, int needle1, int needle3, int needle2) { if (count > 0) { moveDisks(count - 1, needle1, needle2, needle3); System.out.println("Move disk " + count + " from needle " + needle1 + " to needle " + needle3 + ". "); moveDisks(count - 1, needle2, needle3, needle1); } }
Java Programming 707
Recursion or Iteration?
Two ways to solve particular problem
Iteration Recursion
Iterative control structures: use looping to repeat a set of statements Tradeoffs between two options
Sometimes recursive solution is easier Recursive solution is often slower
Java Programming 708
Programming Example: Decimal to Binary
Java Programming
709
Java Programming
710
Sierpinski Gaskets of Various Orders
Java Programming
711
Programming Example: Sierpinski Gasket
Input: nonnegative integer indicating level of Sierpinski gasket Output: triangle shape displaying a Sierpinski gasket of the given order Solution includes:
Recursive method drawSierpinski Method to find midpoint of two points
Java Programming 712
Programming Example: Sierpinski Gasket (continued)
private void drawSierpinski(Graphics g, int lev, Point p1, Point p2, Point p3) { Point midP1P2; Point midP2P3; Point midP3P1; if (lev > 0) { g.drawLine(p1.x, p1.y, p2.x, p2.y); g.drawLine(p2.x, p2.y, p3.x, p3.y); g.drawLine(p3.x, p3.y, p1.x, p1.y); midP1P2 = midPoint(p1, p2); midP2P3 = midPoint(p2, p3); midP3P1 = midPoint(p3, p1); drawSierpinski(g, lev - 1, p1, midP1P2, midP3P1); drawSierpinski(g, lev - 1, p2, midP2P3, midP1P2); drawSierpinski(g, lev - 1, p3, midP3P1, midP2P3); } } Java Programming
713
Programming Example: Sierpinski Gasket (continued)
Java Programming
714
Chapter Summary
Recursive definitions Recursive algorithms Recursive methods Base cases General cases
Java Programming
715
Chapter Summary (continued)
Tracing recursive methods Designing recursive methods Varieties of recursive methods Recursion vs. iteration Various recursive functions explored
Java Programming
716