+ All Categories
Home > Documents > Java Introduction

Java Introduction

Date post: 01-Jan-2016
Category:
Upload: dsunte
View: 76 times
Download: 9 times
Share this document with a friend
Description:
Java Introduction. This introduction takes to all the basics of Java.
716
Java Programming
Transcript
Page 1: Java Introduction

Java Programming

Page 2: Java Introduction

Java Programming

Chapter 1An Overview of Computers and

Programming Languages

2Java Programming

Page 3: Java Introduction

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

Page 4: Java Introduction

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

Page 5: Java Introduction

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

Page 6: Java Introduction

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

Page 7: Java Introduction

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

Page 8: Java Introduction

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

Page 9: Java Introduction

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

Page 10: Java Introduction

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

Page 11: Java Introduction

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

Page 12: Java Introduction

12Java Programming

Elements of a Computer System

• A computer has two components

– Hardware

– Software

Page 13: Java Introduction

13Java Programming

Hardware Components of a

Computer

• Central Processing Unit (CPU)

• Main Memory

Page 14: Java Introduction

14Java Programming

Central Processing Unit

• Arithmetic and logical operations are

carried out inside the CPU

Page 15: Java Introduction

15Java Programming

Central Processing Unit and Main

Memory

Page 16: Java Introduction

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

Page 17: Java Introduction

17Java Programming

Secondary Storage

• Provides permanent storage for information

• Examples of secondary storage:

– Hard disks

– Floppy disks

– Flash memory

– ZIP disks

– CD-ROMs

– Tapes

Page 18: Java Introduction

18Java Programming

Input Devices

• Definition: devices that feed data and

computer programs into computers

• Examples

– Keyboard

– Mouse

– Secondary storage

Page 19: Java Introduction

19Java Programming

Output Devices

• Definition: devices that the computer uses

to display results

• Examples

– Printer

– Monitor

– Secondary storage

Page 20: Java Introduction

20Java Programming: From Problem Analysis to Program Design, 4e

Input/Output Devices

20Java Programming

Page 21: Java Introduction

21Java Programming

Software

• Software consists of programs written to

perform specific tasks

• Two types of programs

– System programs

– Application programs

Page 22: Java Introduction

22Java Programming

System Programs

• System programs control the computer

• The operating system is first to load when

you turn on a computer

Page 23: Java Introduction

23Java Programming

Operating System (OS)

• OS monitors overall activity of the

computer and provides services

• Example services

– Memory management

– Input/output

– Activities

– Storage management

Page 24: Java Introduction

24Java Programming

Application Programs

• Written using programming languages

• Perform a specific task

• Run by the OS

• Example programs

– Word processors

– Spreadsheets

– Games

Page 25: Java Introduction

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

Page 26: Java Introduction

26Java Programming

Language of a Computer (continued)

Page 27: Java Introduction

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

Page 28: Java Introduction

28Java Programming

Instructions in Assembly and

Machine Language

Page 29: Java Introduction

29Java Programming

Evolution of Programming

Languages

• High-level languages make programming easier

• Closer to spoken languages

• Examples

– Basic

– FORTRAN

– COBOL

– C/C++

– Java

Page 30: Java Introduction

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

Page 31: Java Introduction

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

Page 32: Java Introduction

32Java Programming

A Java Program

Output:

Page 33: Java Introduction

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

Page 34: Java Introduction

34Java Programming

Processing a Java Program (continued)

Page 35: Java Introduction

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

Page 36: Java Introduction

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

Page 37: Java Introduction

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

Page 38: Java Introduction

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

Page 39: Java Introduction

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

Page 40: Java Introduction

40Java Programming

Problem-Analysis-Coding-

Execution Cycle (continued)

Page 41: Java Introduction

41Java Programming

Programming Methodologies

• Two basic approaches to programming

design

– Structured design

– Object-oriented design

Page 42: Java Introduction

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

Page 43: Java Introduction

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

Page 44: Java Introduction

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

Page 45: Java Introduction

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

Page 46: Java Introduction

Java Programming

Chapter 2

Basic Elements of Java

Page 47: Java Introduction

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

Page 48: Java Introduction

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

Page 49: Java Introduction

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

Page 50: Java Introduction

50Java Programming

Introduction

• Computer program: a sequence of

statements whose objective is to accomplish

a task

• Programming: process of planning and

creating a program

Page 51: Java Introduction

51Java Programming

A Java Program

Sample Run:

Page 52: Java Introduction

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

Page 53: Java Introduction

53Java Programming

Special Symbols

Page 54: Java Introduction

54Java Programming

Reserved Words (Keywords)

• int

• float

• double

• char

• void

• public

• static

• throws

• return

Page 55: Java Introduction

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

Page 56: Java Introduction

56Java Programming

Illegal Identifiers

Page 57: Java Introduction

57Java Programming

Data Types

• Data type: set of values together with a set

of operations

Page 58: Java Introduction

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

Page 59: Java Introduction

59Java Programming

Integral Data Types

•char

•byte

•short

•int

•long

Page 60: Java Introduction

60Java Programming

Values and Memory Allocation

for Integral Data Types

Page 61: Java Introduction

61Java Programming

Primitive Data Types

• Floating-point data types

– float: precision = 6 or 7

– double: precision = 15

• boolean: two values

– true

– false

Page 62: Java Introduction

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

Page 63: Java Introduction

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

Page 64: Java Introduction

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

Page 65: Java Introduction

65Java Programming

Expressions

• Integral expressions

• Floating-point or decimal expressions

• Mixed expressions

Page 66: Java Introduction

66Java Programming

Integral Expressions

• All operands are integers

• Examples

2 + 3 * 5

3 + x – y / 7

x + 2 * (y – z) + 18

Page 67: Java Introduction

67Java Programming

Floating-Point Expressions

• All operands are floating-point numbers

• Examples

12.8 * 17.5 – 34.50

x * 10.5 + y - 16.2

Page 68: Java Introduction

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

Page 69: Java Introduction

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

Page 70: Java Introduction

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

Page 71: Java Introduction

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";

Page 72: Java Introduction

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

Page 73: Java Introduction

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;

Page 74: Java Introduction

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;

Page 75: Java Introduction

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.";

Page 76: Java Introduction

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

Page 77: Java Introduction

77Java Programming: From Problem Analysis to Program Design, 4e

Input (continued)

77Java Programming

Page 78: Java Introduction

78Java Programming: From Problem Analysis to Program Design, 4e

Input (continued)

78Java Programming

Page 79: Java Introduction

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

