java introduction chapter 1 overview 1. 2 chapter objectives examine how a java program is processed...

489
Java Introduction Chapter 1 Overview 1

Upload: marybeth-campbell

Post on 13-Jan-2016

213 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Java Introduction

Chapter 1Overview

1

Page 2: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

2

Chapter Objectives

• 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 3: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

3

Evolution of Programming Languages

• High-level languages make programming easier

• Closer to spoken languages• Examples

– Basic – FORTRAN– COBOL– C/C++– Java

Page 4: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

4

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 5: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

5

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 6: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

6

A Java Program

Output:

Page 7: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

7

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 8: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

8

Processing a Java Program (continued)

Figure 1-3

Page 9: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

9

Programming Methodologies

• Two basic approaches to programming design– Structured design – Object-oriented design

Page 10: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

10

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 11: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

11

Object-Oriented Design (OOD)

• In OOD, a program is a collection of interacting objects

• An object consists of data and operations

• Steps in OOD1. Identify objects

2. Form the basis of the solution

3. Determine how these objects interact

Page 12: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Java Introduction

Chapter 2Basic Elements of Java

Page 13: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

13

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 14: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

14

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 15: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

15

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 16: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

16

Introduction

• Computer program: a sequence of statements whose objective is to accomplish a task

• Programming: process of planning and creating a program

Page 17: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

17

A Java Program

Sample Run:

Page 18: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

18Java Introduction

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

18

Page 19: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

19

Special Symbols

Page 20: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

20

Reserved Words (Keywords)

• int• float• double• char

• void• public• static• throws • return

Page 21: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

21

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 22: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

22

Illegal Identifiers

Page 23: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

23

Data Types

• Data type: set of values together with a set of operations

Page 24: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

24

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 25: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

25

Integral Data Types

•char•byte •short •int•long

Page 26: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

26

Values and Memory Allocation for Integral Data Types

Page 27: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

27

Primitive Data Types

• Floating-point data types– float: precision = 6 or 7– double: precision = 15

• boolean: two values– true– false

Page 28: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

28Java Introduction

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'

28

Page 29: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

29

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 30: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

30

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 31: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

31

Expressions

• Integral expressions

• Floating-point or decimal expressions

• Mixed expressions

Page 32: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

32

Integral Expressions

• All operands are integers

• Examples2 + 3 * 5

3 + x – y / 7

x + 2 * (y – z) + 18

Page 33: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

33

Floating-Point Expressions

• All operands are floating-point numbers

• Examples

12.8 * 17.5 – 34.50

x * 10.5 + y - 16.2

Page 34: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

34

Mixed Expressions

• Operands of different types• Examples2 + 3.56 / 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 35: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

35

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 36: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

36

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 37: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

37

Strings and the Operator +• Operator + can be used to concatenate

two strings or a string and a numeric value or character

• Example"The sum = " + 12 + 26

-After this statement executes, the string assigned to str is:"The sum = 1226";

Page 38: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Strings and the Operator + (continued)

• Consider the following statement:"The sum = " + (12 + 26)

• In this statement, because of the parentheses, you first evaluate num1 + num2– Because num1 and num2 are both int

variables, num1 + num2 = 12 + 26 = 38

– After this statement executes, the string assigned to str is:

"The sum = 38";

38

Page 39: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Example2_1

// This program illustrates how the String concatenation works.

public class Example2_1

{

public static void main(String[] args)

{

System.out.println("The sum = " + 12 + 26);

System.out.println("The sum = " + (12 + 26));

System.out.println(12 + 26 + " is the sum");

System.out.println("The sum of " + 12 + " and " + 26

+ " = " + (12 + 26));

}

}

39

Page 40: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

40

Input• Named constant

– Cannot be changed during program execution– Declared by using the reserved word final– Initialized when it is declared

• Example final double CENTIMETERS_PER_INCH = 2.54;

final int NO_OF_STUDENTS = 20;

final char BLANK = ' ';

final double PAY_RATE = 15.75;

Page 41: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

41

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 double amountDue;int counter;char ch;int num1, num2;

Page 42: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

42

Input (continued)• The assignment statement

variable = expression;

• Example 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 43: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Example2_2

// This program illustrates how data in the variables are

// manipulated.

public class Example2_2

{

public static void main(String[] args)

{

int num1;

int num2;

double sale;

char first;

String str;

num1 = 4;

System.out.println("num1 = " + num1);

43

Page 44: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Example2_2 num2 = 4 * 5 - 11;

System.out.println("num2 = " + num2);

sale = 0.02 * 1000;

System.out.println("sale = " + sale);

first = 'D';

System.out.println("first = " + first);

str = "It is a sunny day.";

System.out.println("str = " + str);

}

}

44

Page 45: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

45Java Introduction

Input (continued)

• Example1. num1 = 18;

2. num1 = num1 + 27;

3. num2 = num1;

4. num3 = num2 / 5;

5. num3 = num3 / 4;

45

Page 46: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

46Java Introduction

Input (continued)

46

Page 47: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

47Java Introduction

Input (continued)

47

Page 48: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

48

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 49: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

49

Input (continued)static Scanner console = new Scanner(System.in);

• Example static Scanner console = new Scanner(System.in);

int feet;int inches;

Suppose the input is

23 7

feet = console.nextInt(); //Line 1inches = console.nextInt(); //Line 2

Page 50: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Example2_3// This program illustrates how input statements work.

import java.util.*;

public class Example2_3

{

static Scanner console = new Scanner(System.in);

public static void main(String[] args)

{

int feet;

int inches;

System.out.println("Enter two integers separated by spaces.");

feet = console.nextInt();

inches = console.nextInt();

System.out.println("Feet = " + feet);

System.out.println("Inches = " + inches);

}

}

50

Page 51: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

51

Increment and Decrement Operators

• ++ increments the value of its operand by 1• -- decrements the value of its operand by 1

• SyntaxPre-increment: ++variable

Post-increment: variable++

Pre-decrement: --variable

Post-decrement: variable--

Page 52: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

52

Output

• Standard output object: System.out• Methods

printprintln

• SyntaxSystem.out.print(stringExp);System.out.println(stringExp);

System.out.println();

Page 53: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

53

Commonly Used Escape Sequences

Page 54: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

54

Packages, Classes, Methods, and the import Statement

• Package: collection of related classes

• Class: consists of methods

• Method: designed to accomplish a specific task

Page 55: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

55

import Statement

• Used to import the components of a package into a program

• Reserved word• import java.io.*;

– Imports the (components of the) package java.io into the program

• Primitive data types and the class String– Part of the Java language– Don’t need to be imported

Page 56: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

56

Creating a Java Application Program

• Syntax of a class

• Syntax of the main method

Page 57: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

57

Debugging: Understanding and Fixing Syntax Errors

• When you type a program, typos and unintentional syntax errors are likely to occur

• Therefore, when you compile a program, the compiler will identify the syntax error

