Java Programming
Java Programming
Chapter 1An Overview of Computers and
Programming Languages
2Java Programming
3Java Programming
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
4Java Programming
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 object-oriented programming design methodologies
5Java Programming
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
6Java Programming
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
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
8Java Programming
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
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
10Java Programming
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
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
12Java Programming
Elements of a Computer System
• A computer has two components
– Hardware
– Software
13Java Programming
Hardware Components of a
Computer
• Central Processing Unit (CPU)
• Main Memory
14Java Programming
Central Processing Unit
• Arithmetic and logical operations are
carried out inside the CPU
15Java Programming
Central Processing Unit and Main
Memory
16Java Programming
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
17Java Programming
Secondary Storage
• Provides permanent storage for information
• Examples of secondary storage:
– Hard disks
– Floppy disks
– Flash memory
– ZIP disks
– CD-ROMs
– Tapes
18Java Programming
Input Devices
• Definition: devices that feed data and
computer programs into computers
• Examples
– Keyboard
– Mouse
– Secondary storage
19Java Programming
Output Devices
• Definition: devices that the computer uses
to display results
• Examples
– Printer
– Monitor
– Secondary storage
20Java Programming: From Problem Analysis to Program Design, 4e
Input/Output Devices
20Java Programming
21Java Programming
Software
• Software consists of programs written to
perform specific tasks
• Two types of programs
– System programs
– Application programs
22Java Programming
System Programs
• System programs control the computer
• The operating system is first to load when
you turn on a computer
23Java Programming
Operating System (OS)
• OS monitors overall activity of the
computer and provides services
• Example services
– Memory management
– Input/output
– Activities
– Storage management
24Java Programming
Application Programs
• Written using programming languages
• Perform a specific task
• Run by the OS
• Example programs
– Word processors
– Spreadsheets
– Games
25Java Programming
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
26Java Programming
Language of a Computer (continued)
27Java Programming
Evolution of Programming
Languages
• Early computers programmed in machine language
• Assembly languages were developed to make programmer’s job easier
• In assembly language, an instruction is an easy-to-remember form called a mnemonic
• Assembler: translates assembly language instructions into machine language
28Java Programming
Instructions in Assembly and
Machine Language
29Java Programming
Evolution of Programming
Languages
• High-level languages make programming easier
• Closer to spoken languages
• Examples
– Basic
– FORTRAN
– COBOL
– C/C++
– Java
30Java 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
31Java Programming
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
32Java Programming
A Java Program
Output:
33Java Programming
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
34Java Programming
Processing a Java Program (continued)
35Java Programming
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 Defense’s 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
36Java Programming: From Problem Analysis to Program Design, 4e
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
36Java Programming
37Java Programming: From Problem Analysis to Program Design, 4e
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
37Java Programming
38Java Programming: From Problem Analysis to Program Design, 4e
Problem-Analysis-Coding-
Execution Cycle
• Algorithm: a step-by-step problem-solving
process in which a solution is arrived at in a
finite amount of time
38Java Programming
39Java Programming
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
40Java Programming
Problem-Analysis-Coding-
Execution Cycle (continued)
41Java Programming
Programming Methodologies
• Two basic approaches to programming
design
– Structured design
– Object-oriented design
42Java Programming
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
43Java Programming
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
44Java Programming
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
45Java Programming
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
Chapter 2
Basic Elements of Java
47Java Programming
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
48Java Programming
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
49Java Programming
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
50Java Programming
Introduction
• Computer program: a sequence of
statements whose objective is to accomplish
a task
• Programming: process of planning and
creating a program
51Java Programming
A Java Program
Sample Run:
52Java Programming: From Problem Analysis to Program Design, 4e
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
52Java Programming
53Java Programming
Special Symbols
54Java Programming
Reserved Words (Keywords)
• int
• float
• double
• char
• void
• public
• static
• throws
• return
55Java Programming
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
56Java Programming
Illegal Identifiers
57Java Programming
Data Types
• Data type: set of values together with a set
of operations
58Java Programming
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
59Java Programming
Integral Data Types
•char
•byte
•short
•int
•long
60Java Programming
Values and Memory Allocation
for Integral Data Types
61Java Programming
Primitive Data Types
• Floating-point data types
– float: precision = 6 or 7
– double: precision = 15
• boolean: two values
– true
– false
62Java Programming: From Problem Analysis to Program Design, 4e
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'
62Java Programming
63Java Programming
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
64Java Programming
Order of Precedence
1. * / % (same precedence)
2. + - (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
65Java Programming
Expressions
• Integral expressions
• Floating-point or decimal expressions
• Mixed expressions
66Java Programming
Integral Expressions
• All operands are integers
• Examples
2 + 3 * 5
3 + x – y / 7
x + 2 * (y – z) + 18
67Java Programming
Floating-Point Expressions
• All operands are floating-point numbers
• Examples
12.8 * 17.5 – 34.50
x * 10.5 + y - 16.2
68Java Programming
Mixed Expressions
• Operands of different types
• Examples
2 + 3.5
6 / 4 + 3.9
• Integer operands yield an integer result; floating-point numbers yield floating-point results
• If both types of operands are present, the result is a floating-point number
• Precedence rules are followed
69Java Programming
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
70Java Programming
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
71Java Programming
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";
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 intvariables, num1 + num2 = 12 + 26 = 38
– After this statement executes, the string assigned to str is:
"The sum = 38";
Java Programming 72
73Java Programming
Input
• Named constant
– Cannot be changed during program execution
– Declared by using the reserved word final
– Initialized when it is declared
• Example 2-11final double CENTIMETERS_PER_INCH = 2.54;
final int NO_OF_STUDENTS = 20;
final char BLANK = ' ';
final double PAY_RATE = 15.75;
74Java 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 double amountDue;
int counter;
char ch;
int num1, num2;
75Java 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.";
76Java Programming: From Problem Analysis to Program Design, 4e
Input (continued)
• Example 2-14
1. num1 = 18;
2. num1 = num1 + 27;
3. num2 = num1;
4. num3 = num2 / 5;
5. num3 = num3 / 4;
76Java Programming
77Java Programming: From Problem Analysis to Program Design, 4e
Input (continued)
77Java Programming
78Java Programming: From Problem Analysis to Program Design, 4e
Input (continued)
78Java Programming
79Java Programming
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
80Java Programming
Input (continued)static Scanner console = new Scanner(System.in);
• Example 2-16static Scanner console = new Scanner(System.in);
int feet;
int inches;
Suppose the input is
23 7
feet = console.nextInt(); //Line 1
inches = console.nextInt(); //Line 2
81Java Programming
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--
82Java Programming
Output
• Standard output object: System.out
• Methodsprint
println
• Syntax
System.out.print(stringExp);
System.out.println(stringExp);
System.out.println();
83Java Programming
Commonly Used Escape Sequences
84Java Programming
Packages, Classes, Methods, and
the import Statement
• Package: collection of related classes
• Class: consists of methods
• Method: designed to accomplish a specific
task
85Java Programming
import Statement
• Used to import the components of a package into a program
• Reserved word
• import java.io.*;
– Imports the (components of the) packagejava.io into the program
• Primitive data types and the classString
– Part of the Java language
– Don’t need to be imported
86Java Programming
Creating a Java Application
Program
• Syntax of a class
• Syntax of the main method
87Java Programming
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
88Java Programming
More on Assignment Statements
variable = variable * (expression);
is equivalent to
variable *= expression;
Similarly,
variable = variable + (expression);
is equivalent to
variable += expression;
89Java Programming
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
90Java Programming
Chapter Summary
• Basic Elements of a Java program include:
– The main method
– Reserved words
– Special symbols
– Identifiers
– Data types
– Expressions
– Input
– Output
– Statements
91Java 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
Chapter 3
Introduction to Objects and
Input/Output
93Java Programming
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
94Java Programming
Chapter Objectives (continued)
• Explore how to format the output of decimal numbers with the String method
format
• Become familiar with file input and output
95Java Programming
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
96Java Programming
int x; //Line 1
String str; //Line 2
x = 45; //Line 3
str = "Java Programming"; //Line 4
Object and Reference Variables
(continued)
97Java Programming: From Problem Analysis to Program Design, 4e
Object and Reference Variables
(continued)
97Java Programming
98Java Programming
Object and Reference Variables
(continued)
Object and Reference Variables
(continued)
Java Programming 99
100Java Programming
• 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
Objects and Reference Variables
(continued)
101Java Programming
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
102Java Programming
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
103Java Programming
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
104Java Programming
The class String
• String variables are reference variables
• Given:
String name;
– Similar Statements
name = new String("Lisa Johnson");
name = "Lisa Johnson";
105Java Programming
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
106Java Programming: From Problem Analysis to Program Design, 4e
The class String
(continued)
sentence = "Programming with Java";
106Java Programming
107Java Programming
Some Commonly Used String
Methods
108Java Programming
Some Commonly Used String
Methods (continued)
109Java Programming
Some Commonly Used String
Methods (continued)
110Java Programming
Some Commonly Used String
Methods (continued)
111Java Programming: From Problem Analysis to Program Design, 4e
Some Commonly Used String
Methods (continued)
111Java Programming
112Java Programming
Input/Output
• Input data
• Format output
• Output results
• Format output
• Read from and write to files
113Java Programming
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
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
115Java Programming
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
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
118Java Programming
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
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
120Java Programming
Formatting Output with printf
(continued)
121Java Programming
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
122Java Programming
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
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
124Java Programming
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
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
126Java Programming
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);
127Java Programming
Parameters for the Method
showMessageDialog
128Java Programming
JOptionPane Options for the
Parameter messageType
129Java Programming
JOptionPane Example
130Java Programming
Formatting the Output Using the
String Method format
Example 3-12double x = 15.674;
double y = 235.73;
double z = 9525.9864;
int num = 83;
String str;
131Java Programming
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
132Java Programming
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"));
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
134Java Programming
File Input/Output (continued)
135Java Programming
File Input/Output (continued)
• Java file I/O process
1. Import necessary classes from the packages java.util and java.io into the program
2. Create and associate appropriate objects with the
input/output sources
3. Use the appropriate methods associated with the
variables created in Step 2 to input/output data
4. Close the files
136Java Programming
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(); //close the input file
File Input/Output (continued)
137Java Programming
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 fileprog.out
Storing (Writing) Output to a File
(continued)
• Consider the following statement:PrintWriter outFile = newPrintWriter("prog.out");
• This statement creates the PrintWriterobject outFile and associates it with the file prog.out
• You can now use the methods print, println, and printf with outFilejust the same way they have been used with the object System.out
Java Programming 138
139Java Programming
Storing (Writing) Output to a File
(continued)
• The statement:
outFile.println("The paycheck is: $" + pay);
stores the output—The paycheck is: $565.78—in the file prog.out-This statement assumes that the value of the variable pay is 565.78
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
141Java Programming
• 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
throws Clause
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 exceptionJava Programming 142
143Java Programming
Skeleton of I/O Program
144Java Programming
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:
145Java Programming
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
146Java Programming
Programming Example:
Student Grade
• Input: file containing student’s first name,
last name, five test scores
• Output: file containing student’s first name,
last name, five test scores, average of five
test scores
147Java Programming
Programming Example:
Student Grade (continued)
• Import appropriate packages
• Get input from file using the classesScanner and FileReader
• Read and calculate the average of test scores
• Write to output file using the classPrintWriter
• Close files
148Java Programming
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
149Java Programming
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
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 Stringmethod format
Java Programming 150
Java Programming
Chapter 4
Control Structures I: Selection
152Java Programming
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, if…else, and switch in
a program
153Java Programming
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)
154Java Programming
Flow of Execution
155Java Programming
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
156Java Programming
Relational Operators in Java
157Java Programming
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
158Java Programming: From Problem Analysis to Program Design, 4e 158Java Programming
159Java Programming: From Problem Analysis to Program Design, 4e 159Java Programming
160Java Programming
Relational Operators and the
Unicode Collating Sequence
161Java Programming
Logical (Boolean) Operators
162Java Programming
Logical (Boolean) Operators
(continued)
163Java Programming
Logical (Boolean) Operators
(continued)
164Java Programming
Logical (Boolean) Operators
(continued)
165Java Programming
Precedence of Operators
166Java Programming: From Problem Analysis to Program Design, 4e
Precedence of Operators
(continued)
166Java Programming
167Java Programming
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
168Java Programming
Selection
• One-way selection
• Two-way selection
• Compound (block of) statements
• Multiple selections (nested if)
• Conditional operator
• switch structures
169Java Programming
One-Way Selection
• Syntaxif (expression)
statement
• Expression referred to as decision maker
• Statement referred to as action statement
One-Way Selection (continued)
Java Programming 170
171Java Programming
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
One-Way Selection (continued)
172Java Programming
if (number < 0) //Line 4
number = -number; //Line 5
JOptionPane.showMessageDialog(null,
"The absolute value of " + temp
+ " is " + number,
"Absolute Value",
JOptionPane.INFORMATION_MESSAGE); //Line 6
System.exit(0);
}
One-Way Selection (continued)
173Java Programming
Two-Way Selection
• Syntax
if (expression)
statement1
else
statement2
• else statement must be paired with an if
174Java Programming
Two-Way Selection (continued)
175Java Programming
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;
176Java Programming
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
Two-Way Selection (continued)
177Java Programming
Compound (Block of) Statements
• Syntax
178Java Programming
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.");
}
179Java Programming
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
if…else statements
• May take longer to
evaluate
180Java 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
181Java Programming
switch Structures
182Java Programming: From Problem Analysis to Program Design, 4e
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
182Java Programming
switch Structures (continued)
Java Programming: From Problem Analysis to Program Design, 4e 183
• 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
183Java Programming
switch Structures (continued)
Java Programming: From Problem Analysis to Program Design, 4e 184
• The break statement may or may not appear
after each statements1, statements2, ...,
statementsn
• A switch structure may or may not have the
default label
184Java Programming
185Java Programming
switch Structures (continued)
186Java Programming
switch Structures (continued)
187Java Programming
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;
switch Structures (continued)
188Java Programming
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.");
}
switch Structures (continued)
189Java Programming
Programming Example:
Cable Company Billing
• Input: customer’s account number,
customer code, number of premium
channels to which customer subscribes,
number of basic service connections (in
case of business customers)
• Output: customer’s account number and the
billing amount
190Java Programming
Programming Example:
Cable Company Billing (continued)
• Solution
– Prompt user for information
– Use switch statements based on customer’s type
– Use an if statement nested within a switch
statement to determine amount due by each
customer
191Java Programming
Comparing Strings
• class String
– Method compareTo
– Method equals
• Given string str1 and str2
str2str1 0
str2str1 0
str2str1 0
reTo(str2)str1.compa
string ifinteger an
string toequal is string if
string ifinteger an
192Java Programming
Comparing Strings (continued)String str1 = "Hello";
String str2 = "Hi";
String str3 = "Air";
String str4 = "Bill";
String str5 = "Bigger";
193Java Programming
Comparing Strings (continued)
194Java Programming
Comparing Strings (continued)
195Java Programming
Chapter Summary
• Control structures are used to process programs
• Logical expressions and order of precedence of
operators are used in expressions
• If statements
• if…else statements
• switch structures
• Proper syntax for using control statements
• Compare strings
Java Programming
Chapter 5
Control Structures II: Repetition
197Java Programming
Chapter Objectives
• Learn about repetition (looping) control structures
• Explore how to construct and use count-
controlled, sentinel-controlled, flag-controlled,
and EOF-controlled repetition structures
• Examine break and continue statements
• Discover how to form and use nested control
structures
198Java Programming
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
199Java Programming
The while Looping (Repetition)
Structure
• Syntaxwhile (expression)
statement
• Expression is always true in an infinite loop
• Statements must change value of expression to
false
200Java Programming
The while Looping (Repetition)
Structure (continued)
201Java Programming
The while Looping (Repetition)
Structure (continued)
Example 5-1
i = 0; //Line 1
while (i <= 20) //Line 2
{
System.out.print(i + " "); //Line 3
i = i + 5; //Line 4
}
System.out.println(); //Line 5
Output:
0 5 10 15 20
202Java Programming
The while Looping (Repetition)
Structure (continued)
• Typically, while loops are written in the
following form:
203Java Programming
Counter-Controlled while Loop
• Used when exact number of data or entry pieces is known
• General form:
204Java Programming
Sentinel-Controlled while Loop
• Used when exact number of entry pieces is unknown but last entry (special/sentinel value) is known
• General form:
205Java Programming
Flag-Controlled while Loop
• Boolean value used to control loop
• General form:
206Java Programming
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 classScanner, returns true if there is an input in the input stream; otherwise it returns false
207Java Programming
EOF (End of File)-Controlled
while Loop (continued)• 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:
208Java Programming
EOF (End of File)-Controlled
while Loop (continued)
• Suppose that inFile is a Scanner object initialized to the input file; in this case, the EOF-controlled while loop takes the following form:
209Java Programming: From Problem Analysis to Program Design, 4e 209Java Programming
210Java Programming
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
211Java Programming
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
212Java Programming
The for Looping (Repetition)
Structure
• Specialized form of while loop
• Simplifies the writing of count-controlled loops
• Syntaxfor (initial expression; logical expression;
update expression)
statement
213Java Programming
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
214Java Programming
The for Looping (Repetition)
Structure (continued)
215Java Programming
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();
216Java Programming
The for Looping (Repetition)
Structure (continued)Example 5-101. 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
217Java Programming
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
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: From Problem Analysis to Program Design, 4e 219219Java Programming
220Java Programming
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
221Java Programming
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
222Java Programming: From Problem Analysis to Program Design, 4e
Programming Example: Classify
Numbers (Solution) (continued)
• The switch statement in Step 3c can also be written
as an if...else statement as follows:
222Java Programming
223Java Programming
The do…while 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
224Java Programming
do…while Loop (Post-test Loop)
225Java Programming: From Problem Analysis to Program Design, 4e
do…while Loop (Post-test Loop)
225Java Programming
226Java Programming: From Problem Analysis to Program Design, 4e
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
226Java Programming
227Java Programming
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
228Java Programming
continue Statements
• Used in while, for, and do...whilestructures
• 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/do…whilestructure, expression evaluated immediately after continue statement
• In a for structure, the update expression is executed after the continue statement; then the loop condition executes
229Java Programming
Nested Control Structure
• Provides new power, subtlety, and
complexity
• if, if…else, and switch structures can
be placed within while loops
• for loops can be found within other for
loops
230Java Programming
Nested Control Structure (Example)
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
System.out.print(" *");
System.out.println();
}
• Output:*
**
***
****
*****
231Java Programming
Chapter Summary
• Looping Mechanisms– Counter-controlled while loop
– Sentinel-controlled while loop
– Flag-controlled while loop
– EOF-controlled while loop
– for loop
– do…while loop
• break statements
• continue statements
• Nested control structures
Java Programming
Chapter 6
Graphical User Interface (GUI)
and Object-Oriented Design (OOD)
233Java Programming
Chapter Objectives
• Learn about basic GUI components
• Explore how the GUI components
JFrame, JLabel, JTextField, and
JButton work
• Become familiar with the concept of event-
driven programming
234Java Programming
Chapter Objectives (continued)
• Discover events and event handlers
• Explore object-oriented design
• Learn how to identify objects, classes, and
members of a class
235Java Programming
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
236Java Programming
Java GUI Components
237Java Programming
Graphical User Interface (GUI)
Components (continued)
• GUI components placed in content pane
• GUI components
– Windows
– Labels
– Text areas
– Buttons
238Java Programming
GUI Components
• Added to content pane of window
• Not added to window itself
• Pixel: picture element
239Java Programming
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
240Java Programming
class JFrame
• GUI window instance created as instance of JFrame
• Provides various methods to control
window attributes
241Java Programming
Methods Provided by the class
JFrame
242Java Programming
Methods Provided by the class
Jframe (continued)
243Java Programming
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
244Java Programming
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
245Java Programming
Methods Provided by the class
Container
246Java Programming
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
247Java Programming
class Jlabel (continued)
248Java Programming
class JTextField
• Text fields: objects belonging to class
JTextField
• To create text field:
– Declare reference variable of type JTextField
– Instantiate object
249Java Programming
class JTextField
(continued)
250Java Programming
class JTextField (continued)
251Java Programming
class JButton
• Provided to create buttons in Java
• To create button:
– Same technique as creating JLabel and
JTextField
252Java Programming
class Jbutton (continued)
253Java Programming
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
254Java Programming
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
255Java Programming
Rectangle Program: Sample Run
256Java Programming
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
257Java Programming
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
258Java Programming
Sample Run for TempConversion
259Java Programming
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
260Java Programming
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
261Java Programming
class Rectangle with Data
Members and Operations
262Java Programming
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
263Java Programming
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
264Java Programming
Object-Oriented Design
Example 2 (continued)
265Java Programming
Object-Oriented Design
Example 2 (continued)
266Java Programming
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)
267Java Programming
The class Integer
268Java Programming
The class Integer (continued)
269Java Programming
The class Integer (continued)
270Java Programming
The class Integer (continued)
Integer num;
num = new Integer(86)
271Java Programming
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
272Java Programming
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
273Java Programming
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
274Java Programming
The class Integer (continued)
275Java Programming
The class Integer (continued)
276Java Programming
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
277Java Programming
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
Chapter 7
User-Defined Methods
279Java Programming
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
280Java Programming
Chapter Objectives (continued)
• Explore how to construct and use a value-
returning, 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
281Java Programming
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
282Java Programming
Predefined Classes (continued)
283Java Programming
Predefined Classes (continued)
284Java Programming
Predefined Classes (continued)
285Java Programming
Predefined Classes (continued)
286Java Programming
class Character
(Package: java.lang)
287Java Programming
class Character
(Package: java.lang) (continued)
288Java Programming
class Character
(Package: java.lang) (continued)
289Java Programming
Syntax: Value-Returning Method
290Java Programming
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
291Java Programming
Syntax
• Syntax: formal parameter list
-The syntax of the formal parameter list is:
• Method call
-The syntax to call a value-returning method is:
292Java Programming
Syntax (continued)
• Syntax: return statement
-The return statement has the following syntax:
return expr;
• Syntax: actual parameter list
-The syntax of the actual parameter list is:
293Java Programming
Equivalent Method Definitions
public static double larger(double x, double y)
{
double max;
if (x >= y)
max = x;
else
max = y;
return max;
}
294Java Programming: From Problem Analysis to Program Design, 4e 294Java Programming
295Java Programming: From Problem Analysis to Program Design, 4e 295Java Programming
296Java Programming
Equivalent Method Definitions
(continued)
public static double larger(double x, double y)
{
if (x >= y)
return x;
else
return y;
}
297Java Programming
Equivalent Method Definitions
(continued)
public static double larger(double x, double y)
{
if (x >= y)
return x;
return y;
}
298Java Programming: From Problem Analysis to Program Design, 4e
The int variable num contains the desired sum to be rolled
298Java Programming
299Java Programming
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
300Java Programming
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;
}
301Java Programming
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
302Java Programming
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
303Java Programming
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);
}
304Java Programming
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
305Java Programming
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
306Java Programming
Void Methods with Parameters: Syntax
307Java Programming
Void Methods with Parameters:
Syntax (continued)
308Java Programming
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
309Java Programming
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
310Java Programming
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
311Java Programming
Reference Variables as Parameters:
type String
312Java Programming
Reference Variables as Parameters:
type String (continued)
313Java Programming
Reference Variables as Parameters:
type String (continued)
314Java Programming
Reference Variables as Parameters:
type String (continued)
315Java Programming: From Problem Analysis to Program Design, 4e
Reference Variables as Parameters:
type String (continued)String str = "Hello"; //Line 5
315Java Programming
316Java Programming: From Problem Analysis to Program Design, 4e
Reference Variables as Parameters:
type String (continued)
stringParameter(str); //Line 7
316Java Programming
317Java Programming: From Problem Analysis to Program Design, 4e
Reference Variables as Parameters:
type String (continued)
pStr = "Sunny Day"; //Line 14
317Java Programming
318Java Programming
Reference Variables as Parameters:
type String (continued)
Variables before the statement in Line 8 executes
319Java Programming
• 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
320Java Programming: From Problem Analysis to Program Design, 4e 320Java Programming
321Java Programming: From Problem Analysis to Program Design, 4e 321Java Programming
322Java Programming: From Problem Analysis to Program Design, 4e 322Java Programming
323Java Programming: From Problem Analysis to Program Design, 4e 323Java Programming
324Java Programming: From Problem Analysis to Program Design, 4e 324Java Programming
325Java Programming
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
326Java Programming: From Problem Analysis to Program Design, 4e
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 program326Java Programming
327Java Programming
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
Scope of an Identifier within a
Class (continued)
• A method’s 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
330Java Programming
Scope of an Identifier within a
Class (continued)
public static void illegalIdentifierDeclaration()
{
int x;
//block
{
double x; //illegal declaration,
//x is already declared
...
}
}
331Java Programming
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
Scope Rules (continued)
• Suppose X is an identifier declared within a class and outside of every method’s 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
333Java Programming
Example 7-11public 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)
{
//...
}
Scope Rules (continued)
334Java Programming
public static int w;
public static void two(int one, int z)
{
char ch;
int a;
//block three
{
int x = 12;
//...
} //end block three
//...
}
}
Scope Rules (continued)
335Java Programming
Scope Rules: Demonstrated
336Java Programming
Scope Rules: Demonstrated (continued)
337Java Programming
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
338Java Programming
Method Overloading
public void methodOne(int x)
public void methodTwo(int x, double y)
public void methodThree(double y, int x)
public 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
339Java Programming
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
340Java Programming
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
341Java Programming
Method Overloading (continued)
• The following method headings correctly overload the method methodXYZ:
public void methodXYZ()
public void methodXYZ(int x, double y)
public void methodXYZ(double one, int y)
public void methodXYZ(int x, double y,
char ch)
342Java Programming
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
343Java Programming
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
344Java Programming
Sample Output
Course No Group No Course Average
CSC 1 83.71
2 80.82
ENG 1 82.00
2 78.20
HIS 1 77.69
2 84.15
MTH 1 83.57
2 84.29
PHY 1 83.22
2 82.60
Avg for group 1: 82.04
Avg for group 2: 82.01
Programming Example: Data
Comparison (continued)
345Java Programming
Programming Example: Data
Comparison (continued)
346Java Programming
Chapter Summary
• Predefined methods
• User-defined methods
– Value-returning methods
– Void methods
– Formal parameters
– Actual parameters
• Flow of Execution
347Java Programming
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
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: From Problem Analysis to Program Design, 4e 349Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 350Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 351Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 352Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 353Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 354Java Programming
Java Programming: From Problem Analysis to Program Design, 4e
Sample Run: In this sample run, the user input is shadedLine 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
355Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 356Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 357Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 358Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 359Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 360Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 361Java Programming
Java Programming: From Problem Analysis to Program Design, 4e
num1 = 10; //Line 5
362Java Programming
Java Programming: From Problem Analysis to Program Design, 4e
num1 = 10; //Line 5
num2.setNum(15); //Line 6
ch = 'A'; //Line 7
str = new StringBuffer("Sunny"); //Line 8
363Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 364Java Programming
Java Programming: From Problem Analysis to Program Design, 4e
num = b.getNum(); //Line 14
365Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 366Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 367Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 368Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 369Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 370Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 371Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 372Java Programming
Java Programming: From Problem Analysis to Program Design, 4e 373Java Programming
Java Programming
Chapter 8
User-Defined Classes and ADTs
Java Programming 375
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 376
Chapter Objectives (continued)
• Examine constructors and finalizers
• Examine the method toString
• Learn about the abstract data type (ADT)
Java Programming 377
Classesfinal class String
{
//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 378
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 379
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 380
Syntax
The general syntax for defining a class is:
Java Programming 381
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 382
Syntax (continued)
• If a member of a class is a method, it can
(directly) access any member of the class—data
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 383
Data Members (Instance Variables)•private int hr; //store hours
•private int min; //store minutes
•private int sec; //store seconds
class Clock:
Java Programming 384
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 385
• Two types of constructors- With parameters
- Without parameters (default constructor)
Constructors
Java Programming 386
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 387
• Default constructor is:- public Clock()
• Constructor with parameters is:- public Clock(int hours, int
minutes, int seconds)
class Clock: Constructors
Java Programming 388
Unified Modeling Language Class
Diagrams
Java Programming 389
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 390
Variable Declaration and Object
Instantiation (continued)
Java Programming 391
Variable Declaration and Object
Instantiation (continued)
Java Programming 392
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 393
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 394
• 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
Assignment Operator: A Precaution (continued)
Java Programming 395
Assignment Operator: A Precaution
(continued)
Java Programming 396
Definitions of the Constructors and
Methods of the class Clock
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
Definitions of the Constructors and
Methods of the class Clock (continued)
Java Programming 408
Default Constructor
or
Java Programming 409
Constructor with Parameters
or
Java Programming 410
• public value-returning method
• Takes no parameters
• Returns address of a String object
• Output using print, println, printfmethods
• Default definition creates String with name of object’s class name followed by hash code of object
The Method toString
Java Programming 411
Method toString: class Clock
Java Programming 412
The Copy Constructor
• Executes when an object is instantiated
• Initialized using an existing object
• Syntax
Java Programming 413
The Copy Constructor
(continued)
Java Programming 414
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 415
• 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;
}
Static Members of a Class
Java Programming 416
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++;
Static Members of a Class
(continued)
Java Programming 417
Illustrate illusObject1 = new Illustrate(3);
Illustrate illusObject2 = new Illustrate(5);
Static Members of a Class
(continued)
Java Programming 418
Illustrate.incrementY();
Illustrate.count++;
Static Members of a Class
(continued)
Java Programming 419
Finalizers
• Automatically execute when class object
goes out of scope
• Have no parameters
• Only one finalizer per class
• Name of finalizer: finalize
Java Programming 420
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 421
The Reference this
• Refers to instance variables and methods of
a class
• Used to implement cascaded method calls
Java Programming 422
Inner Classes
• Defined within other classes
• Can be either a complete class definition or
anonymous inner class definition
• Used to handle events
Java Programming 423
Abstract Data Types
• Definition
- A data type that specifies the logical
properties without the implementation details
Java Programming 424
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 425
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 426
Programming Example: Candy
Machine (Input and Output)
• Input: the item selection and the cost of the
item
• Output: the selected item
Java Programming 427
Programming Example:
Candy Machine
• Components
– Cash Register
– Dispenser
– Machine
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
Programming Example:
Candy Machine (continued)
Java Programming 434
Chapter Summary
• Creating classes
• Members of a class– private
– protected
– public
– static
• Implementing classes
• Various operations on classes
Java Programming 435
Chapter Summary (continued)
• Constructors
• Finalizers
• Method toString
• Abstract Data Types
Java Programming
Chapter 9
Arrays
Java Programming 437
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 438
Chapter Objectives (continued)
• Discover how to pass an array as a
parameter to a method
• Discover how to manipulate data in a two-
dimensional array
• Learn about multidimensional arrays
Java Programming 439
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 440
One-Dimensional Arrays
Java Programming 441
One-Dimensional Arrays
(continued)
Java Programming 442
One-Dimensional Arrays
(continued)
•intExp = number of components in array >= 0
•0 <= indexExp <= intExp
Java Programming 443
• Array num:int[] num = new int[5];
Arrays
Java Programming 444
• Array num:int[] num = new int[5];
Arrays (continued)
Java Programming 445
Array List
Java Programming 446
Array List (continued)
Java Programming 447
Array List (continued)
Java Programming 448
Array List (continued)
Java Programming 449
Specifying Array Size During Program Execution
Java Programming 450
• 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
Array Initialization During Declaration
Java Programming 451
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 452
• 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 aprogram using the array name and the dot operator
int[] list = {10, 20, 30, 40, 50, 60};
Arrays and the Instance Variable
length
Java Programming 453
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 numListof 10 components and initializes each component to 0
Java Programming 454
• The value of numList.length is 10numList[0] = 5;
numList[1] = 10;
numList[2] = 15;
numList[3] = 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
Arrays and the Instance Variable
length (continued)
Java Programming 455
• 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] + " ");
Processing One-Dimensional
Arrays
Java Programming 456
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 457
Code to Initialize Array to
Specific Value (10.00)
for (int index = 0; index < sales.length;
index++)
sales[index] = 10.00;
Java Programming 458
Code to Read Data into Array
for (int index = 0; index < sales.length;
index++)
sales[index] = console.nextDouble();
Java Programming 459
Code to Print Array
for (int index = 0; index < sales.length;
index++)
System.out.print(sales[index] + " ");
Java Programming 460
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 461
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 462
Determining Largest Element in
Array (continued)
Java Programming 463
Determining Largest Element in Array (continued)
Java Programming 464
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 465
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 466
The Assignment Operators and
Arrays
Java Programming 467
The Assignment Operators and
Arrays (continued)
Java Programming 468
The Assignment Operators and
Arrays (continued)
Java Programming 469
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 470
Relational Operators and Arrays
(continued)boolean areEqualArrays(int[] firstArray,
int[] secondArray)
{
if (firstArray.length != secondArray.length)
return false;
for (int index = 0; index < firstArray.length;
index++)
if (firstArray[index] != secondArray[index])
return false;
return true;
}
if (areEqualArrays(listA, listB))
...
Java Programming 471
Arrays as Parameter Methods
Java Programming 472
Methods for Array Processing
Java Programming 473
Methods for Array Processing (continued)
Java Programming 474
Methods for Array Processing
(continued)
Java Programming 475
Methods for Array Processing
(continued)
Java Programming 476
• 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 477
• Search for 10
• Search starts at the first element in the list, that is, atlist[0]
• This time, the search item, which is 10, is compared withevery item in the list; eventually, no more data is left in thelist to compare with the search item; this is an unsuccessfulsearch
Java Programming 478
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 479
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 480
Array of String Objects
String[] nameList = new String[5];
nameList[0] = "Amanda Green";
nameList[1] = "Vijay Arora";
nameList[2] = "Sheila Mann";
nameList[3] = "Rohit Sharma";
nameList[4] = "Mandy Johnson";
Java Programming 481
Array of String Objects
(continued)
Java Programming 482
Clock[] arrivalTimeEmp = new Clock[100];
Arrays of Objects (continued)
Java Programming 483
Instantiating Array Objectsfor (int j = 0; j < arrivalTimeEmp.length; j++)
arrivalTimeEmp[j] = new Clock();
Java Programming 484
arrivalTimeEmp[49].setTime(8, 5, 10);
Instantiating Array Objects (continued)
Java Programming 485
Arrays and Variable Length
Parameter List
• The syntax to declare a variable length formal
parameter (list) is:
dataType ... identifier
Java Programming 486
Arrays and Variable Length Parameter List
(continued)
Java Programming 487
Arrays and Variable Length
Parameter List (continued)
Java Programming 488
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 489
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 490
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 491
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 492
Two-Dimensional Arrays
Java Programming 493
Two-Dimensional Arrays
(continued)
Java Programming 494
double[][] sales = new double[10][5];
Two-Dimensional Arrays (continued)
Java Programming 495
• intExp1, intExp2 >= 0
• indexExp1 = row position
• indexExp2 = column position
Accessing Array Elements
Java Programming 496
Accessing Array Elements
(continued)
Java Programming 497
• This statement declares and instantiates a two-
dimensional array matrix of 20 rows and 15
columns• The value of the expression:
matrix.length
is 20, the number of rows
Two-Dimensional Arrays and the
Instance Variable length
Java Programming 498
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 499
Two-Dimensional Arrays:
Special Cases
Java Programming 500
•Create columns
Two-Dimensional Arrays: Special
Cases (continued)
Java Programming 501
Two-Dimensional Array
Initialization During
Declaration
Java Programming 502
• 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
Two-Dimensional Array Initialization
During Declaration (continued)
Java Programming 503
Two-Dimensional Array
Initialization During Declaration
(continued)
Java Programming 504
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 505
Two-Dimensional Arrays:
ProcessingInitialization
for (int row = 0; row < matrix.length; row++)
for (int col = 0; col < matrix[row].length;
col++)
matrix[row][col] = 10;
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 506
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);
}
Two-Dimensional Arrays:
Processing (continued)
Java Programming 507
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);
}
Two-Dimensional Arrays:
Processing (continued)
Java Programming 508
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);
}
Two-Dimensional Arrays:
Processing (continued)
Java Programming 509
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);
}
Two-Dimensional Arrays:
Processing (continued)
Java Programming 510
Java Programming 511
Java Programming 512
Java Programming 513
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 514
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 515
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 516
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 517
Chapter Summary
• Arrays
– Definition
– Uses
• Different Arrays
– One-dimensional
– Two-dimensional
– Multidimensional (n-dimensional)
– Arrays of objects
– Parallel arrays
Java Programming 518
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
Chapter 10
Inheritance and Polymorphism
Java Programming 520
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 521
Chapter Objectives (continued)
• Learn about polymorphism
• Examine abstract classes
• Become aware of interfaces
• Learn about composition
Java Programming 522
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 523
Inheritance (continued)
modifier(s) class ClassName extends ExistingClassName
modifier(s)
{
memberList
}
Java Programming 524
Inheritance: class Circle Derived
from class Shape
public class Circle extends Shape
{
.
.
.
}
Java Programming 525
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 526
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 527
Inheritance (continued)
• To write a method’s 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 528
UML Class Diagram: class
Rectangle
Java Programming 529
UML Class Diagram: class
Box
Java Programming 530
class Boxpublic 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 531
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 532
Objects myRectangle and myBox
Rectangle myRectangle = new Rectangle(5, 3);
Box myBox = new Box(6, 5, 4);
Java Programming 533
UML Class Diagram
Java Programming 534
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 535
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 536
The class Object:
Equivalent Definition of a
Classpublic 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 537
Some Constructors and Methods
of the class Object
Java Programming 538
Hierarchy of Java Stream Classes
Java Programming 539
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 540
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 541
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 542
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 543
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 supRefpoints 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 544
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 ClassCastException—indicating that
the class cast is not allowed
Java Programming 545
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 546
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 547
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 allthe abstract methods of the superclass
Java Programming 548
Abstract Class Examplepublic abstract class AbstractClassExample
{
protected int x;
public void abstract print();
public void setX(int a)
{
x = a;
}
public AbstractClassExample()
{
x = 0;
}
}
Java Programming 549
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 550
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 551
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 552
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 553
Composition (Aggregation) Example
Java Programming 554
Composition (Aggregation) Example
(continued)
Java Programming 555
Programming Example: Grade
Report
• Components: student, course
• Operations on course
– Set course information
– Print course information
– Show credit hours
– Show course number
Java Programming 556
Components Course and Student
Java Programming 557
Components Course and Student (continued)
Java Programming 558
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
Java Programming 559
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 560
Sample Output: Grade Report Program
Java Programming 561
Chapter Summary
• Inheritance
– Single and multiple
– Rules
– Uses
– Superclasses/subclasses (objects)
– Overriding/overloading methods
– Constructors
• The class Object
Java Programming 562
Chapter Summary (continued)
• Java stream classes
• Polymorphism
• Abstract methods
• Abstract classes
• Interfaces
• Composition
Java Programming
Chapter 11
Handling Exceptions and Events
Java Programming 564
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 565
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 566
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 567
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 568
Java’s 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 classArithmeticException
Java Programming 569
Java’s Mechanism of Exception
Handling (continued)
• When a division by zero exception occurs, the program creates an object of the classArithmeticException
• When a Scanner object is used to input data into a program, any invalid input errors are handled using the classInputMismatchException
• The class Exception (directly or indirectly) is the superclass of all the exception classes in Java
Java Programming 570
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 571
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 572
try/catch/finally Block
(continued)
Java Programming 573
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 574
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 575
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 576
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 tryblock, a catch block declaring an exception of a subclass type should be placed before catchblocks declaring exceptions of a superclass type
Java Programming 577
Java Exception Hierarchy
Java Programming 578
Java Exception Hierarchy (continued)
Java Programming 579
Java Exception Hierarchy (continued)
Java Programming 580
Java Exception Hierarchy (continued)
Java Programming 581
Java Exception Hierarchy (continued)
Java Programming 582
Java’s 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 583
The class Exception and
its Constructors
Java Programming 584
Java Exception Classes
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
Java Exception Classes (continued)
Java Programming 592
Checked Exceptions
• Definition: any exception that can be
recognized by the compiler
• Examples
– FileNotFoundExceptions
Java Programming 593
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 594
Exceptions Example Code
public static void exceptionMethod()
throws InputMismatchException,
FileNotFoundException
{
//statements
}
• The method exceptionMethod throws exceptions of the type InputMismatchException and FileNotFoundException
Java Programming 595
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 596
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()); }
The class Exception and
the Operator instanceof
Java Programming 597
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 598
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 599
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());
}
}
}
Rethrowing and Throwing an
Exception (continued)
Java Programming 600
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;
}
}
}
Rethrowing and Throwing an
Exception (continued)
Java Programming 601
The Method printStackTrace
• Used to determine the order in which the
methods were called and where the
exception was handled
Java Programming 602
import java.io.*;
public class PrintStackTraceExample1
{
public static void main(String[] args)
{
try
{
methodA();
}
catch (Exception e)
{
System.out.println(e.toString()
+ " caught in main");
e.printStackTrace();
}
}
The Method printStackTrace
(continued)
Java Programming 603
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");}
}
The Method printStackTrace
(continued)
Java Programming 604
• Sample Runjava.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)
The Method printStackTrace
(continued)
Java Programming 605
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 606
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 607
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 608
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 609
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 610
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 611
Event Handling (continued)
Java Programming 612
Event Handling (continued)
Java Programming 613
Event Handling (continued)
Java Programming 614
Programming Example:
Calculator
Java Programming 615
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 Operatorinstanceof
– Rethrowing and throwing an exception
• Exception– Hierarchy
– Classes
Java Programming 616
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
Chapter 12
Advanced GUIs and Graphics
Java Programming 618
Chapter Objectives
• Learn about applets
• Explore the class Graphics
• Learn about the class Font
• Explore the class Color
Java Programming 619
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 620
Inheritance Hierarchy of GUI Classes
Java Programming 621
Constructors and Methods of the class Component
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 Component (continued)
Java Programming 625
Constructors and Methods of the
class Container
Java Programming 626
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 627
Members of class JApplet
Java Programming 628
Members of class Japplet
(continued)
Java Programming 629
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 630
Applet Methods
• init Method
– Initializes variables
– Gets data from user
– Places various GUI components
• paint Method
– Performs output
Java Programming 631
Skeleton of a Java Applet
import java.awt.Graphics;
import javax.swing.JApplet;
public class WelcomeApplet extends JApplet
{
}
Java Programming 632
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 633
HTML to Run Applet
Java Programming 634
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 635
Constructors and Methods of the class Font
Java Programming 636
Constructors and Methods of the class Font
(continued)
Java Programming 637
Constructors and Methods of the
class Font (continued)
Java Programming 638
class Color
• Shows text in different colors
• Changes background color of component
• Contained in package java.awt
Java Programming 639
Constructors of the class
Color
Java Programming 640
Constructors of the class
Color (continued)
Java Programming 641
Constants Defined in the class
Color
Java Programming 642
Constants Defined in the class
Color (continued)
Java Programming 643
Constants Defined in the class
Color (continued)
Java Programming 644
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 645
Constructors and Methods of the
class Graphics
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
Constructors and Methods of the
class Graphics
(continued)
Java Programming 653
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
• GUI applications– class extends JFrame
– Invokes main method
– Uses constructors
– Uses method setVisible
– Uses setTitle method
– Uses method setSize
– Closes with Exit button
Java Programming 654
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 655
Additional GUI Components
• JTextArea
• JCheckBox
• JRadioButton
• JComboBox
• JList
Java Programming 656
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 657
JTextArea (continued)
Java Programming 658
Methods Inherited by class
JTextArea from Parent
class JTextComponent
Java Programming 659
JTextArea Example
Java Programming 660
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 661
Constructors and Methods of class JCheckBox
Java Programming 662
Constructors and Methods of
class JCheckBox (continued)
Java Programming 663
Constructors and Methods of
class JCheckBox (continued)
Java Programming 664
Constructors and Methods of
class JCheckBox (continued)
Java Programming 665
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 666
JRadioButton (continued)
Java Programming 667
JRadioButton (continued)
Java Programming 668
JRadioButton (continued)
Java Programming 669
JRadioButton (continued)
Java Programming 670
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 671
Constructors of class JComboBox
Java Programming 672
Applet with JCheckBox,
JComboBox, and JRadioButton
Java Programming 673
Constructors of class JList
Java Programming 674
Constructors of class Jlist
(continued)
Java Programming 675
Constructors of class Jlist
(continued)
Java Programming 676
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 677
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 678
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 679
Key and Mouse Events
Java Programming 680
Chapter Summary
• Creating applets
• class Font
• class Graphics
• class Color
• Differences between applet and GUI
application
• Converting GUI application to applet
Java Programming 681
Chapter Summary (continued)
• GUI components
– JTextArea
– JCheckBox
– JRadioButton
• Layout managers
• Menus
• Key and mouse events
Java Programming
Chapter 13
Recursion
Java Programming 683
Chapter Objectives
• Learn about recursive definitions
• Explore the base case and the general case
of a recursive definition
• Learn about recursive algorithms
Java Programming 684
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 685
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 686
Recursive Definitions (continued)
Java Programming 687
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 688
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 689
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 690
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 691
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 692
Designing Recursive Methods
• Understand problem requirements
• Determine limiting conditions
• Identify base cases
Java Programming 693
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 694
Recursive Factorial Method
public static int fact(int num)
{
if (num = = 0)
return 1;
else
return num * fact(num – 1);
}
Java Programming 695
Recursive Factorial Method (continued)
Java Programming 696
Largest Value in Array
Java Programming 697
• 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
Largest Value in Array (continued)
Java Programming 698
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;
}
}
Largest Value in Array (continued)
Java Programming 699
Execution of largest
(list, 0, 3)
Java Programming 700
Execution of largest (list, 0, 3)
Java Programming 701
Recursive Fibonacci
Java Programming 702
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 703
Recursive Fibonacci (continued)
Java Programming 704
Towers of Hanoi Problem with
Three Disks
Java Programming 705
Towers of Hanoi: Three Disk
Solution
Java Programming 706
Towers of Hanoi: Three Disk Solution
(continued)
Java Programming 707
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 708
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 709
Programming Example:
Decimal to Binary
Java Programming 710
Java Programming 711
Sierpinski Gaskets of Various Orders
Java Programming 712
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 713
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);
}
}
Programming Example:
Sierpinski Gasket (continued)
Java Programming 714
Programming Example: Sierpinski
Gasket (continued)
Java Programming 715
Chapter Summary
• Recursive definitions
• Recursive algorithms
• Recursive methods
• Base cases
• General cases
Java Programming 716
Chapter Summary (continued)
• Tracing recursive methods
• Designing recursive methods
• Varieties of recursive methods
• Recursion vs. iteration
• Various recursive functions explored
Top Related