Page 80: Java Introduction

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

Page 81: Java Introduction

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--

Page 82: Java Introduction

82Java Programming

Output

• Standard output object: System.out

• Methodsprint

println

• Syntax

System.out.print(stringExp);

System.out.println(stringExp);

System.out.println();

Page 83: Java Introduction

83Java Programming

Commonly Used Escape Sequences

Page 84: Java Introduction

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

Page 85: Java Introduction

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

Page 86: Java Introduction

86Java Programming

Creating a Java Application

Program

• Syntax of a class

• Syntax of the main method

Page 87: Java Introduction

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

Page 88: Java Introduction

88Java Programming

More on Assignment Statements

variable = variable * (expression);

is equivalent to

variable *= expression;

Similarly,

variable = variable + (expression);

is equivalent to

variable += expression;

Page 89: Java Introduction

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

Page 90: Java Introduction

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

Page 91: Java Introduction

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

Page 92: Java Introduction

Java Programming

Chapter 3

Introduction to Objects and

Input/Output

Page 93: Java Introduction

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

Page 94: Java Introduction

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

Page 95: Java Introduction

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

Page 96: Java Introduction

96Java Programming

int x; //Line 1

String str; //Line 2

x = 45; //Line 3

str = "Java Programming"; //Line 4

Object and Reference Variables

(continued)

Page 97: Java Introduction

97Java Programming: From Problem Analysis to Program Design, 4e

Object and Reference Variables

(continued)

97Java Programming

Page 98: Java Introduction

98Java Programming

Object and Reference Variables

(continued)

Page 99: Java Introduction

Object and Reference Variables

(continued)

Java Programming 99

Page 100: Java Introduction

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)

Page 101: Java Introduction

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

Page 102: Java Introduction

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

Page 103: Java Introduction

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

Page 104: Java Introduction

104Java Programming

The class String

• String variables are reference variables

• Given:

String name;

– Similar Statements

name = new String("Lisa Johnson");

name = "Lisa Johnson";

Page 105: Java Introduction

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

Page 106: Java Introduction

106Java Programming: From Problem Analysis to Program Design, 4e

The class String

(continued)

sentence = "Programming with Java";

106Java Programming

Page 107: Java Introduction

107Java Programming

Some Commonly Used String

Methods

Page 108: Java Introduction

108Java Programming

Some Commonly Used String

Methods (continued)

Page 109: Java Introduction

109Java Programming

Some Commonly Used String

Methods (continued)

Page 110: Java Introduction

110Java Programming

Some Commonly Used String

Methods (continued)

Page 111: Java Introduction

111Java Programming: From Problem Analysis to Program Design, 4e

Some Commonly Used String

Methods (continued)

111Java Programming

Page 112: Java Introduction

112Java Programming

Input/Output

• Input data

• Format output

• Output results

• Format output

• Read from and write to files

Page 113: Java Introduction

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

Page 114: Java Introduction

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

Page 115: Java Introduction

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

Page 116: Java Introduction

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

Page 117: Java Introduction

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

Page 118: Java Introduction

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

Page 119: Java Introduction

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

Page 120: Java Introduction

120Java Programming

Formatting Output with printf

(continued)

Page 121: Java Introduction

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

Page 122: Java Introduction

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

Page 123: Java Introduction

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

Page 124: Java Introduction

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

Page 125: Java Introduction

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

Page 126: Java Introduction

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);

Page 127: Java Introduction

127Java Programming

Parameters for the Method

showMessageDialog

Page 128: Java Introduction

128Java Programming

JOptionPane Options for the

Parameter messageType

Page 129: Java Introduction

129Java Programming

JOptionPane Example

Page 130: Java Introduction

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;

Page 131: Java Introduction

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

Page 132: Java Introduction

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"));

Page 133: Java Introduction

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

Page 134: Java Introduction

134Java Programming

File Input/Output (continued)

Page 135: Java Introduction

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

Page 136: Java Introduction

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)

Page 137: Java Introduction

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

Page 138: Java Introduction

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

Page 139: Java Introduction

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

Page 140: Java Introduction

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

Page 141: Java Introduction

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

Page 142: Java Introduction

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

Page 143: Java Introduction

143Java Programming

Skeleton of I/O Program

Page 144: Java Introduction

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:

Page 145: Java Introduction

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

Page 146: Java Introduction

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

Page 147: Java Introduction

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

Page 148: Java Introduction

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

Page 149: Java Introduction

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

Page 150: Java Introduction

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

Page 151: Java Introduction

Java Programming

Chapter 4

Control Structures I: Selection

Page 152: Java Introduction

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

Page 153: Java Introduction

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)

Page 154: Java Introduction

154Java Programming

Flow of Execution

Page 155: Java Introduction

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

Page 156: Java Introduction

156Java Programming

Relational Operators in Java

Page 157: Java Introduction

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

Page 158: Java Introduction

158Java Programming: From Problem Analysis to Program Design, 4e 158Java Programming

Page 159: Java Introduction

159Java Programming: From Problem Analysis to Program Design, 4e 159Java Programming

Page 160: Java Introduction

160Java Programming

Relational Operators and the

Unicode Collating Sequence

Page 161: Java Introduction

161Java Programming

Logical (Boolean) Operators

Page 162: Java Introduction

162Java Programming

Logical (Boolean) Operators

(continued)

Page 163: Java Introduction

163Java Programming

Logical (Boolean) Operators

(continued)

Page 164: Java Introduction

164Java Programming

Logical (Boolean) Operators

(continued)

Page 165: Java Introduction

165Java Programming

Precedence of Operators

Page 166: Java Introduction

166Java Programming: From Problem Analysis to Program Design, 4e

Precedence of Operators

(continued)

166Java Programming

Page 167: Java Introduction

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

Page 168: Java Introduction

168Java Programming

Selection

• One-way selection

• Two-way selection

• Compound (block of) statements

• Multiple selections (nested if)

• Conditional operator

• switch structures

Page 169: Java Introduction

169Java Programming

One-Way Selection

• Syntaxif (expression)

statement

• Expression referred to as decision maker

• Statement referred to as action statement

Page 170: Java Introduction

One-Way Selection (continued)

Java Programming 170

Page 171: Java Introduction

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)

Page 172: Java Introduction

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)

Page 173: Java Introduction

173Java Programming

Two-Way Selection

• Syntax

if (expression)

statement1

else

statement2

• else statement must be paired with an if

Page 174: Java Introduction

174Java Programming

Two-Way Selection (continued)