Page 58: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

58Java Introduction 58

Page 59: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

59Java Introduction

• The compiler produces the following errors:

ProgramNum.java:9: ';' expected

int num

^

ProgramNum.java:16: reached end of file while parsing

}

^

2 errors

59

Page 60: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

60Java Introduction 60

Page 61: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

61Java Introduction 61

Page 62: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

62Java Introduction 62

Page 63: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

63Java Introduction 63

Page 64: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

64Java Introduction 64

Page 65: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

65Java Introduction

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

65

Page 66: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

66Java Introduction

Avoiding Bugs: Consistent, Proper Formatting and Code Walkthrough

• Java is a free-format language in the sense that programming instructions need not be typed in specific columns

• As you will discover, consistent and proper formatting will make it easier to develop, debug, and maintain programs

• Throughout the book, you will see consistent and predictable use of blanks, tabs, and newline characters to separate the elements of a program

• When you write programs, unintentional typos and errors are unavoidable

• The Java compiler will find the syntax rules and give some hints how to correct them; however, the compiler may not find logical (semantic) errors

66

Page 67: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

67Java Introduction

Avoiding Bugs: Consistent, Proper Formatting and Code Walk-Through

(continued) • Typically, programmers try to find and fix these problems

themselves by walking carefully through their programs • Sometimes after multiple readings, a programmer may not be able

to find the bug because the programmer may overlook the piece of the code that contains the bug and therefore may seek outside help

• If your program is properly formatted and you have used good names for identifiers, the person reading your program will have an easier time reading and debugging the program

67

Page 68: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

68

Avoiding Bugs: Consistent, Proper Formatting and Code Walk-Through

(continued)

• Before you seek outside help, you should be prepared to explain what your program intended to do and answer questions raised by the person reading your program

• The examination of your program by yourself, by another person, or a group of persons is a walk-through; a walk-through is helpful for all phases of the software development process

Page 69: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

69

More on Assignment Statements

variable = variable * (expression);is equivalent to

variable *= expression;

Similarly,

variable = variable + (expression);is equivalent to

variable += expression;

Page 70: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

70

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 71: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

71

Chapter Summary

• Basic elements of a Java program include:– The main method

– Reserved words

– Special symbols

– Identifiers

– Data types

– Expressions

– Input

– Output

– Statements

Page 72: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

72

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 73: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Java Introduction

Chapter 3

Introduction to Objects and Input/Output

Page 74: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

74

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 75: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

75

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 76: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

76

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 77: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

77

int x; //Line 1

String str; //Line 2

x = 45; //Line 3

str = "Java Programming"; //Line 4

Object and Reference Variables (continued)

Page 78: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

78Java Introduction

Object and Reference Variables (continued)

78

Page 79: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

79

Object and Reference Variables (continued)

Page 80: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Object and Reference Variables (continued)

80

Page 81: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

81

• 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 82: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

82

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 83: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

83

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 84: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

84

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 85: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

85

The class String

• String variables are reference variables

• Given:

String name; – Similar statements:name = new String("Lisa Johnson");

name = "Lisa Johnson";

Page 86: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

86

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 87: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

87Java Introduction

The class String (continued)

sentence = "Programming with Java";

87

Page 88: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

88

Some Commonly Used String Methods

Page 89: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

89

Some Commonly Used String Methods (continued)

Page 90: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

90

Some Commonly Used String Methods (continued)

Page 91: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

91

Some Commonly Used String Methods (continued)

Page 92: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

92Java Introduction

Some Commonly Used String Methods (continued)

92

Page 93: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

93

Input/Output

• Input data

• Format output

• Output results

• Format output

• Read from and write to files

Page 94: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

94

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 95: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

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

95

Page 96: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

96

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 97: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

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

97

Page 98: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

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

98

Page 99: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

99

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 100: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

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

100

Page 101: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

101

Formatting Output with printf (continued)

Page 102: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

102Java Introduction 102

Page 103: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

103Java Introduction 103

Page 104: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

104Java Introduction 104

Page 105: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

105Java Introduction 105

Page 106: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

106Java Introduction 106

Page 107: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

107Java Introduction

The output of these statements is:

107

Page 108: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

108

Page 109: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

109Java Introduction 109

Page 110: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

110Java Introduction 110

Page 111: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

111Java Introduction

Sample Run:123456789012345678901234567890763 658.75 Java Program. ***Java Program. 763 658.75 ***658.75 763 Java Program. ***num = 763 ***x = 658.75 ***str = Java Program. ***Program No.4 ***

111

Page 112: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

112Java Introduction

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") = 6723Integer.parseInt("-823") = -823

112

Page 113: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

113

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.56Float.parseFloat("-542.97") = -542.97

Page 114: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

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.78Double.parseDouble("-782.873") = -782.873

114

Page 115: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

115

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 116: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

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

116

Page 117: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

117

Using Dialog Boxes for Input/Output

• Use a graphical user interface (GUI)• class JOptionPane

– Contained in package javax.swing– Contains methods showInputDialog and showMessageDialog

• Syntaxstr = JOptionPane.showInputDialog(strExpression)

• Program must end with System.exit(0);

Page 118: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

118Java Introduction

Using Dialog Boxes for Input/Output (continued)

118

Page 119: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

119

Parameters for the Method showMessageDialog

Page 120: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

120

JOptionPane Options for the Parameter messageType

Page 121: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

121

JOptionPane Example

Page 122: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

122

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 123: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

123

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 124: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

124

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 125: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

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

125

Page 126: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

126

File Input/Output (continued)

Page 127: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

127Java Introduction

File Input/Output (continued)

The statement in Line 1 assumes that the file prog.dat is in the same directory (subdirectory) as your program. However, if this is in a different directory (subdirectory), then you must specify the path where the file is located, along with the name of the file. For example, suppose that the file prog.dat is on a flash memory in drive H. Then the statement in Line 1 should be modified as follows:Scanner inFile = new Scanner(new FileReader("h:\\prog.dat"));Note that there are two \ after h:. Recall that in Java \ is the escape character. Therefore, to produce a \ within a string you need \\. (Moreover, to be absolutely sure about specifying the source where the input file is stored, such as the flash memory in drive h:\\, check your system’s documentation.)

127

Page 128: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

128

File Input/Output (continued)

• Java file I/O process1. 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 129: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

129

Example 3-16Suppose 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 130: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

130

Storing (Writing) Output to a File

• To store the output of a program in a file, you use the class PrintWriter

• Declare a PrintWriter variable and associate this variable with the destination

• Suppose the output is to be stored in the file prog.out

Page 131: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Storing (Writing) Output to a File (continued)

• Consider the following statement:PrintWriter outFile = new PrintWriter("prog.out");

• This statement creates the PrintWriter object outFile and associates it with the file prog.out

• You can now use the methods print, println, and printf with outFile just the same way they have been used with the object System.out

131

Page 132: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

132

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 133: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

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

133

Page 134: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

134

• 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 135: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

throws Clause (continued)• If an output file cannot be created or accessed, the

program throws a FileNotFoundException • For the next few chapters, we will simply throw

the exceptions• Because we do not need the method main to

handle the FileNotFoundException exception, we will include a command in the heading of the method main to throw the FileNotFoundException exception

135

Page 136: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

136

Skeleton of I/O Program

Page 137: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

137

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 138: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

138

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 139: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

import javax.swing.JOptionPane;

public class MovieTicketSale

{

public static void main(String[] args)

{

//Step 1

String movieName;

String inputStr;

String outputStr;

double adultTicketPrice;

double childTicketPrice;

int noOfAdultTicketsSold;

int noOfChildTicketsSold;

double percentDonation;

double grossAmount;

double amountDonated;

double netSaleAmount;

139

Page 140: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

movieName = JOptionPane.showInputDialog

("Enter the movie name"); //Step 2

inputStr = JOptionPane.showInputDialog

("Enter the price of an adult ticket"); //Step 3

adultTicketPrice = Double.parseDouble(inputStr); //Step 4

inputStr = JOptionPane.showInputDialog

("Enter the price of a child ticket"); //Step 5

childTicketPrice = Double.parseDouble(inputStr); //Step 6

inputStr = JOptionPane.showInputDialog

("Enter the number of adult tickets sold"); //Step 7

noOfAdultTicketsSold = Integer.parseInt(inputStr); //Step 8

inputStr = JOptionPane.showInputDialog

("Enter the number of child tickets sold"); //Step 9

noOfChildTicketsSold = Integer.parseInt(inputStr); //Step 10

inputStr = JOptionPane.showInputDialog

("Enter the percentage of the donation"); //Step 11

percentDonation = Double.parseDouble(inputStr); //Step 12

grossAmount = adultTicketPrice * noOfAdultTicketsSold +

childTicketPrice * noOfChildTicketsSold; //Step 13

140

Page 141: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

amountDonated = grossAmount * percentDonation / 100; //Step 14

netSaleAmount = grossAmount - amountDonated; //Step 15

outputStr = "Movie Name: " + movieName + "\n"

+ "Number of Tickets Sold: "

+ (noOfAdultTicketsSold +

noOfChildTicketsSold) + "\n"

+ "Gross Amount: $"

+ String.format("%.2f", grossAmount) + "\n"

+ "Percentage of the Gross Amount Donated: "

+ String.format("%.2f%%", percentDonation) + "\n"

+ "Amount Donated: $"

+ String.format("%.2f", amountDonated) + "\n"

+ "Net Sale: $"

+ String.format("%.2f", netSaleAmount); //Step 16

JOptionPane.showMessageDialog(null, outputStr,

"Theater Sales Data",

JOptionPane.INFORMATION_MESSAGE); //Step 17

System.exit(0); //Step 18

}

}

141

Page 142: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

142

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 143: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

143

Programming Example:Student Grade (continued)

• Import appropriate packages• Get input from file using the classes Scanner and FileReader

• Read and calculate the average of test scores

• Write to output file using the class PrintWriter

• Close files

Page 144: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

import java.io.*;

import java.util.*;

public class StudentGrade

{

public static void main(String[] args) throws

FileNotFoundException

{

//declare and initialize the variables //Step 1

double test1, test2, test3, test4, test5;

double average;

String firstName;

String lastName;

Scanner inFile =

new Scanner(new FileReader("test.txt")); //Step 2

PrintWriter outFile = new

PrintWriter("testavg.out"); //Step 3

firstName = inFile.next(); //Step 4

lastName = inFile.next(); //Step 4

144

Page 145: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

outFile.println("Student Name: "

+ firstName + " " + lastName); //Step 5

//Step 6 - retrieve the five test scores

test1 = inFile.nextDouble();

test2 = inFile.nextDouble();

test3 = inFile.nextDouble();

test4 = inFile.nextDouble();

test5 = inFile.nextDouble();

outFile.printf("Test scores: %5.2f %5.2f %5.2f "

+ "%5.2f %5.2f %n", test1, test2,

test3, test4, test5); //Step 7

average = (test1 + test2 + test3 + test4

+ test5) / 5.0; //Step 8

outFile.printf("Average test score: %5.2f %n",

average); //Step 9

inFile.close(); //Step 10

outFile.close(); //Step 10

}

}

145

Page 146: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

146

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 147: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

147

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 148: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Chapter Summary (continued)

• Methods of the class String are used to manipulate input and output data

• Dialog boxes can be used to input data and output results

• Data can be read from and written to files• Data can be formatted using the String

method format

148

Page 149: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Java Introduction

Chapter 4Control Structures I: Selection

Page 150: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

150

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 151: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

151

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 152: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

152

Flow of Execution

Page 153: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

153

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 154: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

154

Relational Operators in Java

Page 155: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

155

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 156: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

156Java Introduction 156

Page 157: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

157Java Introduction 157

Page 158: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

158

Relational Operators and the Unicode Collating Sequence

Page 159: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

159

Logical (Boolean) Operators

Page 160: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

160

Logical (Boolean) Operators (continued)

Page 161: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

161

Logical (Boolean) Operators (continued)

Page 162: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

162

Logical (Boolean) Operators (continued)

Page 163: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

163

Precedence of Operators

Page 164: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

164Java Introduction

Precedence of Operators (continued)

164

Page 165: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

165Java Introduction 165

Page 166: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

166Java Introduction 166

Page 167: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

167Java Introduction 167

Page 168: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

168

Selection

• One-way selection

• Two-way selection

• Compound (block of) statements

• Multiple selections (nested if)

• Conditional operator• switch structures

Page 169: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

169

One-Way Selection

• Syntaxif (expression)

statement

• Expression referred to as decision maker

• Statement referred to as action statement

Page 170: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

One-Way Selection (continued)

170

Page 171: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

171

Example 4-7

//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 Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

172

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 Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

173Java Introduction

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

173

Page 174: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

174

Two-Way Selection

• Syntax

if (expression)

statement1

else

statement2• else statement must be paired with an if

Page 175: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

175

Two-Way Selection (continued)

Page 176: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

176

Two-Way Selection (continued)

Example 4-10

if (hours > 40.0) wages = 40.0 * rate + 1.5 * rate * (hours - 40.0); else wages = hours * rate;

Page 177: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

177

Example 4-11

if (hours > 40.0); //Line 1 wages = 40.0 * rate + 1.5 * rate * (hours - 40.0); //Line 2else //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 178: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

178Java Introduction

Two-Way Selection (continued)

178

Page 179: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

179

Compound (Block of) Statements• Syntax

Page 180: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

180

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 181: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

181

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 182: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

182Java Introduction

Multiple Selection: Nested if (continued)

182

Page 183: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

183Java Introduction

Multiple Selection: Nested if (continued)

To avoid excessive indentation, the code in Example 4-15 can be rewritten as follows:

183

Page 184: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

184Java Introduction

Multiple Selection: Nested if (continued)

184

Page 185: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

185Java Introduction

Multiple Selection: Nested if (continued)

185

Page 186: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

186Java Introduction 186

Page 187: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

187Java Introduction 187

Page 188: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

188Java Introduction

• 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

Short-Circuit Evaluation

188

Page 189: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

189Java Introduction

Short-Circuit Evaluation (continued)

189

Page 190: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

190Java Introduction 190

Page 191: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

191Java Introduction 191

Page 192: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

192Java Introduction 192

Page 193: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

193Java Introduction

• The preceding program and its output show that you should be careful when comparing floating-point numbers for equality.

• One way to check whether two floating-point numbers are equal is to check whether the absolute value of their difference is less than a certain tolerance. For example, suppose the tolerance is .000001.

• Then x and y are equal if the absolute value of (x – y) is less than 0.000001. To find the absolute value, you can use the function Math.abs of the class Math, as shown in the program.

• Therefore, the expression Math.abs(x – y) < 0.000001 determines whether the absolute value of (x – y) is less than 0.000001.

193

Page 194: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

194

Conditional (? :) Operator

• Ternary operator

• Syntaxexpression1 ? expression2 : expression3

• If expression1 = true, then the result of the condition is expression 2; otherwise, the result of the condition is expression 3

Page 195: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

195Java Introduction 195

Page 196: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

196Java Introduction 196

Page 197: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

197Java Introduction 197

Page 198: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

198Java Introduction 198

Page 199: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

199

switch Structures

Page 200: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

200Java Introduction

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

200

Page 201: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

switch Structures (continued)

Java Introduction 201

• 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

201

Page 202: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

switch Structures (continued)

Java Introduction 202

• The break statement may or may not appear after each statements1, statements2, ..., statementsn

• A switch structure may or may not have the default label

202

Page 203: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

203

switch Structures (continued)

Page 204: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

204

switch Structures (continued)

Page 205: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

205

Example 4-20

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 206: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

206

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 207: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

207Java Introduction 207

Page 208: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

208Java Introduction 208

Page 209: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

209Java Introduction 209

Page 210: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

210Java Introduction

To output results correctly, the switch structure must include a break statement after each println statement, except the last println statement.

210

Page 211: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

211

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 212: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

212

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 213: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

213

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 214: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

214

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

String str2 = "Hi";

String str3 = "Air";

String str4 = "Bill";

String str5 = "Bigger";

Page 215: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

215

Comparing Strings (continued)

Page 216: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

216

Comparing Strings (continued)

Page 217: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Code Example//***********************************************************

//

// Program: Cable Company Billing

// This program calculates and prints a customer’s bill for

// a local cable company. The program processes two types of

// customers: residential and business.

//***********************************************************

import java.util.*;

public class CableCompanyBilling

{

static Scanner console = new Scanner(System.in);

//Named constants - residential customers

static final double R_BILL_PROC_FEE = 4.50;

static final double R_BASIC_SERV_COST = 20.50;

static final double R_COST_PREM_CHANNEL = 7.50;

217

Page 218: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

//Named constants - business customers

static final double B_BILL_PROC_FEE = 15.00;

static final double B_BASIC_SERV_COST = 75.00;

static final double B_BASIC_CONN_COST = 5.00;

static final double B_COST_PREM_CHANNEL = 50.00;

public static void main(String[] args)

{

//Variable declaration

int accountNumber;

char customerType;

int noOfPremChannels;

int noOfBasicServConn;

double amountDue;

System.out.println("This program computes "

+ "a cable bill.");

218

Page 219: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

System.out.print("Enter the account "

+ "number: "); //Step 1

accountNumber = console.nextInt(); //Step 2

System.out.println();

System.out.print("Enter the customer type: "

+ "R or r (Residential), "

+ "B or b(Business): "); //Step 3

customerType = console.next().charAt(0); //Step 4

System.out.println();

switch (customerType)

{

case 'r': //Step 5

case 'R':

System.out.print("Enter the number of "

+ "premium channels: "); //Step 5a

noOfPremChannels = console.nextInt(); //Step 5b

System.out.println();

amountDue = R_BILL_PROC_FEE + //Step 5c

R_BASIC_SERV_COST +

noOfPremChannels *

R_COST_PREM_CHANNEL;

System.out.println("Account number = "

+ accountNumber); //Step 5d

System.out.printf("Amount due = $%.2f %n",

amountDue); //Step 5e

break;

219

Page 220: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

case 'b': //Step 6

case 'B':

System.out.print("Enter the number of "

+ "basic service "

+ "connections: "); //Step 6a

noOfBasicServConn = console.nextInt(); //Step 6b

System.out.println();

System.out.print("Enter the number of "

+ "premium channels: "); //Step 6c

noOfPremChannels = console.nextInt(); //Step 6d

System.out.println();

if (noOfBasicServConn <= 10) //Step 6e

amountDue = B_BILL_PROC_FEE +

B_BASIC_SERV_COST +

noOfPremChannels *

B_COST_PREM_CHANNEL;

else

amountDue = B_BILL_PROC_FEE +

B_BASIC_SERV_COST +

(noOfBasicServConn - 10) *

B_BASIC_CONN_COST +

noOfPremChannels *

B_COST_PREM_CHANNEL;

220

Page 221: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

System.out.println("Account number = "

+ accountNumber); //Step 6f

System.out.printf("Amount due = $%.2f %n",

amountDue); //Step 6g

break;

default: //Step 7

System.out.println("Invalid customer type.");

}//end switch

}

}

221

Page 222: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

222

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 223: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Java Introduction

Chapter 5Control Structures II: Repetition

Page 224: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

224

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 225: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

225

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 226: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

226

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 227: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

227

The while Looping (Repetition) Structure (continued)

Page 228: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

228

The while Looping (Repetition) Structure (continued)

Example 5-1

i = 0; //Line 1while (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 229: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

229

The while Looping (Repetition) Structure (continued)

• Typically, while loops are written in the following form:

Page 230: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

230

Counter-Controlled while Loop• Used when exact number of data or entry pieces is

known• General form:

Page 231: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

231Java Introduction 231

Page 232: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

232Java Introduction 232

Page 233: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

233Java Introduction 233

Page 234: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

234Java Introduction 234

Page 235: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

235

Sentinel-Controlled while Loop

• Used when exact number of entry pieces is unknown but last entry (special/sentinel value) is known

• General form:

Page 236: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

236Java Introduction 236

Page 237: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

237

Java Introduction

237

Page 238: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

238

Flag-Controlled while Loop

• Boolean value used to control loop

• General form:

Page 239: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

239

EOF (End of File)-Controlled while Loop

• Used when input is from files• Sentinel value is not always appropriate• In an EOF-controlled while loop that uses

the Scanner object console to input data, console acts at the loop control variable