Page 175: Java Introduction

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;

Page 176: Java Introduction

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)

Page 177: Java Introduction

177Java Programming

Compound (Block of) Statements

• Syntax

Page 178: Java Introduction

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.");

}

Page 179: Java Introduction

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

Page 180: Java Introduction

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

Page 181: Java Introduction

181Java Programming

switch Structures

Page 182: Java Introduction

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

Page 183: Java Introduction

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

Page 184: Java Introduction

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

Page 185: Java Introduction

185Java Programming

switch Structures (continued)

Page 186: Java Introduction

186Java Programming

switch Structures (continued)

Page 187: Java Introduction

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)

Page 188: Java Introduction

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)

Page 189: Java Introduction

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

Page 190: Java Introduction

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

Page 191: Java Introduction

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

Page 192: Java Introduction

192Java Programming

Comparing Strings (continued)String str1 = "Hello";

String str2 = "Hi";

String str3 = "Air";

String str4 = "Bill";

String str5 = "Bigger";

Page 193: Java Introduction

193Java Programming

Comparing Strings (continued)

Page 194: Java Introduction

194Java Programming

Comparing Strings (continued)

Page 195: Java Introduction

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

Page 196: Java Introduction

Java Programming

Chapter 5

Control Structures II: Repetition

Page 197: Java Introduction

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

Page 198: Java Introduction

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

Page 199: Java Introduction

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

Page 200: Java Introduction

200Java Programming

The while Looping (Repetition)

Structure (continued)

Page 201: Java Introduction

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

Page 202: Java Introduction

202Java Programming

The while Looping (Repetition)

Structure (continued)

• Typically, while loops are written in the

following form:

Page 203: Java Introduction

203Java Programming

Counter-Controlled while Loop

• Used when exact number of data or entry pieces is known

• General form:

Page 204: Java Introduction

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:

Page 205: Java Introduction

205Java Programming

Flag-Controlled while Loop

• Boolean value used to control loop

• General form:

Page 206: Java Introduction

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

Page 207: Java Introduction

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:

Page 208: Java Introduction

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:

Page 209: Java Introduction

209Java Programming: From Problem Analysis to Program Design, 4e 209Java Programming

Page 210: Java Introduction

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

Page 211: Java Introduction

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

Page 212: Java Introduction

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

Page 213: Java Introduction

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

Page 214: Java Introduction

214Java Programming

The for Looping (Repetition)

Structure (continued)

Page 215: Java Introduction

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();

Page 216: Java Introduction

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

Page 217: Java Introduction

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

Page 218: Java Introduction

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

Page 219: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 219219Java Programming

Page 220: Java Introduction

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

Page 221: Java Introduction

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

Page 222: Java Introduction

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

Page 223: Java Introduction

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

Page 224: Java Introduction

224Java Programming

do…while Loop (Post-test Loop)

Page 225: Java Introduction

225Java Programming: From Problem Analysis to Program Design, 4e

do…while Loop (Post-test Loop)

225Java Programming

Page 226: Java Introduction

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

Page 227: Java Introduction

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

Page 228: Java Introduction

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

Page 229: Java Introduction

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

Page 230: Java Introduction

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:*

**

***

****

*****

Page 231: Java Introduction

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

Page 232: Java Introduction

Java Programming

Chapter 6

Graphical User Interface (GUI)

and Object-Oriented Design (OOD)

Page 233: Java Introduction

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

Page 234: Java Introduction

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

Page 235: Java Introduction

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

Page 236: Java Introduction

236Java Programming

Java GUI Components

Page 237: Java Introduction

237Java Programming

Graphical User Interface (GUI)

Components (continued)

• GUI components placed in content pane

• GUI components

– Windows

– Labels

– Text areas

– Buttons

Page 238: Java Introduction

238Java Programming

GUI Components

• Added to content pane of window

• Not added to window itself

• Pixel: picture element

Page 239: Java Introduction

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

Page 240: Java Introduction

240Java Programming

class JFrame

• GUI window instance created as instance of JFrame

• Provides various methods to control

window attributes

Page 241: Java Introduction

241Java Programming

Methods Provided by the class

JFrame

Page 242: Java Introduction

242Java Programming

Methods Provided by the class

Jframe (continued)

Page 243: Java Introduction

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

Page 244: Java Introduction

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

Page 245: Java Introduction

245Java Programming

Methods Provided by the class

Container

Page 246: Java Introduction

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

Page 247: Java Introduction

247Java Programming

class Jlabel (continued)

Page 248: Java Introduction

248Java Programming

class JTextField

• Text fields: objects belonging to class

JTextField

• To create text field:

– Declare reference variable of type JTextField

– Instantiate object

Page 249: Java Introduction

249Java Programming

class JTextField

(continued)

Page 250: Java Introduction

250Java Programming

class JTextField (continued)

Page 251: Java Introduction

251Java Programming

class JButton

• Provided to create buttons in Java

• To create button:

– Same technique as creating JLabel and

JTextField

Page 252: Java Introduction

252Java Programming

class Jbutton (continued)

Page 253: Java Introduction

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

Page 254: Java Introduction

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

Page 255: Java Introduction

255Java Programming

Rectangle Program: Sample Run

Page 256: Java Introduction

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

Page 257: Java Introduction

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

Page 258: Java Introduction

258Java Programming

Sample Run for TempConversion

Page 259: Java Introduction

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

Page 260: Java Introduction

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

Page 261: Java Introduction

261Java Programming

class Rectangle with Data

Members and Operations

Page 262: Java Introduction

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

Page 263: Java Introduction

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

Page 264: Java Introduction

264Java Programming

Object-Oriented Design

Example 2 (continued)

Page 265: Java Introduction

265Java Programming

Object-Oriented Design

Example 2 (continued)

Page 266: Java Introduction

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)

Page 267: Java Introduction

267Java Programming

The class Integer

Page 268: Java Introduction

268Java Programming

The class Integer (continued)

Page 269: Java Introduction

269Java Programming

The class Integer (continued)

Page 270: Java Introduction

270Java Programming

The class Integer (continued)

Integer num;

num = new Integer(86)

Page 271: Java Introduction

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

Page 272: Java Introduction

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

Page 273: Java Introduction

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

Page 274: Java Introduction

274Java Programming

The class Integer (continued)

Page 275: Java Introduction

275Java Programming

The class Integer (continued)

Page 276: Java Introduction

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

Page 277: Java Introduction

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

Page 278: Java Introduction

Java Programming

Chapter 7

User-Defined Methods

Page 279: Java Introduction

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

Page 280: Java Introduction

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

Page 281: Java Introduction

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

Page 282: Java Introduction

282Java Programming

Predefined Classes (continued)

Page 283: Java Introduction

283Java Programming

Predefined Classes (continued)

Page 284: Java Introduction

284Java Programming

Predefined Classes (continued)

Page 285: Java Introduction

285Java Programming

Predefined Classes (continued)

Page 286: Java Introduction

286Java Programming

class Character

(Package: java.lang)

Page 287: Java Introduction

287Java Programming

class Character

(Package: java.lang) (continued)

Page 288: Java Introduction

288Java Programming

class Character

(Package: java.lang) (continued)

Page 289: Java Introduction

289Java Programming

Syntax: Value-Returning Method

Page 290: Java Introduction

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

Page 291: Java Introduction

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:

Page 292: Java Introduction

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:

Page 293: Java Introduction

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;

}

Page 294: Java Introduction

294Java Programming: From Problem Analysis to Program Design, 4e 294Java Programming

Page 295: Java Introduction

295Java Programming: From Problem Analysis to Program Design, 4e 295Java Programming

Page 296: Java Introduction

296Java Programming

Equivalent Method Definitions

(continued)

public static double larger(double x, double y)

{

if (x >= y)

return x;

else

return y;

}

Page 297: Java Introduction

297Java Programming

Equivalent Method Definitions

(continued)

public static double larger(double x, double y)

{

if (x >= y)

return x;

return y;

}

Page 298: Java Introduction

298Java Programming: From Problem Analysis to Program Design, 4e

The int variable num contains the desired sum to be rolled

298Java Programming

Page 299: Java Introduction

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

Page 300: Java Introduction

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;

}

Page 301: Java Introduction

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

Page 302: Java Introduction

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

Page 303: Java Introduction

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);

}

Page 304: Java Introduction

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

Page 305: Java Introduction

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

Page 306: Java Introduction

306Java Programming

Void Methods with Parameters: Syntax

Page 307: Java Introduction

307Java Programming

Void Methods with Parameters:

Syntax (continued)

Page 308: Java Introduction

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

Page 309: Java Introduction

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

Page 310: Java Introduction

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

Page 311: Java Introduction

311Java Programming

Reference Variables as Parameters:

type String

Page 312: Java Introduction

312Java Programming

Reference Variables as Parameters:

type String (continued)

Page 313: Java Introduction

313Java Programming

Reference Variables as Parameters:

type String (continued)

Page 314: Java Introduction

314Java Programming

Reference Variables as Parameters:

type String (continued)

Page 315: Java Introduction

315Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters:

type String (continued)String str = "Hello"; //Line 5

315Java Programming

Page 316: Java Introduction

316Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters:

type String (continued)

stringParameter(str); //Line 7

316Java Programming

Page 317: Java Introduction

317Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters:

type String (continued)

pStr = "Sunny Day"; //Line 14

317Java Programming

Page 318: Java Introduction

318Java Programming

Reference Variables as Parameters:

type String (continued)

Variables before the statement in Line 8 executes

Page 319: Java Introduction

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

Page 320: Java Introduction

320Java Programming: From Problem Analysis to Program Design, 4e 320Java Programming

Page 321: Java Introduction

321Java Programming: From Problem Analysis to Program Design, 4e 321Java Programming

Page 322: Java Introduction

322Java Programming: From Problem Analysis to Program Design, 4e 322Java Programming

Page 323: Java Introduction

323Java Programming: From Problem Analysis to Program Design, 4e 323Java Programming

Page 324: Java Introduction

324Java Programming: From Problem Analysis to Program Design, 4e 324Java Programming

Page 325: Java Introduction

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

Page 326: Java Introduction

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

Page 327: Java Introduction

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

Page 328: Java Introduction

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

Page 329: Java Introduction

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

Page 330: Java Introduction

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

...

}

}

Page 331: Java Introduction

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

Page 332: Java Introduction

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

Page 333: Java Introduction

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)

Page 334: Java Introduction

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)

Page 335: Java Introduction

335Java Programming

Scope Rules: Demonstrated

Page 336: Java Introduction

336Java Programming

Scope Rules: Demonstrated (continued)

Page 337: Java Introduction

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

Page 338: Java Introduction

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

Page 339: Java Introduction

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

Page 340: Java Introduction

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

Page 341: Java Introduction

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)

Page 342: Java Introduction

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

Page 343: Java Introduction

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

Page 344: Java Introduction

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)

Page 345: Java Introduction

345Java Programming

Programming Example: Data

Comparison (continued)

Page 346: Java Introduction

346Java Programming

Chapter Summary

• Predefined methods

• User-defined methods

– Value-returning methods

– Void methods

– Formal parameters

– Actual parameters

• Flow of Execution

Page 347: Java Introduction

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

Page 348: Java Introduction

Java Programming

Chapter 7

Passing Primitive Types As Objects

Page 349: Java Introduction

• 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

Page 350: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 350Java Programming

Page 351: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 351Java Programming

Page 352: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 352Java Programming

Page 353: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 353Java Programming

Page 354: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 354Java Programming

Page 355: Java Introduction

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

Page 356: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 356Java Programming

Page 357: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 357Java Programming

Page 358: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 358Java Programming

Page 359: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 359Java Programming

Page 360: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 360Java Programming

Page 361: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 361Java Programming

Page 362: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e

num1 = 10; //Line 5

362Java Programming

Page 363: Java Introduction

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

Page 364: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 364Java Programming

Page 365: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e

num = b.getNum(); //Line 14

365Java Programming

Page 366: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 366Java Programming

Page 367: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 367Java Programming

Page 368: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 368Java Programming

Page 369: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 369Java Programming

Page 370: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 370Java Programming

Page 371: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 371Java Programming

Page 372: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 372Java Programming

Page 373: Java Introduction

Java Programming: From Problem Analysis to Program Design, 4e 373Java Programming

Page 374: Java Introduction

Java Programming

Chapter 8

User-Defined Classes and ADTs

Page 375: Java Introduction

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

Page 376: Java Introduction

Java Programming 376

Chapter Objectives (continued)

• Examine constructors and finalizers

• Examine the method toString

• Learn about the abstract data type (ADT)

Page 377: Java Introduction

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

}

...

}

Page 378: Java Introduction

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

Page 379: Java Introduction

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

Page 380: Java Introduction

Java Programming 380

Syntax

The general syntax for defining a class is:

Page 381: Java Introduction

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