• The method hasNext, of the class Scanner, returns true if there is an input in the input stream; otherwise it returns false

Page 240: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

240

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 241: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

241

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 242: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

242Java Introduction 242

Page 243: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

243

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 244: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

244

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 245: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

245

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 246: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

246

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 247: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

247

The for Looping (Repetition) Structure (continued)

Page 248: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

248

The for Looping (Repetition) Structure (continued)

Example 5-9The following for loop prints the first 10 nonnegative integers:

for (i = 0; i < 10; i++)

System.out.print(i + " ");

System.out.println();

Page 249: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

249

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 250: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

250

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 251: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

The for Looping (Repetition) Structure (continued)

• If logical expression is omitted, it is assumed to be true

• for statement ending in semicolon is empty

251

Page 252: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Java Introduction 252252

Page 253: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Java Introduction 253253

Page 254: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

254

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 255: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

255

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 256: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

256Java Introduction

Programming Example: Classify Numbers (Solution) (continued)

• The switch statement in Step 3c can also be written as an if...else statement as follows:

256

Page 257: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

257

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 258: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

258

do…while Loop (Post-test Loop)

Page 259: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

259Java Introduction

do…while Loop (Post-test Loop) (continued)

259

Page 260: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

260Java Introduction

do…while Loop (Post-test Loop) (continued)

• A do...while loop can be used for input validation. • Suppose that a program prompts a user to enter a test score, which

must be greater than or equal to 0 and less than or equal to 50. • If the user enters a score less than 0 or greater than 50, the user

should be prompted to re-enter the score. • The following do...while loop can be used to accomplish this

objective:

260

Page 261: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

261Java Introduction

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

261

Page 262: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

262

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 263: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

263

continue Statements

• Used in while, for, and do...while structures

• When executed in a loop, the remaining statements in the loop are skipped; proceeds with the next iteration of the loop

• When executed in a while/do…while structure, expression evaluated immediately after continue statement

• In a for structure, the update expression is executed after the continue statement; then the loop condition executes

Page 264: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

264Java Introduction

The objective is to find the sum of the numbers in each line. For each line, output the numbers together with their sum. Let us consider the following program:

264

Page 265: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

265Java Introduction 265

Page 266: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

266Java Introduction 266

Page 267: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

267Java Introduction 267

Page 268: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

268Java Introduction

• The Sample Run shows that there is a bug in the program because after correctly producing the three lines of output, the program crashes with error messages.

• This is an example of a run (execution) time error. That is, the program compiled correctly, but crashed during execution.

• The last line of output shows that the error is in line 23 of the code, which is the put statement: num = infile.nextInt();.

• The program is trying to read data from the input file, but there is no more input in the file.

• At this point the value of the outer loop variable i is 4. Clearly, there is a bug in the program and we must fix the code. Some programmers, especially some beginners, address the symptom of the problem by adding a software patch.

• A beginning programmer might fix the code by adding a software patch as shown in the following modified program:

268

Page 269: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

269Java Introduction 269

Page 270: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

270Java Introduction 270

Page 271: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

271Java Introduction 271

Page 272: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

272Java Introduction

• The programmer merely observed the symptom and addressed the problem by adding a software patch.

• Not only will the program execute extra statements, it is also an example of a partially understood concept.

• It appears that the programmer does not have a good grasp of why the earlier program produced four lines rather than three. Adding a patch eliminated the symptom, but it is a poor programming practice.

• The programmer must resolve why the program produced four lines.

• Looking at the program closely, we can see that the four lines are produced because the outer loop executes four times.

272

Page 273: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

273Java Introduction

• The values assigned to loop control variable i are 1, 2, 3, and 4. • This is an example of the classic ‘‘off by one’’ problem. (In the

‘‘off by one’’ problem, either the loop executes one too many or one too few times.)

• We can eliminate this problem by correctly setting the values of the loop control variable. For example, we can rewrite the loops as follows:

273

Page 274: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

274Java Introduction 274

Page 275: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

275Java Introduction

• If there are syntax errors, the compiler will identify them. • If there are logical errors, we must carefully look at the code or

even maybe at the design to try to find the errors. • To increase the reliability of the program, errors must be

discovered and fixed before the program is released to the users. • Once an algorithm is written, the next step is to verify that it

works properly. • If the algorithm is a simple sequential flow or contains a branch,

it can be hand traced or you can use the debugger, if any, provided by the IDE.

275

Page 276: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

276Java Introduction

• Typically, loops are harder to debug. The correctness of a loop can be verified by using loop invariants.

• A loop invariant is a set of statements that remains true each time the loop body is executed. Let p be a loop invariant and q be the (logical) expression in a loop statement.

• Then p && q remains true before each iteration of the loop and p && not(q) is true after the loop terminates.

276

Page 277: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

277Java Introduction

• The most common error associated with loops is off by one. • If a loop turns out to be an infinite loop, the error is most likely in

the logical expression that controls the execution of the loop. • Check the logical expression carefully and see if you have reversed

an inequality, an assignment statement symbol appears in place of the equality operator, or && appears in place of ||.

• If the loop changes the values of variables, you can print the values of the variables before and/or after each iteration or you can use your IDE’s debugger, if any, and watch the values of variables during each iteration.

• Debugging can be a tiresome process. • If your program is very bad, do not debug; throw it away and start

over.

277

Page 278: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

278

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 279: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

279

Nested Control Structure (Example)

for (i = 1; i <= 5; i++){ for (j = 1; j <= i; j++) System.out.print(" *");

System.out.println();}• Output:***************

Page 280: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Code Example//********************************************************

// Program: Telephone Digits

// This is an example of a sentinel-controlled while loop.

// This program converts uppercase letters to their

// corresponding telephone digits.

//********************************************************

import javax.swing.JOptionPane;

public class TelephoneDigitProgram