Page 382: Java Introduction

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)

Page 383: Java Introduction

Java Programming 383

Data Members (Instance Variables)•private int hr; //store hours

•private int min; //store minutes

•private int sec; //store seconds

class Clock:

Page 384: Java Introduction

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()

Page 385: Java Introduction

Java Programming 385

• Two types of constructors- With parameters

- Without parameters (default constructor)

Constructors

Page 386: Java Introduction

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

Page 387: Java Introduction

Java Programming 387

• Default constructor is:- public Clock()

• Constructor with parameters is:- public Clock(int hours, int

minutes, int seconds)

class Clock: Constructors

Page 388: Java Introduction

Java Programming 388

Unified Modeling Language Class

Diagrams

Page 389: Java Introduction

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);

Page 390: Java Introduction

Java Programming 390

Variable Declaration and Object

Instantiation (continued)

Page 391: Java Introduction

Java Programming 391

Variable Declaration and Object

Instantiation (continued)

Page 392: Java Introduction

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)).

.

.

Page 393: Java Introduction

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

Page 394: Java Introduction

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)

Page 395: Java Introduction

Java Programming 395

Assignment Operator: A Precaution

(continued)

Page 396: Java Introduction

Java Programming 396

Definitions of the Constructors and

Methods of the class Clock

Page 397: Java Introduction

Java Programming 397

Definitions of the Constructors and

Methods of the class Clock (continued)

Page 398: Java Introduction

Java Programming 398

Definitions of the Constructors and

Methods of the class Clock (continued)

Page 399: Java Introduction

Java Programming 399

Definitions of the Constructors and

Methods of the class Clock (continued)

Page 400: Java Introduction

Java Programming 400

Definitions of the Constructors and

Methods of the class Clock (continued)

Page 401: Java Introduction

Java Programming 401

Definitions of the Constructors and

Methods of the class Clock (continued)

Page 402: Java Introduction

Java Programming 402

Definitions of the Constructors and

Methods of the class Clock (continued)

Page 403: Java Introduction

Java Programming 403

Definitions of the Constructors and

Methods of the class Clock (continued)

Page 404: Java Introduction

Java Programming 404

Definitions of the Constructors and

Methods of the class Clock (continued)

Page 405: Java Introduction

Java Programming 405

Definitions of the Constructors and

Methods of the class Clock (continued)

Page 406: Java Introduction

Java Programming 406

Definitions of the Constructors and

Methods of the class Clock (continued)

Page 407: Java Introduction

Java Programming 407

Definitions of the Constructors and

Methods of the class Clock (continued)

Page 408: Java Introduction

Java Programming 408

Default Constructor

or

Page 409: Java Introduction

Java Programming 409

Constructor with Parameters

or

Page 410: Java Introduction

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

Page 411: Java Introduction

Java Programming 411

Method toString: class Clock

Page 412: Java Introduction

Java Programming 412

The Copy Constructor

• Executes when an object is instantiated

• Initialized using an existing object

• Syntax

Page 413: Java Introduction

Java Programming 413

The Copy Constructor

(continued)

Page 414: Java Introduction

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

Page 415: Java Introduction

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

Page 416: Java Introduction

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)

Page 417: Java Introduction

Java Programming 417

Illustrate illusObject1 = new Illustrate(3);

Illustrate illusObject2 = new Illustrate(5);

Static Members of a Class

(continued)

Page 418: Java Introduction

Java Programming 418

Illustrate.incrementY();

Illustrate.count++;

Static Members of a Class

(continued)

Page 419: Java Introduction

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

Page 420: Java Introduction

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)

Page 421: Java Introduction

Java Programming 421

The Reference this

• Refers to instance variables and methods of

a class

• Used to implement cascaded method calls

Page 422: Java Introduction

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

Page 423: Java Introduction

Java Programming 423

Abstract Data Types

• Definition

- A data type that specifies the logical

properties without the implementation details

Page 424: Java Introduction

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

Page 425: Java Introduction

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

Page 426: Java Introduction

Java Programming 426

Programming Example: Candy

Machine (Input and Output)

• Input: the item selection and the cost of the

item

• Output: the selected item

Page 427: Java Introduction

Java Programming 427

Programming Example:

Candy Machine

• Components

– Cash Register

– Dispenser

– Machine

Page 428: Java Introduction

Java Programming 428

Programming Example:

Candy Machine (continued)

Page 429: Java Introduction

Java Programming 429

Programming Example:

Candy Machine (continued)

Page 430: Java Introduction

Java Programming 430

Programming Example:

Candy Machine (continued)

Page 431: Java Introduction

Java Programming 431

Programming Example:

Candy Machine (continued)

Page 432: Java Introduction

Java Programming 432

Programming Example:

Candy Machine (continued)

Page 433: Java Introduction

Java Programming 433

Programming Example:

Candy Machine (continued)

Page 434: Java Introduction

Java Programming 434

Chapter Summary

• Creating classes

• Members of a class– private

– protected

– public

– static

• Implementing classes

• Various operations on classes

Page 435: Java Introduction

Java Programming 435

Chapter Summary (continued)

• Constructors

• Finalizers

• Method toString

• Abstract Data Types

Page 436: Java Introduction

Java Programming

Chapter 9

Arrays

Page 437: Java Introduction

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

Page 438: Java Introduction

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

Page 439: Java Introduction

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

Page 440: Java Introduction

Java Programming 440

One-Dimensional Arrays

Page 441: Java Introduction

Java Programming 441

One-Dimensional Arrays

(continued)

Page 442: Java Introduction

Java Programming 442

One-Dimensional Arrays

(continued)

•intExp = number of components in array >= 0

•0 <= indexExp <= intExp

Page 443: Java Introduction

Java Programming 443

• Array num:int[] num = new int[5];

Arrays

Page 444: Java Introduction

Java Programming 444

• Array num:int[] num = new int[5];

Arrays (continued)

Page 445: Java Introduction

Java Programming 445

Array List

Page 446: Java Introduction

Java Programming 446

Array List (continued)

Page 447: Java Introduction

Java Programming 447

Array List (continued)

Page 448: Java Introduction

Java Programming 448

Array List (continued)

Page 449: Java Introduction

Java Programming 449

Specifying Array Size During Program Execution

Page 450: Java Introduction

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

Page 451: Java Introduction

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

Page 452: Java Introduction

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

Page 453: Java Introduction

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

Page 454: Java Introduction

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)

Page 455: Java Introduction

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

Page 456: Java Introduction

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;

Page 457: Java Introduction

Java Programming 457

Code to Initialize Array to

Specific Value (10.00)

for (int index = 0; index < sales.length;

index++)

sales[index] = 10.00;

Page 458: Java Introduction

Java Programming 458

Code to Read Data into Array

for (int index = 0; index < sales.length;

index++)

sales[index] = console.nextDouble();

Page 459: Java Introduction

Java Programming 459

Code to Print Array

for (int index = 0; index < sales.length;

index++)

System.out.print(sales[index] + " ");

Page 460: Java Introduction

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;

Page 461: Java Introduction

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];

Page 462: Java Introduction

Java Programming 462

Determining Largest Element in

Array (continued)

Page 463: Java Introduction

Java Programming 463

Determining Largest Element in Array (continued)

Page 464: Java Introduction

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

Page 465: Java Introduction

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);

Page 466: Java Introduction

Java Programming 466

The Assignment Operators and

Arrays

Page 467: Java Introduction

Java Programming 467

The Assignment Operators and

Arrays (continued)

Page 468: Java Introduction

Java Programming 468

The Assignment Operators and

Arrays (continued)

Page 469: Java Introduction

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

Page 470: Java Introduction

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))

...

Page 471: Java Introduction

Java Programming 471

Arrays as Parameter Methods

Page 472: Java Introduction

Java Programming 472

Methods for Array Processing

Page 473: Java Introduction

Java Programming 473

Methods for Array Processing (continued)

Page 474: Java Introduction

Java Programming 474

Methods for Array Processing

(continued)

Page 475: Java Introduction

Java Programming 475

Methods for Array Processing

(continued)

Page 476: Java Introduction

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

Page 477: Java Introduction

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

Page 478: Java Introduction

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;

}

Page 479: Java Introduction

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();

Page 480: Java Introduction

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";

Page 481: Java Introduction

Java Programming 481

Array of String Objects

(continued)

Page 482: Java Introduction

Java Programming 482

Clock[] arrivalTimeEmp = new Clock[100];

Arrays of Objects (continued)

Page 483: Java Introduction

Java Programming 483

Instantiating Array Objectsfor (int j = 0; j < arrivalTimeEmp.length; j++)

arrivalTimeEmp[j] = new Clock();

Page 484: Java Introduction

Java Programming 484

arrivalTimeEmp[49].setTime(8, 5, 10);

Instantiating Array Objects (continued)

Page 485: Java Introduction

Java Programming 485

Arrays and Variable Length

Parameter List

• The syntax to declare a variable length formal

parameter (list) is:

dataType ... identifier

Page 486: Java Introduction

Java Programming 486

Arrays and Variable Length Parameter List

(continued)

Page 487: Java Introduction

Java Programming 487

Arrays and Variable Length

Parameter List (continued)

Page 488: Java Introduction

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

Page 489: Java Introduction

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

Page 490: Java Introduction

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

Page 491: Java Introduction

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;

}

Page 492: Java Introduction

Java Programming 492

Two-Dimensional Arrays

Page 493: Java Introduction

Java Programming 493

Two-Dimensional Arrays

(continued)

Page 494: Java Introduction

Java Programming 494

double[][] sales = new double[10][5];

Two-Dimensional Arrays (continued)

Page 495: Java Introduction

Java Programming 495

• intExp1, intExp2 >= 0

• indexExp1 = row position

• indexExp2 = column position

Accessing Array Elements

Page 496: Java Introduction

Java Programming 496

Accessing Array Elements

(continued)

Page 497: Java Introduction

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

Page 498: Java Introduction

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

Page 499: Java Introduction

Java Programming 499

Two-Dimensional Arrays:

Special Cases

Page 500: Java Introduction

Java Programming 500

•Create columns

Two-Dimensional Arrays: Special

Cases (continued)

Page 501: Java Introduction

Java Programming 501

Two-Dimensional Array

Initialization During

Declaration

Page 502: Java Introduction

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)

Page 503: Java Introduction

Java Programming 503

Two-Dimensional Array

Initialization During Declaration

(continued)

Page 504: Java Introduction

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

Page 505: Java Introduction

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;

Print

for (int row = 0; row < matrix.length; row++)

{

for (int col = 0; col < matrix[row].length;

col++)

System.out.printf("%7d", matrix[row][col]);

System.out.println();

}

Page 506: Java Introduction

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)

Page 507: Java Introduction

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)

Page 508: Java Introduction

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)

Page 509: Java Introduction

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)

Page 510: Java Introduction

Java Programming 510

Page 511: Java Introduction

Java Programming 511

Page 512: Java Introduction

Java Programming 512

Page 513: Java Introduction

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

Page 514: Java Introduction

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;

Page 515: Java Introduction

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

Page 516: Java Introduction

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

Page 517: Java Introduction

Java Programming 517

Chapter Summary

• Arrays

– Definition

– Uses

• Different Arrays

– One-dimensional

– Two-dimensional

– Multidimensional (n-dimensional)

– Arrays of objects

– Parallel arrays

Page 518: Java Introduction

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

Page 519: Java Introduction

Java Programming

Chapter 10

Inheritance and Polymorphism

Page 520: Java Introduction

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

Page 521: Java Introduction

Java Programming 521

Chapter Objectives (continued)

• Learn about polymorphism

• Examine abstract classes

• Become aware of interfaces

• Learn about composition

Page 522: Java Introduction

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

Page 523: Java Introduction

Java Programming 523

Inheritance (continued)

modifier(s) class ClassName extends ExistingClassName

modifier(s)

{

memberList

}

Page 524: Java Introduction

Java Programming 524

Inheritance: class Circle Derived

from class Shape

public class Circle extends Shape

{

.

.

.

}

Page 525: Java Introduction

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

Page 526: Java Introduction

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

Page 527: Java Introduction

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)

Page 528: Java Introduction

Java Programming 528

UML Class Diagram: class

Rectangle

Page 529: Java Introduction

Java Programming 529

UML Class Diagram: class

Box

Page 530: Java Introduction

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);

}

Page 531: Java Introduction

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;

}

Page 532: Java Introduction

Java Programming 532

Objects myRectangle and myBox

Rectangle myRectangle = new Rectangle(5, 3);

Box myBox = new Box(6, 5, 4);

Page 533: Java Introduction

Java Programming 533

UML Class Diagram

Page 534: Java Introduction

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

Page 535: Java Introduction

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

Page 536: Java Introduction

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

//...

}

Page 537: Java Introduction

Java Programming 537

Some Constructors and Methods

of the class Object