{

public static void main (String[] args)

{

char letter; //Line 1

String inputMessage; //Line 2

String inputString; //Line 3

String outputMessage; //Line 4

280

Page 281: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Code Example inputMessage = "Program to convert uppercase "

+ "letters to their corresponding "

+ "telephone digits.\n"

+ "To stop the program enter #.\n"

+ "Enter a letter:"; //Line 5

inputString =

JOptionPane.showInputDialog(inputMessage); //Line 6

letter = inputString.charAt(0); //Line 7

while (letter != '#' ) //Line 8

{

outputMessage = "The letter you entered is: "

+ letter + "\n"

+ "The corresponding telephone "

+ "digit is: "; //Line 9

281

Page 282: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Code Example if (letter >= 'A' && letter <= 'Z') //Line 10

{

switch (letter) //Line 11

{

case 'A':

case 'B':

case 'C':

outputMessage = outputMessage

+ "2"; //Line 12

break; //Line 13

case 'D':

case 'E':

case 'F':

outputMessage = outputMessage

+ "3"; //Line 14

break; //Line 15

case 'G':

case 'H':

case 'I':

outputMessage = outputMessage

+ "4"; //Line 16

break; //Line 17

case 'J':

case 'K':

case 'L':

outputMessage = outputMessage

+ "5"; //Line 18

break; //Line 19

case 'M':

case 'N':

case 'O':

outputMessage = outputMessage

+ "6"; //Line 20

break; //Line 21

case 'P':

case 'Q':

case 'R':

case 'S':

outputMessage = outputMessage

+ "7"; //Line 22

break; //Line 23

case 'T':

case 'U':

case 'V':

outputMessage = outputMessage

+ "8"; //Line 24

break; //Line 25

case 'W':

case 'X':

case 'Y':

case 'Z':

outputMessage = outputMessage

+ "9"; //Line 26

}

}

282

Page 283: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Code Example case 'J':

case 'K':

case 'L':

outputMessage = outputMessage

+ "5"; //Line 18

break; //Line 19

case 'M':

case 'N':

case 'O':

outputMessage = outputMessage

+ "6"; //Line 20

break; //Line 21

case 'P':

case 'Q':

case 'R':

case 'S':

outputMessage = outputMessage

+ "7"; //Line 22

break; //Line 23

case 'T':

case 'U':

case 'V':

outputMessage = outputMessage

+ "8"; //Line 24

break; //Line 25

case 'W':

case 'X':

case 'Y':

case 'Z':

outputMessage = outputMessage

+ "9"; //Line 26

}

}

283

Page 284: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Code Example case 'T':

case 'U':

case 'V':

outputMessage = outputMessage

+ "8"; //Line 24

break; //Line 25

case 'W':

case 'X':

case 'Y':

case 'Z':

outputMessage = outputMessage

+ "9"; //Line 26

}

}

284

Page 285: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Code Example else //Line 27

outputMessage = outputMessage

+ "Invalid input"; //Line 28

JOptionPane.showMessageDialog(null, outputMessage,

"Telephone Digit",

JOptionPane.PLAIN_MESSAGE); //Line 29

inputMessage = "Enter another uppercase letter "

+ "to find its corresponding "

+ "telephone digit.\n"

+ "To stop the program enter #.\n"

+ "Enter a letter:"; //Line 30

inputString =

JOptionPane.showInputDialog(inputMessage); //Line 31

letter = inputString.charAt(0); //Line 32

}//end while

System.exit(0); //Line 33

}

}

285

Page 286: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

286

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 287: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Java Introduction

Chapter 6

Graphical User Interface (GUI) and Object-Oriented Design (OOD)

Page 288: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

288

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 289: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

289

Chapter Objectives (continued)

• Discover events and event handlers

• Explore object-oriented design

• Learn how to identify objects, classes, and members of a class

Page 290: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

290

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 291: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

291

Java GUI Components

Page 292: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Code Example// This Java Program determines the area and

// perimeter of a rectangle.

import javax.swing.JOptionPane;

public class Rectangle

{

public static void main(String[] args)

{

double width, length, area, perimeter; //Line 1

String lengthStr, widthStr, outputStr; //Line 2

lengthStr =

JOptionPane.showInputDialog("Enter the length: "); //Line 3

length = Double.parseDouble(lengthStr); //Line 4

widthStr =

JOptionPane.showInputDialog("Enter the width: "); //Line 5

width = Double.parseDouble(widthStr); //Line 6

292

Page 293: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Code Example area = length * width; //Line 7

perimeter = 2 * (length + width); //Line 8

outputStr = "Length: " + length + "\n" +

"Width: " + width + "\n" +

"Area: " + area + " square units\n" +

"Perimeter: " + perimeter + " units\n"; //Line 9

JOptionPane.showMessageDialog(null, outputStr,

"Rectangle",

JOptionPane.INFORMATION_MESSAGE); //Line 10

System.exit(0); //Line 11

}

}

293

Page 294: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

294

Graphical User Interface (GUI) Components (continued)

• GUI components placed in content pane

• GUI components– Windows– Labels– Text areas– Buttons

Page 295: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

295

GUI Components

• Added to content pane of window

• Not added to window itself

• Pixel: picture element

Page 296: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

296

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 297: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

297

class JFrame

• GUI window instance created as instance of JFrame

• Provides various methods to control window attributes

Page 298: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

298

Methods Provided by the class JFrame

Page 299: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

299

Methods Provided by the class Jframe (continued)

Page 300: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

300

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 301: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

301

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 302: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

302

Methods Provided by the class Container

Page 303: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

303

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 304: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

304

class Jlabel (continued)

Page 305: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

305

class JTextField

• Text fields: objects belonging to class JTextField

• To create text field:– Declare reference variable of type JTextField

– Instantiate object

Page 306: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

306

class JTextField (continued)

Page 307: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

307

class JTextField (continued)

Page 308: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

308

class JButton

• Provided to create buttons in Java

• To create button:– Same technique as creating JLabel and JTextField

Page 309: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

309

class Jbutton (continued)

Page 310: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

310

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 311: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

311

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 312: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

312

Rectangle Program: Sample Run

Page 313: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

313

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 314: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

314

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 315: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

//*************************************************************

//

//Java program to convert the temperature between Celsius and

//Fahrenheit.

//*************************************************************

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class TempConversion extends JFrame

{

private JLabel celsiusLabel;

private JLabel fahrenheitLabel;

private JTextField celsiusTF;

private JTextField fahrenheitTF;

private CelsHandler celsiusHandler;

private FahrHandler fahrenheitHandler;

private static final int WIDTH = 500;

private static final int HEIGHT = 50;

private static final double FTOC = 5.0 / 9.0;

private static final double CTOF = 9.0 / 5.0;

private static final int OFFSET = 32;

315

Page 316: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

public TempConversion()

{

setTitle("Temperature Conversion");

Container c = getContentPane();

c.setLayout(new GridLayout(1, 4));

celsiusLabel = new JLabel("Temp in Celsius: ",

SwingConstants.RIGHT);

fahrenheitLabel = new JLabel("Temp in Fahrenheit: ",

SwingConstants.RIGHT);

celsiusTF = new JTextField(7);

fahrenheitTF = new JTextField(7);

c.add(celsiusLabel);

c.add(celsiusTF);

c.add(fahrenheitLabel);

c.add(fahrenheitTF);

celsiusHandler = new CelsHandler();

fahrenheitHandler = new FahrHandler();

celsiusTF.addActionListener(celsiusHandler);

fahrenheitTF.addActionListener(fahrenheitHandler);

316

Page 317: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

setSize(WIDTH, HEIGHT);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setVisible(true);

}

private class CelsHandler implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

double celsius, fahrenheit;

celsius =

Double.parseDouble(celsiusTF.getText());

fahrenheit = celsius * CTOF + OFFSET;

fahrenheitTF.setText(String.format("%.2f",

fahrenheit));

}

}

317

Page 318: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

private class FahrHandler implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

double celsius, fahrenheit;

fahrenheit =

Double.parseDouble(fahrenheitTF.getText());

celsius = (fahrenheit - OFFSET) * FTOC;

celsiusTF.setText(String.format("%.2f",

celsius));

}

}

public static void main(String[] args)

{

TempConversion tempConv = new TempConversion();

}

}

318

Page 319: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

319

Sample Run for TempConversion

Page 320: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

320

Object-Oriented Design

• Simplified methodology1. 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 321: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

321

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 322: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

322

class Rectangle with Data Members and Operations

Page 323: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

323

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 324: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

324

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 325: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

325

Object-Oriented Design Example 2 (continued)

Page 326: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

326

Object-Oriented Design Example 2 (continued)

Page 327: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

327

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 328: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

328

The class Integer

Page 329: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

329

The class Integer (continued)

Page 330: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

330

The class Integer (continued)

Page 331: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

331

The class Integer (continued)

Integer num; num = new Integer(86)

Page 332: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

332

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 333: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

333

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 334: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

334

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 335: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

335

The class Integer (continued)

Page 336: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

336

The class Integer (continued)

Page 337: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

337

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 338: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

338

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 339: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Java Introduction

Chapter 7User-Defined Methods

Page 340: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

340

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 341: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

341

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 342: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

342

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 343: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

343

Predefined Classes (continued)

Page 344: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

344

Predefined Classes (continued)

Page 345: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

345

Predefined Classes (continued)

Page 346: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

346

Predefined Classes (continued)

Page 347: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

347

class Character (Package: java.lang)

Page 348: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

348

class Character (Package: java.lang) (continued)

Page 349: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

349

class Character (Package: java.lang) (continued)

Page 350: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

350Java Introduction

To simplify the use of (public) static methods of a class, Java 5.0 introduces the following import statements:

These are called static import statements. After including such statements in your program, when you use a (public) static method (or any other public static member) of a class, you can omit the name of the class and the dot operator.

350

Page 351: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

351Java Introduction 351

Page 352: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

352Java Introduction 352

Page 353: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

353Java Introduction 353

Page 354: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

354Java Introduction 354

Page 355: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

355

Syntax: Value-Returning Method

Page 356: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

356

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 357: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

357

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 358: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

358

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 359: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

359

Equivalent Method Definitions

public static double larger(double x, double y){ double max;

if (x >= y) max = x; else max = y;

return max;}

Page 360: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

360Java Introduction 360

Page 361: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

361Java Introduction 361

Page 362: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

362

Equivalent Method Definitions (continued)

public static double larger(double x, double y){ if (x >= y) return x; else return y;}

Page 363: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

363

Equivalent Method Definitions (continued)

public static double larger(double x, double y){ if (x >= y) return x; return y;}

Page 364: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

364Java Introduction

The int variable num contains the desired sum to be rolled

364

Page 365: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

365

Palindrome Number

• Palindrome: integer or string that reads the same forward and backward

• The method isPalindrome takes a string as a parameter and returns true if the string is a palindrome, false otherwise

Page 366: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

366

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 367: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

367

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 368: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

368

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 369: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

369

Solution: Largest Numberstatic 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 370: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

370

Sample Run: Largest Number

• Sample Run

Enter 10 numbers:10.5 56.34 73.3 42 22 67 88.55 26 62 11The largest number is 88.55

Page 371: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

371

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 372: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

372

Void Methods with Parameters: Syntax

Page 373: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

373

Void Methods with Parameters: Syntax (continued)

Page 374: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

374

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 375: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

375

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 376: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

376

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 377: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

377

Reference Variables as Parameters: type String

Page 378: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

378

Reference Variables as Parameters: type String (continued)

Page 379: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

379

Reference Variables as Parameters: type String (continued)

Page 380: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

380

Reference Variables as Parameters: type String (continued)

Page 381: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

381Java Introduction

Reference Variables as Parameters: type String (continued)

String str = "Hello"; //Line 5

381

Page 382: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

382Java Introduction

Reference Variables as Parameters: type String (continued)

stringParameter(str); //Line 7

382

Page 383: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

383Java Introduction

Reference Variables as Parameters: type String (continued)

pStr = "Sunny Day"; //Line 14

383

Page 384: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

384

Reference Variables as Parameters: type String (continued)

Variables before the statement in Line 8 executes

Page 385: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

385

• 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 386: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

386Java Introduction 386

Page 387: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

387Java Introduction 387

Page 388: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

388Java Introduction 388

Page 389: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

389Java Introduction 389

Page 390: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

390Java Introduction 390

Page 391: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

391

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 392: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

392Java Introduction

Primitive Type Wrapper Classes as Parameters (continued)

• If we want to pass a String object as a parameter and also change that object, we can use the class StringBuffer

• Java does not provide any class that wraps primitive type values in objects and when passed as parameters changes their values

• If a method returns only one value of a primitive type, then you can write a value-returning method

• If you encounter a situation that requires you to write a method that needs to pass more than one value of a primitive type, then you should design your own classes

• Appendix D provides the definitions of such classes and shows how to use them in a program

392

Page 393: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

393

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 394: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

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

394

Page 395: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

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

395

Page 396: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

396

Scope of an Identifier within a Class (continued)