Page 538: Java Introduction

Java Programming 538

Hierarchy of Java Stream Classes

Page 539: Java Introduction

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

Page 540: Java Introduction

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

Page 541: Java Introduction

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()

{

//...

}

Page 542: Java Introduction

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

Page 543: Java Introduction

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

Page 544: Java Introduction

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

Page 545: Java Introduction

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

Page 546: Java Introduction

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);

Page 547: Java Introduction

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

Page 548: Java Introduction

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;

}

}

Page 549: Java Introduction

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

Page 550: Java Introduction

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);

}

Page 551: Java Introduction

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

Page 552: Java Introduction

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‖

Page 553: Java Introduction

Java Programming 553

Composition (Aggregation) Example

Page 554: Java Introduction

Java Programming 554

Composition (Aggregation) Example

(continued)

Page 555: Java Introduction

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

Page 556: Java Introduction

Java Programming 556

Components Course and Student

Page 557: Java Introduction

Java Programming 557

Components Course and Student (continued)

Page 558: Java Introduction

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

Page 559: Java Introduction

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

Page 560: Java Introduction

Java Programming 560

Sample Output: Grade Report Program

Page 561: Java Introduction

Java Programming 561

Chapter Summary

• Inheritance

– Single and multiple

– Rules

– Uses

– Superclasses/subclasses (objects)

– Overriding/overloading methods

– Constructors

• The class Object

Page 562: Java Introduction

Java Programming 562

Chapter Summary (continued)

• Java stream classes

• Polymorphism

• Abstract methods

• Abstract classes

• Interfaces

• Composition

Page 563: Java Introduction

Java Programming

Chapter 11

Handling Exceptions and Events

Page 564: Java Introduction

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

Page 565: Java Introduction

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

Page 566: Java Introduction

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

Page 567: Java Introduction

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

Page 568: Java Introduction

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

Page 569: Java Introduction

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

Page 570: Java Introduction

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

Page 571: Java Introduction

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

Page 572: Java Introduction

Java Programming 572

try/catch/finally Block

(continued)

Page 573: Java Introduction

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

Page 574: Java Introduction

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

Page 575: Java Introduction

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

Page 576: Java Introduction

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

Page 577: Java Introduction

Java Programming 577

Java Exception Hierarchy

Page 578: Java Introduction

Java Programming 578

Java Exception Hierarchy (continued)

Page 579: Java Introduction

Java Programming 579

Java Exception Hierarchy (continued)

Page 580: Java Introduction

Java Programming 580

Java Exception Hierarchy (continued)

Page 581: Java Introduction

Java Programming 581

Java Exception Hierarchy (continued)

Page 582: Java Introduction

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

Page 583: Java Introduction

Java Programming 583

The class Exception and

its Constructors

Page 584: Java Introduction

Java Programming 584

Java Exception Classes

Page 585: Java Introduction

Java Programming 585

Java Exception Classes

(continued)

Page 586: Java Introduction

Java Programming 586

Java Exception Classes (continued)

Page 587: Java Introduction

Java Programming 587

Java Exception Classes (continued)

Page 588: Java Introduction

Java Programming 588

Java Exception Classes (continued)

Page 589: Java Introduction

Java Programming 589

Java Exception Classes (continued)

Page 590: Java Introduction

Java Programming 590

Java Exception Classes (continued)

Page 591: Java Introduction

Java Programming 591

Java Exception Classes (continued)

Page 592: Java Introduction

Java Programming 592

Checked Exceptions

• Definition: any exception that can be

recognized by the compiler

• Examples

– FileNotFoundExceptions

Page 593: Java Introduction

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

Page 594: Java Introduction

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

Page 595: Java Introduction

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

Page 596: Java Introduction

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

Page 597: Java Introduction

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

Page 598: Java Introduction

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;

Page 599: Java Introduction

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)

Page 600: Java Introduction

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)

Page 601: Java Introduction

Java Programming 601

The Method printStackTrace

• Used to determine the order in which the

methods were called and where the

exception was handled

Page 602: Java Introduction

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)

Page 603: Java Introduction

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)

Page 604: Java Introduction

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)

Page 605: Java Introduction

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

Page 606: Java Introduction

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);

Page 607: Java Introduction

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);

}

}

Page 608: Java Introduction

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

Page 609: Java Introduction

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

Page 610: Java Introduction

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

Page 611: Java Introduction

Java Programming 611

Event Handling (continued)

Page 612: Java Introduction

Java Programming 612

Event Handling (continued)

Page 613: Java Introduction

Java Programming 613

Event Handling (continued)

Page 614: Java Introduction

Java Programming 614

Programming Example:

Calculator

Page 615: Java Introduction

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

Page 616: Java Introduction

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

Page 617: Java Introduction

Java Programming

Chapter 12

Advanced GUIs and Graphics

Page 618: Java Introduction

Java Programming 618

Chapter Objectives

• Learn about applets

• Explore the class Graphics

• Learn about the class Font

• Explore the class Color

Page 619: Java Introduction

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

Page 620: Java Introduction

Java Programming 620

Inheritance Hierarchy of GUI Classes

Page 621: Java Introduction

Java Programming 621

Constructors and Methods of the class Component

Page 622: Java Introduction

Java Programming 622

Constructors and Methods of the

class Component (continued)

Page 623: Java Introduction

Java Programming 623

Constructors and Methods of the

class Component (continued)

Page 624: Java Introduction

Java Programming 624

Constructors and Methods of the

class Component (continued)

Page 625: Java Introduction

Java Programming 625

Constructors and Methods of the

class Container

Page 626: Java Introduction

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

Page 627: Java Introduction

Java Programming 627

Members of class JApplet

Page 628: Java Introduction

Java Programming 628

Members of class Japplet

(continued)

Page 629: Java Introduction

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

Page 630: Java Introduction

Java Programming 630

Applet Methods

• init Method

– Initializes variables

– Gets data from user

– Places various GUI components

• paint Method

– Performs output

Page 631: Java Introduction

Java Programming 631

Skeleton of a Java Applet

import java.awt.Graphics;

import javax.swing.JApplet;

public class WelcomeApplet extends JApplet

{

}

Page 632: Java Introduction

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

}

}

Page 633: Java Introduction

Java Programming 633

HTML to Run Applet

Page 634: Java Introduction

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)

Page 635: Java Introduction

Java Programming 635

Constructors and Methods of the class Font

Page 636: Java Introduction

Java Programming 636

Constructors and Methods of the class Font

(continued)

Page 637: Java Introduction

Java Programming 637

Constructors and Methods of the

class Font (continued)

Page 638: Java Introduction

Java Programming 638

class Color

• Shows text in different colors

• Changes background color of component

• Contained in package java.awt

Page 639: Java Introduction

Java Programming 639

Constructors of the class

Color

Page 640: Java Introduction

Java Programming 640

Constructors of the class

Color (continued)

Page 641: Java Introduction

Java Programming 641

Constants Defined in the class

Color

Page 642: Java Introduction

Java Programming 642

Constants Defined in the class

Color (continued)

Page 643: Java Introduction

Java Programming 643

Constants Defined in the class

Color (continued)

Page 644: Java Introduction

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

Page 645: Java Introduction

Java Programming 645

Constructors and Methods of the

class Graphics

Page 646: Java Introduction

Java Programming 646

Constructors and Methods of the

class Graphics

(continued)

Page 647: Java Introduction

Java Programming 647

Constructors and Methods of the

class Graphics

(continued)

Page 648: Java Introduction

Java Programming 648

Constructors and Methods of the

class Graphics

(continued)

Page 649: Java Introduction

Java Programming 649

Constructors and Methods of the

class Graphics

(continued)

Page 650: Java Introduction

Java Programming 650

Constructors and Methods of the

class Graphics

(continued)

Page 651: Java Introduction

Java Programming 651

Constructors and Methods of the

class Graphics (continued)

Page 652: Java Introduction

Java Programming 652

Constructors and Methods of the

class Graphics

(continued)

Page 653: Java Introduction

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

Page 654: Java Introduction

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)

Page 655: Java Introduction

Java Programming 655

Additional GUI Components

• JTextArea

• JCheckBox

• JRadioButton

• JComboBox

• JList

Page 656: Java Introduction

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

Page 657: Java Introduction

Java Programming 657

JTextArea (continued)

Page 658: Java Introduction

Java Programming 658

Methods Inherited by class

JTextArea from Parent

class JTextComponent

Page 659: Java Introduction

Java Programming 659

JTextArea Example

Page 660: Java Introduction

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

Page 661: Java Introduction

Java Programming 661

Constructors and Methods of class JCheckBox

Page 662: Java Introduction

Java Programming 662

Constructors and Methods of

class JCheckBox (continued)

Page 663: Java Introduction

Java Programming 663

Constructors and Methods of

class JCheckBox (continued)

Page 664: Java Introduction

Java Programming 664

Constructors and Methods of

class JCheckBox (continued)

Page 665: Java Introduction

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

Page 666: Java Introduction

Java Programming 666

JRadioButton (continued)

Page 667: Java Introduction

Java Programming 667

JRadioButton (continued)

Page 668: Java Introduction

Java Programming 668

JRadioButton (continued)

Page 669: Java Introduction

Java Programming 669

JRadioButton (continued)

Page 670: Java Introduction

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

Page 671: Java Introduction

Java Programming 671

Constructors of class JComboBox

Page 672: Java Introduction

Java Programming 672

Applet with JCheckBox,

JComboBox, and JRadioButton

Page 673: Java Introduction

Java Programming 673

Constructors of class JList

Page 674: Java Introduction

Java Programming 674

Constructors of class Jlist

(continued)

Page 675: Java Introduction

Java Programming 675

Constructors of class Jlist

(continued)

Page 676: Java Introduction

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

Page 677: Java Introduction

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

Page 678: Java Introduction

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

Page 679: Java Introduction

Java Programming 679

Key and Mouse Events

Page 680: Java Introduction

Java Programming 680

Chapter Summary

• Creating applets

• class Font

• class Graphics

• class Color

• Differences between applet and GUI

application

• Converting GUI application to applet

Page 681: Java Introduction

Java Programming 681

Chapter Summary (continued)

• GUI components

– JTextArea

– JCheckBox

– JRadioButton

• Layout managers

• Menus

• Key and mouse events

Page 682: Java Introduction

Java Programming

Chapter 13

Recursion

Page 683: Java Introduction

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

Page 684: Java Introduction

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

Page 685: Java Introduction

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

Page 686: Java Introduction

Java Programming 686

Recursive Definitions (continued)

Page 687: Java Introduction

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

Page 688: Java Introduction

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

Page 689: Java Introduction

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

Page 690: Java Introduction

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

Page 691: Java Introduction

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

Page 692: Java Introduction

Java Programming 692

Designing Recursive Methods

• Understand problem requirements

• Determine limiting conditions

• Identify base cases

Page 693: Java Introduction

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

Page 694: Java Introduction

Java Programming 694

Recursive Factorial Method

public static int fact(int num)

{

if (num = = 0)

return 1;

else

return num * fact(num – 1);

}

Page 695: Java Introduction

Java Programming 695

Recursive Factorial Method (continued)

Page 696: Java Introduction

Java Programming 696

Largest Value in Array

Page 697: Java Introduction

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)

Page 698: Java Introduction

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)

Page 699: Java Introduction

Java Programming 699

Execution of largest

(list, 0, 3)

Page 700: Java Introduction

Java Programming 700

Execution of largest (list, 0, 3)

Page 701: Java Introduction

Java Programming 701

Recursive Fibonacci

Page 702: Java Introduction

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);

}

Page 703: Java Introduction

Java Programming 703

Recursive Fibonacci (continued)

Page 704: Java Introduction

Java Programming 704

Towers of Hanoi Problem with

Three Disks

Page 705: Java Introduction

Java Programming 705

Towers of Hanoi: Three Disk

Solution

Page 706: Java Introduction

Java Programming 706

Towers of Hanoi: Three Disk Solution

(continued)

Page 707: Java Introduction

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);

}

}

Page 708: Java Introduction

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

Page 709: Java Introduction

Java Programming 709

Programming Example:

Decimal to Binary

Page 710: Java Introduction

Java Programming 710

Page 711: Java Introduction

Java Programming 711

Sierpinski Gaskets of Various Orders

Page 712: Java Introduction

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

Page 713: Java Introduction

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)

Page 714: Java Introduction

Java Programming 714

Programming Example: Sierpinski

Gasket (continued)

Page 715: Java Introduction

Java Programming 715

Chapter Summary

• Recursive definitions

• Recursive algorithms

• Recursive methods

• Base cases

• General cases

Page 716: Java Introduction

Java Programming 716

Chapter Summary (continued)

• Tracing recursive methods

• Designing recursive methods

• Varieties of recursive methods

• Recursion vs. iteration

• Various recursive functions explored


Recommended