public static void illegalIdentifierDeclaration(){ int x; //block { double x; //illegal declaration, //x is already declared ... }}

Page 397: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

397

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 398: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

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

398

Page 399: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

399

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 400: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

400

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 401: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

401

Scope Rules: Demonstrated

Page 402: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

402

Scope Rules: Demonstrated (continued)

Page 403: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

403

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 404: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

404

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 405: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

405

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 406: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

406

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 407: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

407

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 408: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

408

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 409: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

409

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 410: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

410

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.04Avg for group 2: 82.01

Programming Example: Data Comparison (continued)

Page 411: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

411

Programming Example: Data Comparison (continued)

Page 412: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

412Java Introduction

• A program may contain a number of methods. In a complex program, usually, when a method is written, it is tested and debugged alone.

• You can write a separate program to test the method. The program that tests a method is called a driver program.

• Before writing the complete program, you could write separate driver programs to make sure that each method is working properly.

412

Page 413: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

413Java Introduction

• Sometimes the results calculated by one method are needed in another method.

• In that case, the method that depends on another method cannot be tested alone.

• A method stub is a method that is not fully coded. • For a void method, a method stub might consist of only a

method header and a set of empty braces, {}. • For a value-returning method it might contain only a return

statement with a plausible return value.

413

Page 414: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

414Java Introduction

• If the problem is large and complex, it must be broken into subproblems, and if a subproblem is still complex, it must further be divided into subproblems.

• The subdivision of a problem should continue to the point where the solution is clear and obvious.

• Once a subproblem is solved, we can continue with the solution of another subproblem and if all the subproblems of a problem are solved, we can continue with the next level.

• Eventually, the overall solution of the problem must be assembled and tested to ensure that the programming code accomplishes the required task.

414

Page 415: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

415Java Introduction

• A Java program is a collection of classes, and a class is a collection of data members and methods.

• Each class and each method must work properly. • To accomplish this, as explained in the previous section, once a

method is written, it can be tested using stubs and drivers. • Since a method can be tested in isolation, it is not necessary to

code all the methods in order. • Once all the methods are written, the overall program must be

tested.

415

Page 416: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

416Java Introduction

• The technique to solve a problem by subdividing into smaller problems is known as divide and conquer and top-down design approach.

• These techniques are suitable and work for many kinds of problems, including most of the problems given in this book and the problems you will encounter as a beginning programmer.

• To simplify the overall solution of a problem that consists of many subproblems, we write and test the code one piece at a time.

• Typically, once a subproblem is solved and the code is tested, it is saved as the first version or a version of the program.

• We continue to add and save the program one piece at a time. Keep in mind that a working program with fewer features is better than a nonworking one with many features.

416

Page 417: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

417

Chapter Summary

• Predefined methods

• User-defined methods– Value-returning methods– Void methods– Formal parameters– Actual parameters

• Flow of execution

Page 418: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

418

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 419: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

419Java Introduction

Chapter Summary (continued)

• Debugging: using drivers and stubs

• Avoiding bugs: one-piece-at-a-time coding

419

Page 420: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

Java Introduction

Chapter 8User-Defined Classes and ADTs

Page 421: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

421

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 422: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

422

Chapter Objectives (continued)

• Examine constructors and finalizers

• Examine the method toString• Learn about the abstract data type (ADT)

Page 423: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

423

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 424: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

424

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 425: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

425

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 426: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

426

Syntax

The general syntax for defining a class is:

Page 427: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

427

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 428: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

428

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 429: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

429

Data Members (Instance Variables)•private int hr; //store hours•private int min; //store minutes•private int sec; //store seconds

class Clock

Page 430: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

430

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 431: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

431

• Two types of constructors- With parameters- Without parameters (default constructor)

Constructors

Page 432: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

432

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 433: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

433

• Default constructor is:- public Clock()

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

class Clock: Constructors

Page 434: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

434

Unified Modeling Language Class Diagrams

Page 435: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

435

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 436: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

436

Variable Declaration and Object Instantiation (continued)

Page 437: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

437

Variable Declaration and Object Instantiation (continued)

Page 438: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

438

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 439: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

439

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 440: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

440

• 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 441: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

441

Assignment Operator: A Precaution (continued)

Page 442: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

442

Definitions of the Constructors and Methods of the class Clock

Page 443: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

443

Definitions of the Constructors and Methods of the class Clock (continued)

Page 444: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

444

Definitions of the Constructors and Methods of the class Clock (continued)

Page 445: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

445

Definitions of the Constructors and Methods of the class Clock (continued)

Page 446: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

446

Definitions of the Constructors and Methods of the class Clock (continued)

Page 447: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

447

Definitions of the Constructors and Methods of the class Clock (continued)

Page 448: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

448

Definitions of the Constructors and Methods of the class Clock (continued)

Page 449: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

449

Definitions of the Constructors and Methods of the class Clock (continued)

Page 450: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

450

Definitions of the Constructors and Methods of the class Clock (continued)

Page 451: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

451

Definitions of the Constructors and Methods of the class Clock (continued)

Page 452: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

452

Definitions of the Constructors and Methods of the class Clock (continued)

Page 453: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

453

Definitions of the Constructors and Methods of the class Clock (continued)

Page 454: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

454

Default Constructor

or

Page 455: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

455

Constructor with Parameters

or

Page 456: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

456

Page 457: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

457

Page 458: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

458

Page 459: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

459

Page 460: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

460

• public value-returning method• Takes no parameters• Returns address of a String object• Output using print, println, printf

methods• Default definition creates String with

name of object’s class name followed by hash code of object

The Method toString

Page 461: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

461

Method toString: class Clock

Page 462: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

462

The Copy Constructor

• Executes when an object is instantiated• Initialized using an existing object • Syntax

Page 463: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

463

The Copy Constructor (continued)

Page 464: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

464

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 465: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

465

• Example 8-5public 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 466: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

466

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 467: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

467

Illustrate illusObject1 = new Illustrate(3); Illustrate illusObject2 = new Illustrate(5);

Static Members of a Class (continued)

Page 468: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

468

Illustrate.incrementY();Illustrate.count++;

Static Members of a Class (continued)

Page 469: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

469

Finalizers

• Automatically execute when class object goes out of scope

• Have no parameters

• Only one finalizer per class

• Name of finalizer: finalize

Page 470: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

470

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 471: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

471

• Before moving to the design phase, a problem must be thoroughly understood so that the focus is on solving the problem.

• Once a class is designed, it must be properly documented. • In order to design the class Clock, first we identified the operations

and determined that each operation must be implemented using a method.

• We then identified the data members and their types. • We also identified which member should be public and which

should be private. • An algorithm must be designed and documented to implement a

method. • Describing the algorithm is not as important as the clarity of the

algorithm.

Page 472: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

472

Page 473: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

473

Page 474: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

474

• You can write the Java code of the class Clock using this specification.

• You can also specify the design of a class as it is shown in the programming example, Candy Machine, of this chapter.

• To become an effective and a good programmer, you must avoid the temptation to skip the design phase.

• It is possible that the first few programs that you write can be coded directly.

• In general, this approach works only for very small programs. • You will spend less time in implementing, debugging, and

maintaining a code that is properly designed and documented.

Page 475: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

475

The Reference this

• Refers to instance variables and methods of a class

• Used to implement cascaded method calls

Page 476: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

476

Inner Classes

• Defined within other classes

• Can be either a complete class definition or anonymous inner class definition

• Used to handle events

Page 477: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

477

Abstract Data Types

• Definition- A data type that specifies the logical properties without the implementation details

Page 478: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

478

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 479: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

479

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 machine2. Let the customer make the selection3. Show the customer the cost of the item selected4. Accept money from the customer5. Release the item

Page 480: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

480

Programming Example: Candy Machine (Input and Output)

• Input: the item selection and the cost of the item

• Output: the selected item

Page 481: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

481

Programming Example: Candy Machine

• Components– Cash register– Dispenser– Machine

Page 482: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

482

Programming Example: Candy Machine (continued)

Page 483: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

483

Programming Example: Candy Machine (continued)

Page 484: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

484

Programming Example: Candy Machine (continued)

Page 485: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

485

Programming Example: Candy Machine (continued)

Page 486: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

486

Programming Example: Candy Machine (continued)

Page 487: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

487

Programming Example: Candy Machine (continued)

Page 488: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

488

Chapter Summary

• Creating classes• Members of a class

– private– protected– public– static

• Implementing classes• Various operations on classes

Page 489: Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving

489

Chapter Summary (continued)

• Constructors

• Finalizers

• Method toString• Abstract data types