Programming Languages: Java Lecture 2 - Columbia...

116
1 1992-2007 Pearson Education, Inc. All rights reserved. Programming Languages: Java Instructor: Omer Boyaci Lecture 2 Control Structures Object-oriented Programming

Transcript of Programming Languages: Java Lecture 2 - Columbia...

Page 1: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

1

1992-2007 Pearson Education, Inc. All rights reserved.

Programming Languages: Java

Instructor: Omer Boyaci

Lecture 2Control StructuresObject-oriented Programming

Page 2: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

2

1992-2007 Pearson Education, Inc. All rights reserved.

Review of if...else and whileIntroductionEssentials of Counter-Controlled Repetition for Repetition Statement Examples Using the for Statement do…while Repetition Statement switch Multiple-Selection Statement break and continue Statements Logical Operators

Page 3: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

3

1992-2007 Pearson Education, Inc. All rights reserved.

Control Statements 2

Page 4: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

4

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 4.3 | if…else double-selection statement UML activity diagram.

if…else double-selection statement

Page 5: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

5

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 4.4 | while repetition statement UML activity diagram.

while repetition statement

Page 6: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

6

1992-2007 Pearson Education, Inc. All rights reserved.

Introduction

• Continue structured-programming discussion– Introduce Java’s remaining control structures

• for, do…while, switch

Page 7: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

7

1992-2007 Pearson Education, Inc. All rights reserved.

Essentials of Counter-Controlled Repetition

• Counter-controlled repetition requires:– Control variable (loop counter)– Initial value of the control variable– Increment/decrement of control variable through each loop– Loop-continuation condition that tests for the final value of

the control variable

Page 8: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

8

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

WhileCounter.java

1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while repetition statement. 3 4 public class WhileCounter

5 {

6 public static void main( String args[] )

7 {

8 int counter = 1; // declare and initialize control variable 9 10 while ( counter <= 10 ) // loop-continuation condition 11 { 12 System.out.printf( "%d ", counter ); 13 ++counter; // increment control variable by 1 14 } // end while 15 16 System.out.println(); // output a newline 17 } // end main 18 } // end class WhileCounter 1 2 3 4 5 6 7 8 9 10

Control-variable name is counter

Control-variable initial value is 1

Condition tests for counter’s final value

Increment for counter

Page 9: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

9

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error

Because floating-point values may be approximate, controlling loops with floating-point variables may result in imprecise counter values and inaccurate termination tests.

Error-Prevention TipControl counting loops with integers.

Page 10: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

10

1992-2007 Pearson Education, Inc. All rights reserved.

for Repetition Statement

• Handles counter-controlled-repetition details

Page 11: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

11

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ForCounter.java

Line 10int counter = 1;

Line 10 counter <= 10;

Line 10 counter++;

1 // Fig. 5.2: ForCounter.java 2 // Counter-controlled repetition with the for repetition statement. 3 4 public class ForCounter

5 {

6 public static void main( String args[] )

7 {

8 // for statement header includes initialization, 9 // loop-continuation condition and increment 10 for ( int counter = 1; counter <= 10; counter++ ) 11 System.out.printf( "%d ", counter ); 12 13 System.out.println(); // output a newline 14 } // end main 15 } // end class ForCounter 1 2 3 4 5 6 7 8 9 10

Control-variable name is counter

Control-variable initial value is 1

Condition tests for counter’s final value

Increment for counter

Page 12: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

12

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error

Using an incorrect relational operator or an incorrect final value of a loop counter in the loop-continuation condition of a repetition statement can cause an off-by-one error.

Page 13: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

13

1992-2007 Pearson Education, Inc. All rights reserved.

Good Programming Practice

Using the final value in the condition of a while or for statement and using the <= relational operator helps avoid off-by-one errors. For a loop that prints the values 1 to 10, the loop-continuation condition should be counter <= 10 rather than counter < 10 (which causes an off-by-one error) or counter < 11 (which is correct). Many programmers prefer so-called zero-based counting, in which to count 10 times, counter would be initialized to zero and the loop-continuation test would be counter < 10.

Page 14: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

14

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 5.3 | for statement header components.

Page 15: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

15

1992-2007 Pearson Education, Inc. All rights reserved.

for Repetition Statement (Cont.)

for ( initialization; loopContinuationCondition; increment )

statement;

can usually be rewritten as:

initialization;while ( loopContinuationCondition )

{ statement; increment;}

Page 16: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

16

1992-2007 Pearson Education, Inc. All rights reserved.

Error-Prevention TipInfinite loops occur when the loop-continuation condition in a repetition statement never becomes false. To prevent this situation in a counter-controlled loop, ensure that the control variable is incremented (or decremented) during each iteration of the loop. In a sentinel-controlled loop, ensure that the sentinel value is eventually input.

Page 17: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

17

1992-2007 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip

Although the value of the control variable can be changed in the body of a for loop, avoid doing so, because this practice can lead to subtle errors.

Page 18: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

18

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 5.4 | UML activity diagram for the for statement in Fig. 5.2.

Page 19: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

19

1992-2007 Pearson Education, Inc. All rights reserved.

Examples Using the for Statement

• Varying control variable in for statement– Vary control variable from 1 to 100 in increments of 1

• for ( int i = 1; i <= 100; i++ )

– Vary control variable from 100 to 1 in increments of –1• for ( int i = 100; i >= 1; i-- )

– Vary control variable from 7 to 77 in increments of 7• for ( int i = 7; i <= 77; i += 7 )

– Vary control variable from 20 to 2 in decrements of 2• for ( int i = 20; i >= 2; i -= 2 )

– Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20• for ( int i = 2; i <= 20; i += 3 )

– Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0• for ( int i = 99; i >= 0; i -= 11 )

Page 20: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

20

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Sum.java

Line 11

1 // Fig. 5.5: Sum.java 2 // Summing integers with the for statement. 3 4 public class Sum

5 {

6 public static void main( String args[] )

7 {

8 int total = 0; // initialize total 9 10 // total even integers from 2 through 20 11 for ( int number = 2; number <= 20; number += 2 ) 12 total += number; 13 14 System.out.printf( "Sum is %d\n", total ); // display results 15 } // end main 16 } // end class Sum Sum is 110

increment number by 2 each iteration

Page 21: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

21

1992-2007 Pearson Education, Inc. All rights reserved.

Examples Using the for Statement (Cont.)

• Initialization and increment expression can be comma-separated lists of expressions

– E.g., lines 11-12 of Fig. 5.5 can be rewritten as

for ( int number = 2; number <= 20; total += number, number += 2 ) ; // empty statement

Page 22: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

22

1992-2007 Pearson Education, Inc. All rights reserved.

Floating-Point Numbers and Type double

• Floating-point numbers– float

– double

• Stores numbers with greater magnitude and precision than float

Page 23: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

23

1992-2007 Pearson Education, Inc. All rights reserved.

Floating-Point Number Precision and Memory Requirements

• float– Single-precision floating-point numbers– Seven significant digits

• double– Double-precision floating-point numbers– Fifteen significant digits

Page 24: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

24

1992-2007 Pearson Education, Inc. All rights reserved.

AccountTest Class to use Class Account

• Format specifier %f– Used to output floating-point numbers– Place a decimal and a number between the percent

sign and the f to specify a precision

Page 25: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

25

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error

Using floating-point numbers in a manner that assumes they are represented precisely can lead to logic errors.

Page 26: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

26

1992-2007 Pearson Education, Inc. All rights reserved.

Interest2.java

Page 27: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

27

1992-2007 Pearson Education, Inc. All rights reserved.

Interest2.java

>java Interest2Year Amount on deposit 1 1,050.00 2 1,102.50 3 1,157.63 4 1,215.51 5 1,276.28 6 1,340.10 7 1,407.10 8 1,477.46 9 1,551.33 10 1,628.89

Page 28: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

28

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Interest.java(1 of 2)

Line 8

Line 13

1 // Fig. 5.6: Interest.java 2 // Compound-interest calculations with for. 3 4 public class Interest

5 {

6 public static void main( String args[] )

7 {

8 double amount; // amount on deposit at end of each year 9 double principal = 1000.0; // initial amount before interest 10 double rate = 0.05; // interest rate 11 12 // display headers 13 System.out.printf( "%s%20s\n", "Year", "Amount on deposit" ); 14

Java treats literal values with decimal points as type double

Second string is right justified and displayed with a field width of 20

Page 29: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

29

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Interest.java

(2 of 2)

Lines 16-23

Line 22

Program output

15 // calculate amount on deposit for each of ten years 16 for ( int year = 1; year <= 10; year++ ) 17 { 18 // calculate new amount for specified year 19 amount = principal * Math.pow( 1.0 + rate, year ); 20 21 // display the year and the amount 22 System.out.printf( "%4d%,20.2f\n", year, amount ); 23 } // end for 24 } // end main 25 } // end class Interest Year Amount on deposit 1 1,050.00 2 1,102.50 3 1,157.63 4 1,215.51 5 1,276.28 6 1,340.10 7 1,407.10 8 1,477.46 9 1,551.33 10 1,628.89

Calculate amount with for statement

Use the comma (,) formatting flag to display the amount with a thousands separator

Page 30: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

30

1992-2007 Pearson Education, Inc. All rights reserved.

Examples Using the for Statement (Cont.)

• Formatting output– Field width

• %,20.2f %4d – Minus sign (-) formatting flag for left justification

• %-4d– Comma (,) formatting flag to output numbers with

grouping separators• %,20.2f

•static method– ClassName.methodName( arguments)

• Math.pow( 1.0 + rate, year )

Page 31: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

31

1992-2007 Pearson Education, Inc. All rights reserved.

do…while Repetition Statement

•do…while statement– Similar to while statement– Tests loop-continuation after performing body of loop

• i.e., loop body always executes at least once

Page 32: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

32

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

DoWhileTest.java

Line 8

Lines 10-14

Program output

1 // Fig. 5.7: DoWhileTest.java 2 // do...while repetition statement. 3 4 public class DoWhileTest

5 {

6 public static void main( String args[] )

7 {

8 int counter = 1; // initialize counter 9 10 do 11 { 12 System.out.printf( "%d ", counter ); 13 ++counter; 14 } while ( counter <= 10 ); // end do...while 15 16 System.out.println(); // outputs a newline 17 } // end main 18 } // end class DoWhileTest 1 2 3 4 5 6 7 8 9 10

Declares and initializes control variable counter

Variable counter’s value is displayed before testing counter’s final value

Page 33: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

33

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 5.8 | do...while repetition statement UML activity diagram.

Page 34: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

34

1992-2007 Pearson Education, Inc. All rights reserved.

switch Multiple-Selection Statement

•switch statement– Used for multiple selections

Page 35: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

35

1992-2007 Pearson Education, Inc. All rights reserved.

GradeBookInitial.java

Page 36: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

36

1992-2007 Pearson Education, Inc. All rights reserved.

Page 37: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

37

1992-2007 Pearson Education, Inc. All rights reserved.

Page 38: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

38

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBookInitial.java

(2 of 2)

Program output

Welcome to the grade book for CS101 Introduction to Java Programming! Enter the integer grades in the range 0-100. Type the end-of-file indicator to terminate input: On UNIX/Linux/Mac OS X type <ctrl> d then press Enter On Windows type <ctrl> z then press Enter 99 92 45 57 63 71 76 85 90 100 ^Z Grade Report: Total of the 10 grades entered is 778 Class average is 77.80 Number of students who received each grade: A: 4 B: 1 C: 2 D: 1 F: 2

Page 39: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

39

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error

Forgetting a break statement when one is needed in a switch is a logic error.

Page 40: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

40

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 5.2

Provide a default case in switch statements. Including a default case focuses you on the need to process exceptional conditions.

Page 41: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

41

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 5.11 | switch multiple-selection statement UML activity diagram with break statements.

Page 42: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

42

1992-2007 Pearson Education, Inc. All rights reserved.

switch Multiple-Selection Statement (Cont.)

• Expression in each case– Constant integral expression

• Combination of integer constants that evaluates to a constant integer value

– Character constant• E.g., ‘A’, ‘7’ or ‘$’

– Constant variable• Declared with keyword final

Page 43: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

43

1992-2007 Pearson Education, Inc. All rights reserved.

break and continue Statements

•break/continue– Alter flow of control

•break statement – Causes immediate exit from control structure

• Used in while, for, do…while or switch statements

•continue statement – Skips remaining statements in loop body– Proceeds to next iteration

• Used in while, for or do…while statements

Page 44: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

44

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

BreakTest.java

Line 9

Lines 11-12

Program output

1 // Fig. 5.12: BreakTest.java 2 // break statement exiting a for statement. 3 public class BreakTest

4 {

5 public static void main( String args[] )

6 {

7 int count; // control variable also used after loop terminates 8

9 for ( count = 1; count <= 10; count++ ) // loop 10 times 10 { 11 if ( count == 5 ) // if count is 5, 12 break; // terminate loop 13 14 System.out.printf( "%d ", count ); 15 } // end for 16 17 System.out.printf( "\nBroke out of loop at count = %d\n", count ); 18 } // end main 19 } // end class BreakTest 1 2 3 4 Broke out of loop at count = 5

Loop 10 timesExit for statement (break)

when count equals 5

Page 45: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

45

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

ContinueTest.java

Line 7

Lines 9-10

Program output

1 // Fig. 5.13: ContinueTest.java 2 // continue statement terminating an iteration of a for statement. 3 public class ContinueTest

4 {

5 public static void main( String args[] )

6 {

7 for ( int count = 1; count <= 10; count++ ) // loop 10 times 8 {

9 if ( count == 5 ) // if count is 5, 10 continue; // skip remaining code in loop 11 12 System.out.printf( "%d ", count ); 13 } // end for 14 15 System.out.println( "\nUsed continue to skip printing 5" ); 16 } // end main 17 } // end class ContinueTest 1 2 3 4 6 7 8 9 10 Used continue to skip printing 5

Loop 10 times

Skip line 12 and proceed to line 7 when count equals 5

Page 46: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

46

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation

Some programmers feel that break and continue violate structured programming. Since the same effects are achievable with structured programming techniques, these programmers do not use break or continue.

Page 47: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

47

1992-2007 Pearson Education, Inc. All rights reserved.

Logical Operators

• Logical operators– Allows for forming more complex conditions– Combines simple conditions

• Java logical operators– && (conditional AND)– || (conditional OR)– & (boolean logical AND)– | (boolean logical inclusive OR)– ^ (boolean logical exclusive OR)– ! (logical NOT)

Page 48: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

48

1992-2007 Pearson Education, Inc. All rights reserved.

5.8 Logical Operators (Cont.)

• Conditional AND (&&) Operator– Consider the following if statement

if ( gender == FEMALE && age >= 65 )

++seniorFemales;– Combined condition is true

• if and only if both simple conditions are true– Combined condition is false

• if either or both of the simple conditions are false

Page 49: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

49

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 5.14 | && (conditional AND) operator truth table.

expression1 expression2 expression1 && expression2 false false False false true False true false False true true True

Page 50: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

50

1992-2007 Pearson Education, Inc. All rights reserved.

Logical Operators (Cont.)

• Conditional OR (||) Operator– Consider the following if statement

if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 )

System.out.println( “Student grade is A” );

– Combined condition is true • if either or both of the simple condition are true

– Combined condition is false • if both of the simple conditions are false

Page 51: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

51

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 5.15 | || (conditional OR) operator truth table.

expression1 expression2 expression1 || expression2 false false false false true true true false true true true true

Page 52: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

52

1992-2007 Pearson Education, Inc. All rights reserved.

Logical Operators (Cont.)

• Short-Circuit Evaluation of Complex Conditions– Parts of an expression containing && or || operators are

evaluated only until it is known whether the condition is true or false

– E.g., ( gender == FEMALE ) && ( age >= 65 )• Stops immediately if gender is not equal to FEMALE

Page 53: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

53

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming ErrorIn expressions using operator &&, a condition—we will call this the dependent condition—may require another condition to be true for the evaluation of the dependent condition to be meaningful. In this case, the dependent condition should be placed after the other condition, or an error might occur. For example, in the expression ( i != 0 ) && ( 10 / i == 2 ), the second condition must appear after the first condition, or a divide-by-zero error might occur.

Page 54: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

54

1992-2007 Pearson Education, Inc. All rights reserved.

Logical Operators (Cont.)

• Boolean Logical AND (&) Operator– Works identically to &&– Except & always evaluate both operands

• Boolean Logical OR (|) Operator – Works identidally to ||– Except | always evaluate both operands

Page 55: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

55

1992-2007 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip

For clarity, avoid expressions with side effects in conditions. The side effects may look clever, but they can make it harder to understand code and can lead to subtle logic errors.

Page 56: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

56

1992-2007 Pearson Education, Inc. All rights reserved.

Logical Operators (Cont.)

• Boolean Logical Exclusive OR (^)– One of its operands is true and the other is false

• Evaluates to true– Both operands are true or both are false

• Evaluates to false

• Logical Negation (!) Operator– Unary operator

Page 57: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

57

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 5.16 | ^ (boolean logical exclusive OR) operator truth table.

expression1 expression2 expression1 ^ expression2 false false false false true true true false true true true false

Page 58: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

58

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 5.17 |! (logical negation, or logical NOT) operator truth table.

expression !expression false true true false

Page 59: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

59

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

LogicalOperators. java

(1 of 3)

Lines 9-13

Lines 16-20

Lines 23-27

1 // Fig. 5.18: LogicalOperators.java 2 // Logical operators. 3 4 public class LogicalOperators

5 {

6 public static void main( String args[] )

7 {

8 // create truth table for && (conditional AND) operator 9 System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n",

10 "Conditional AND (&&)", "false && false", ( false && false ), 11 "false && true", ( false && true ), 12 "true && false", ( true && false ), 13 "true && true", ( true && true ) ); 14 15 // create truth table for || (conditional OR) operator 16 System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", 17 "Conditional OR (||)", "false || false", ( false || false ), 18 "false || true", ( false || true ), 19 "true || false", ( true || false ), 20 "true || true", ( true || true ) ); 21 22 // create truth table for & (boolean logical AND) operator 23 System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", 24 "Boolean logical AND (&)", "false & false", ( false & false ), 25 "false & true", ( false & true ), 26 "true & false", ( true & false ), 27 "true & true", ( true & true ) ); 28

Conditional AND truth table

Conditional OR truth table

Boolean logical AND truth table

Page 60: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

60

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

LogicalOperators. java

(2 of 3)

Lines 30-35

Lines 38-43

Lines 46-47

29 // create truth table for | (boolean logical inclusive OR) operator 30 System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", 31 "Boolean logical inclusive OR (|)", 32 "false | false", ( false | false ), 33 "false | true", ( false | true ), 34 "true | false", ( true | false ), 35 "true | true", ( true | true ) ); 36 37 // create truth table for ^ (boolean logical exclusive OR) operator 38 System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", 39 "Boolean logical exclusive OR (^)", 40 "false ^ false", ( false ^ false ), 41 "false ^ true", ( false ^ true ), 42 "true ^ false", ( true ^ false ), 43 "true ^ true", ( true ^ true ) ); 44 45 // create truth table for ! (logical negation) operator 46 System.out.printf( "%s\n%s: %b\n%s: %b\n", "Logical NOT (!)", 47 "!false", ( !false ), "!true", ( !true ) ); 48 } // end main 49 } // end class LogicalOperators

Boolean logical inclusive OR truth table

Boolean logical exclusive OR truth table

Logical negation truth table

Page 61: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

61

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

LogicalOperators. java

(3 of 3)

Program output

Conditional AND (&&) false && false: false false && true: false true && false: false true && true: true Conditional OR (||) false || false: false false || true: true true || false: true true || true: true Boolean logical AND (&) false & false: false false & true: false true & false: false true & true: true Boolean logical inclusive OR (|) false | false: false false | true: true true | false: true true | true: true Boolean logical exclusive OR (^) false ^ false: false false ^ true: true true ^ false: true true ^ true: false Logical NOT (!) !false: true !true: false

Page 62: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

62

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 5.19 | Precedence/associativity of the operators discussed so far.

Operators Associativity Type ++ -- right to left unary postfix ++ - + - ! (type) right to left unary prefix * / % left to right multiplicative + - left to right additive < <= > >= left to right relational == != left to right equality & left to right boolean logical AND ^ left to right boolean logical exclusive OR | left to right boolean logical inclusive OR && left to right conditional AND || left to right conditional OR ?: right to left conditional = += -= *= /= %= right to left assignment

Page 63: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

63

1992-2007 Pearson Education, Inc. All rights reserved.

Structured Programming Summary

• Sequence structure– “built-in” to Java

• Selection structure– if, if…else and switch

• Repetition structure– while, do…while and for

Page 64: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

64

1992-2007 Pearson Education, Inc. All rights reserved.

Introduction to Classes and Objects

Page 65: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

65

1992-2007 Pearson Education, Inc. All rights reserved.

OBJECTIVESWe will cover: What classes, objects, methods and instance variables

are. How to declare a class and use it to create an object. How to declare methods in a class to implement the

class’s behaviors. How to declare instance variables in a class to

implement the class’s attributes. How to call an object’s method to make that method

perform its task. The differences between instance variables of a class

and local variables of a method. How to use a constructor to ensure that an object’s

data is initialized when the object is created. The differences between primitive and reference types.

Page 66: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

66

1992-2007 Pearson Education, Inc. All rights reserved.

Classes, Objects, Methods and Instance Variables Declaring a Class with a Method and Instantiating an Object ofa Class Declaring a Method with a Parameter Instance Variables, set Methods and get Methods Primitive Types vs. Reference Types Initializing Objects with Constructors Floating-Point Numbers and Type double

Page 67: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

67

1992-2007 Pearson Education, Inc. All rights reserved.

Classes, Objects, Methods and Instance Variables

• Class provides one or more methods• Method represents task in a program

– Describes the mechanisms that actually perform its tasks

– Hides from its user the complex tasks that it performs

– Method call tells method to perform its task

Page 68: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

68

1992-2007 Pearson Education, Inc. All rights reserved.

Classes, Objects, Methods and Instance Variables (Cont.)

• Classes contain one or more attributes– Specified by instance variables– Carried with the object as it is used

Page 69: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

69

1992-2007 Pearson Education, Inc. All rights reserved.

Declaring a Class with a Method and Instantiating an Object of a Class

• Each class declaration that begins with keyword public must be stored in a file that has the same name as the class and ends with the .java file-name extension.

Page 70: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

70

1992-2007 Pearson Education, Inc. All rights reserved.

Class GradeBook

• keyword public is an access modifier • Class declarations include:

– Access modifier– Keyword class– Pair of left and right braces

public class GradeBook {}

Page 71: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

71

1992-2007 Pearson Education, Inc. All rights reserved.

Class GradeBook

• Method declarations– Keyword public indicates method is available to

public– Keyword void indicates no return type– Access modifier, return type, name of method and

parentheses comprise method header

public static void main( String args[] ){}

Page 72: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

72

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error 3.1

Declaring more than one public class in the same file is a compilation error.

Page 73: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

73

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBook.java

1 // Fig. 3.1: GradeBook.java 2 // Class declaration with one method. 3

4 public class GradeBook

5 {

6 // display a welcome message to the GradeBook user 7 public void displayMessage()

8 {

9 System.out.println( "Welcome to the Grade Book!" );

10 } // end method displayMessage 11

12 } // end class GradeBook

Print line of text to output

Page 74: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

74

1992-2007 Pearson Education, Inc. All rights reserved.

Class GradeBookTest

• Java is extensible– Programmers can create new classes

• Class instance creation expression– Keyword new– Then name of class to create and parentheses

• Calling a method– Object name, then dot separator (.)– Then method name and parentheses

Page 75: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

75

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBookTest.java

1 // Fig. 3.2: GradeBookTest.java 2 // Create a GradeBook object and call its displayMessage method. 3

4 public class GradeBookTest

5 {

6 // main method begins program execution 7 public static void main( String args[] )

8 {

9 // create a GradeBook object and assign it to myGradeBook 10 GradeBook myGradeBook = new GradeBook();

11

12 // call myGradeBook's displayMessage method 13 myGradeBook.displayMessage();

14 } // end main 15

16 } // end class GradeBookTest Welcome to the Grade Book!

Use class instance creation expression to create object of class

GradeBook

Call method displayMessage using GradeBook object

Page 76: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

76

1992-2007 Pearson Education, Inc. All rights reserved.

Compiling an Application with Multiple Classes

• Compiling multiple classes– List each .java file in the compilation command and

separate them with spaces– Compile with *.java to compile all .java files in that

directory

Page 77: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

77

1992-2007 Pearson Education, Inc. All rights reserved.

UML Class Diagram for Class GradeBook• UML class diagrams

– Top compartment contains name of the class– Middle compartment contains class’s attributes or

instance variables– Bottom compartment contains class’s operations or

methods• Plus sign indicates public methods

Fig. 3.3 | UML class diagram indicating that class GradeBook has a public displayMessage operation.

Page 78: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

78

1992-2007 Pearson Education, Inc. All rights reserved.

Declaring a Method with a Parameter

• Method parameters– Additional information passed to a method– Supplied in the method call with arguments

Page 79: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

79

1992-2007 Pearson Education, Inc. All rights reserved.

Declaring a Method with a Parameter

•Scanner methods– nextLine reads next line of input– next reads next word of input

Page 80: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

80

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBook.java

1 // Fig. 3.4: GradeBook.java 2 // Class declaration with a method that has a parameter. 3

4 public class GradeBook

5 {

6 // display a welcome message to the GradeBook user 7 public void displayMessage( String courseName )

8 {

9 System.out.printf( "Welcome to the grade book for\n%s!\n",

10 courseName );

11 } // end method displayMessage 12

13 } // end class GradeBook

Call printf method with courseName argument

Page 81: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

81

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBookTest.java

1 // Fig. 3.5: GradeBookTest.java 2 // Create GradeBook object and pass a String to 3 // its displayMessage method. 4 import java.util.Scanner; // program uses Scanner 5 6 public class GradeBookTest

7 {

8 // main method begins program execution 9 public static void main( String args[] )

10 { 11 // create Scanner to obtain input from command window 12 Scanner input = new Scanner( System.in ); 13 14 // create a GradeBook object and assign it to myGradeBook 15 GradeBook myGradeBook = new GradeBook(); 16 17 // prompt for and input course name 18 System.out.println( "Please enter the course name:" ); 19 String nameOfCourse = input.nextLine(); // read a line of text 20 System.out.println(); // outputs a blank line 21 22 // call myGradeBook's displayMessage method 23 // and pass nameOfCourse as an argument 24 myGradeBook.displayMessage( nameOfCourse ); 25 } // end main 26 27 } // end class GradeBookTest Please enter the course name: CS101 Introduction to Java Programming Welcome to the grade book for CS101 Introduction to Java Programming!

Call nextLine method to read a line of input

Call displayMessage with an argument

Page 82: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

82

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering Observation

Normally, objects are created with new. One exception is a string literal that is contained in quotes, such as "hello". String literals are references to String objects that are implicitly created by Java.

Page 83: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

83

1992-2007 Pearson Education, Inc. All rights reserved.

More on Arguments and Parameters

• Parameters specified in method’s parameter list– Part of method header– Uses a comma-separated list

Page 84: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

84

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error

A compilation error occurs if the number of arguments in a method call does not match the number of parameters in the method declaration.

Page 85: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

85

1992-2007 Pearson Education, Inc. All rights reserved.

Common Programming Error

A compilation error occurs if the types of the arguments in a method call are not consistent with the types of the corresponding parameters in the method declaration.

Page 86: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

86

1992-2007 Pearson Education, Inc. All rights reserved.

Updated UML Class Diagram for Class GradeBook

• UML class diagram– Parameters specified by parameter name followed by a

colon and parameter type

Fig. 3.6 | UML class diagram indicating that class GradeBook has a displayMessage operation with a courseName parameter of UML type String.

Page 87: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

87

1992-2007 Pearson Education, Inc. All rights reserved.

Notes on Import Declarations

•java.lang is implicitly imported into every program

• Default package– Contains classes compiled in the same directory– Implicitly imported into source code of other files in

directory• Imports unnecessary if fully-qualified names

are used

Page 88: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

88

1992-2007 Pearson Education, Inc. All rights reserved.

Instance Variables, set Methods and get Methods

• Variables declared in the body of method– Called local variables– Can only be used within that method

• Variables declared in a class declaration– Called fields or instance variables– Each object of the class has a separate instance of

the variable

Page 89: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

89

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBook.java

1 // Fig. 3.7: GradeBook.java 2 // GradeBook class that contains a courseName instance variable 3 // and methods to set and get its value. 4 5 public class GradeBook

6 {

7 private String courseName; // course name for this GradeBook 8 9 // method to set the course name 10 public void setCourseName( String name ) 11 { 12 courseName = name; // store the course name 13 } // end method setCourseName 14 15 // method to retrieve the course name 16 public String getCourseName() 17 { 18 return courseName; 19 } // end method getCourseName 20 21 // display a welcome message to the GradeBook user 22 public void displayMessage() 23 { 24 // this statement calls getCourseName to get the 25 // name of the course this GradeBook represents 26 System.out.printf( "Welcome to the grade book for\n%s!\n", 27 getCourseName() ); 28 } // end method displayMessage 29 30 } // end class GradeBook

Instance variable courseName

set method for courseName

get method for courseName

Call get method

Page 90: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

90

1992-2007 Pearson Education, Inc. All rights reserved.

Access Modifiers public and private

• private keyword– Used for most instance variables– private variables and methods are accessible only

to methods of the class in which they are declared– Declaring instance variables private is known as

data hiding• Return type

– Indicates item returned by method– Declared in method header

Page 91: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

91

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering ObservationPrecede every field and method declaration with an access modifier. As a rule of thumb, instance variables should be declared private and methods should be declared public. (We will see that it is appropriate to declare certain methods private, if they will be accessed only by other methods of the class.)

Page 92: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

92

1992-2007 Pearson Education, Inc. All rights reserved.

Good Programming PracticeWe prefer to list the fields of a class first, so that, as you read the code, you see the names and types of the variables before you see them used in the methods of the class. It is possible to list the class’s fields anywhere in the class outside its method declarations, but scattering them tends to lead to hard-to-read code.

Page 93: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

93

1992-2007 Pearson Education, Inc. All rights reserved.

GradeBookTest Class That Demonstrates Class GradeBook

• Default initial value– Provided for all fields not initialized– Equal to null for Strings

Page 94: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

94

1992-2007 Pearson Education, Inc. All rights reserved.

set and get methods

•private instance variables– Cannot be accessed directly by clients of the object– Use set methods to alter the value– Use get methods to retrieve the value

Page 95: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

95

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBookTest.java

(1 of 2)

1 // Fig. 3.8: GradeBookTest.java 2 // Create and manipulate a GradeBook object. 3 import java.util.Scanner; // program uses Scanner 4 5 public class GradeBookTest

6 {

7 // main method begins program execution 8 public static void main( String args[] )

9 {

10 // create Scanner to obtain input from command window 11 Scanner input = new Scanner( System.in ); 12 13 // create a GradeBook object and assign it to myGradeBook 14 GradeBook myGradeBook = new GradeBook(); 15 16 // display initial value of courseName 17 System.out.printf( "Initial course name is: %s\n\n", 18 myGradeBook.getCourseName() ); 19

Call get method for courseName

Page 96: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

96

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBookTest.java

(2 of 2)

20 // prompt for and read course name 21 System.out.println( "Please enter the course name:" );

22 String theName = input.nextLine(); // read a line of text 23 myGradeBook.setCourseName( theName ); // set the course name 24 System.out.println(); // outputs a blank line 25

26 // display welcome message after specifying course name 27 myGradeBook.displayMessage();

28 } // end main 29

30 } // end class GradeBookTest Initial course name is: null Please enter the course name: CS101 Introduction to Java Programming Welcome to the grade book for CS101 Introduction to Java Programming!

Call set method for courseName

Call displayMessage

Page 97: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

97

1992-2007 Pearson Education, Inc. All rights reserved.

GradeBook’s UML Class Diagram with an Instance Variable and set and get Methods

• Attributes– Listed in middle compartment– Attribute name followed by colon followed by

attribute type• Return type of a method

– Indicated with a colon and return type after the parentheses after the operation name

Fig. 3.9 | UML class diagram indicating that class GradeBook has a courseName attribute of UML type String and three operations—setCourseName (with a name parameter of UML type String), getCourseName (returns UML type String) and displayMessage.

Page 98: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

98

1992-2007 Pearson Education, Inc. All rights reserved.

Primitive Types vs. Reference Types

• Types in Java– Primitive

• boolean, byte, char, short, int, long, float, double

– Reference (sometimes called nonprimitive types)• Objects• Default value of null• Used to invoke an object’s methods

Page 99: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

99

1992-2007 Pearson Education, Inc. All rights reserved.

Software Engineering ObservationA variable’s declared type (e.g., int, double or GradeBook) indicates whether the variable is of a primitive or a reference type. If a variable’s type is not one of the eight primitive types, then it is a reference type. For example, Account account1 indicates that account1 is a reference to an Account object).

Page 100: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

100

1992-2007 Pearson Education, Inc. All rights reserved.

Initializing Objects with Constructors

• Constructors– Initialize an object of a class– Java requires a constructor for every class– Java will provide a default no-argument constructor

if none is provided– Called when keyword new is followed by the class

name and parentheses

Page 101: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

101

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBook.java

(1 of 2)

1 // Fig. 3.10: GradeBook.java 2 // GradeBook class with a constructor to initialize the course name. 3

4 public class GradeBook

5 {

6 private String courseName; // course name for this GradeBook 7

8 // constructor initializes courseName with String supplied as argument 9 public GradeBook( String name )

10 {

11 courseName = name; // initializes courseName 12 } // end constructor 13

14 // method to set the course name 15 public void setCourseName( String name )

16 {

17 courseName = name; // store the course name 18 } // end method setCourseName 19

20 // method to retrieve the course name 21 public String getCourseName()

22 {

23 return courseName;

24 } // end method getCourseName

Constructor to initialize courseName variable

Page 102: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

102

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBook.java

(2 of 2)

25

26 // display a welcome message to the GradeBook user 27 public void displayMessage()

28 {

29 // this statement calls getCourseName to get the 30 // name of the course this GradeBook represents 31 System.out.printf( "Welcome to the grade book for\n%s!\n",

32 getCourseName() );

33 } // end method displayMessage 34

35 } // end class GradeBook

Page 103: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

103

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBookTest.java

1 // Fig. 3.11: GradeBookTest.java 2 // GradeBook constructor used to specify the course name at the 3 // time each GradeBook object is created. 4

5 public class GradeBookTest

6 {

7 // main method begins program execution 8 public static void main( String args[] )

9 {

10 // create GradeBook object 11 GradeBook gradeBook1 = new GradeBook(

12 "CS101 Introduction to Java Programming" );

13 GradeBook gradeBook2 = new GradeBook(

14 "CS102 Data Structures in Java" );

15

16 // display initial value of courseName for each GradeBook 17 System.out.printf( "gradeBook1 course name is: %s\n",

18 gradeBook1.getCourseName() );

19 System.out.printf( "gradeBook2 course name is: %s\n",

20 gradeBook2.getCourseName() );

21 } // end main 22

23 } // end class GradeBookTest gradeBook1 course name is: CS101 Introduction to Java Programming gradeBook2 course name is: CS102 Data Structures in Java

Call constructor to create first grade book object

Create second grade book object

Page 104: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

104

1992-2007 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip

Unless default initialization of your class’s instance variables is acceptable, provide a constructor to ensure that your class’s instance variables are properly initialized with meaningful values when each new object of your class is created.

Page 105: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

105

1992-2007 Pearson Education, Inc. All rights reserved.

Adding the Constructor to Class GradeBookTest’s UML Class Diagram

• UML class diagram– Constructors go in third compartment– Place “<<constructor>>” before constructor name– By convention, place constructors first in their

compartment

Fig. 3.12 | UML class diagram indicating that class GradeBook has a constructor that has a name parameter of UML type String.

Page 106: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

106

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

Account.java

1 // Fig. 3.13: Account.java 2 // Account class with a constructor to 3 // initialize instance variable balance. 4 5 public class Account

6 {

7 private double balance; // instance variable that stores the balance 8 9 // constructor 10 public Account( double initialBalance ) 11 { 12 // validate that initialBalance is greater than 0.0; 13 // if it is not, balance is initialized to the default value 0.0 14 if ( initialBalance > 0.0 ) 15 balance = initialBalance; 16 } // end Account constructor 17 18 // credit (add) an amount to the account 19 public void credit( double amount ) 20 { 21 balance = balance + amount; // add amount to balance 22 } // end method credit 23 24 // return the account balance 25 public double getBalance() 26 { 27 return balance; // gives the value of balance to the calling method 28 } // end method getBalance 29 30 } // end class Account

double variable balance

Page 107: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

107

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

AccountTest.java

(1 of 3)

1 // Fig. 3.14: AccountTest.java 2 // Create and manipulate an Account object. 3 import java.util.Scanner;

4

5 public class AccountTest

6 {

7 // main method begins execution of Java application 8 public static void main( String args[] )

9 {

10 Account account1 = new Account( 50.00 ); // create Account object 11 Account account2 = new Account( -7.53 ); // create Account object 12

13 // display initial balance of each object 14 System.out.printf( "account1 balance: $%.2f\n",

15 account1.getBalance() );

16 System.out.printf( "account2 balance: $%.2f\n\n",

17 account2.getBalance() );

18

Page 108: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

108

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

AccountTest.java

19 // create Scanner to obtain input from command window 20 Scanner input = new Scanner( System.in );

21 double depositAmount; // deposit amount read from user 22

23 System.out.print( "Enter deposit amount for account1: " ); // prompt 24 depositAmount = input.nextDouble(); // obtain user input 25 System.out.printf( "\nadding %.2f to account1 balance\n\n",

26 depositAmount );

27 account1.credit( depositAmount ); // add to account1 balance 28

29 // display balances 30 System.out.printf( "account1 balance: $%.2f\n",

31 account1.getBalance() );

32 System.out.printf( "account2 balance: $%.2f\n\n",

33 account2.getBalance() );

34

35 System.out.print( "Enter deposit amount for account2: " ); // prompt 36 depositAmount = input.nextDouble(); // obtain user input 37 System.out.printf( "\nadding %.2f to account2 balance\n\n",

38 depositAmount );

39 account2.credit( depositAmount ); // add to account2 balance 40

AccountTest.java

(2 of 3)Input a double value

Input a double value

Page 109: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

109

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

AccountTest.java

41 // display balances 42 System.out.printf( "account1 balance: $%.2f\n",

43 account1.getBalance() );

44 System.out.printf( "account2 balance: $%.2f\n",

45 account2.getBalance() );

46 } // end main 47

48 } // end class AccountTest account1 balance: $50.00 account2 balance: $0.00 Enter deposit amount for account1: 25.53 adding 25.53 to account1 balance account1 balance: $75.53 account2 balance: $0.00 Enter deposit amount for account2: 123.45 adding 123.45 to account2 balance account1 balance: $75.53 account2 balance: $123.45

AccountTest.java

(3 of 3)Output a double value

Page 110: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

110

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 3.15 | UML class diagram indicating that class Account has a private balance attribute of UML type Double, a constructor (with a parameter of UML type Double) and two public operations—credit (with an amount parameter of UML type Double) and

getBalance (returns UML type Double).

Page 111: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

111

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBookTest.java

(1 of 2)

Lines 13-15

1 // Fig. 5.10: GradeBookTest.java 2 // Create GradeBook object, input grades and display grade report. 3 4 public class GradeBookTest

5 {

6 public static void main( String args[] )

7 {

8 // create GradeBook object myGradeBook and 9 // pass course name to constructor 10 GradeBook myGradeBook = new GradeBook( 11 "CS101 Introduction to Java Programming" ); 12 13 myGradeBook.displayMessage(); // display welcome message 14 myGradeBook.inputGrades(); // read grades from user 15 myGradeBook.displayGradeReport(); // display report based on grades 16 } // end main 17 } // end class GradeBookTest

Call GradeBook public methods to count grades

Page 112: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

112

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBook.java

(1 of 5)

Lines 8-14

1 // Fig. 5.9: GradeBook.java 2 // GradeBook class uses switch statement to count A, B, C, D and F grades. 3 import java.util.Scanner; // program uses class Scanner 4 5 public class GradeBook

6 {

7 private String courseName; // name of course this GradeBook represents 8 private int total; // sum of grades 9 private int gradeCounter; // number of grades entered 10 private int aCount; // count of A grades 11 private int bCount; // count of B grades 12 private int cCount; // count of C grades 13 private int dCount; // count of D grades 14 private int fCount; // count of F grades 15 16 // constructor initializes courseName; 17 // int instance variables are initialized to 0 by default 18 public GradeBook( String name ) 19 { 20 courseName = name; // initializes courseName 21 } // end constructor 22 23 // method to set the course name 24 public void setCourseName( String name ) 25 { 26 courseName = name; // store the course name 27 } // end method setCourseName 28

Page 113: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

113

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBook.java

(2 of 5)

Lines 50-54

29 // method to retrieve the course name 30 public String getCourseName() 31 { 32 return courseName; 33 } // end method getCourseName 34 35 // display a welcome message to the GradeBook user 36 public void displayMessage() 37 { 38 // getCourseName gets the name of the course 39 System.out.printf( "Welcome to the grade book for\n%s!\n\n", 40 getCourseName() ); 41 } // end method displayMessage 42 43 // input arbitrary number of grades from user 44 public void inputGrades() 45 { 46 Scanner input = new Scanner( System.in ); 47 48 int grade; // grade entered by user 49 50 System.out.printf( "%s\n%s\n %s\n %s\n", 51 "Enter the integer grades in the range 0-100.", 52 "Type the end-of-file indicator to terminate input:", 53 "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter", 54 "On Windows type <ctrl> z then press Enter" ); 55

Display prompt

Page 114: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

114

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBook.java

(3 of 5)

Line 57

Line 72 controlling expression

Lines 72-94

56 // loop until user enters the end-of-file indicator 57 while ( input.hasNext() ) 58 { 59 grade = input.nextInt(); // read grade 60 total += grade; // add grade to total 61 ++gradeCounter; // increment number of grades 62 63 // call method to increment appropriate counter 64 incrementLetterGradeCounter( grade ); 65 } // end while 66 } // end method inputGrades 67 68 // add 1 to appropriate counter for specified grade 69 public void incrementLetterGradeCounter( int numericGrade ) 70 { 71 // determine which grade was entered 72 switch ( grade / 10 ) 73 { 74 case 9: // grade was between 90 75 case 10: // and 100 76 ++aCount; // increment aCount 77 break; // necessary to exit switch 78 79 case 8: // grade was between 80 and 89 80 ++bCount; // increment bCount 81 break; // exit switch 82

Loop condition uses method hasNext to determine whether there is more data to input

switch statement determines which case label to execute,

depending on controlling expression

(grade / 10 ) is controlling expression

Page 115: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

115

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBook.java

(4 of 5)

Line 91 default case

83 case 7: // grade was between 70 and 79 84 ++cCount; // increment cCount 85 break; // exit switch 86 87 case 6: // grade was between 60 and 69 88 ++dCount; // increment dCount 89 break; // exit switch 90 91 default: // grade was less than 60 92 ++fCount; // increment fCount 93 break; // optional; will exit switch anyway 94 } // end switch 95 } // end method incrementLetterGradeCounter 96 97 // display a report based on the grades entered by user 98 public void displayGradeReport() 99 { 100 System.out.println( "\nGrade Report:" ); 101 102 // if user entered at least one grade... 103 if ( gradeCounter != 0 ) 104 { 105 // calculate average of all grades entered 106 double average = (double) total / gradeCounter; 107

default case for grade less than 60

Page 116: Programming Languages: Java Lecture 2 - Columbia Universityboyaci/graphics/slides/Java_Lecture_2.pdf1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition with the while

116

1992-2007 Pearson Education, Inc. All rights reserved.

Outline

GradeBook.java

(5 of 5)

108 // output summary of results 109 System.out.printf( "Total of the %d grades entered is %d\n", 110 gradeCounter, total ); 111 System.out.printf( "Class average is %.2f\n", average ); 112 System.out.printf( "%s\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n", 113 "Number of students who received each grade:", 114 "A: ", aCount, // display number of A grades 115 "B: ", bCount, // display number of B grades 116 "C: ", cCount, // display number of C grades 117 "D: ", dCount, // display number of D grades 118 "F: ", fCount ); // display number of F grades 119 } // end if 120 else // no grades were entered, so output appropriate message 121 System.out.println( "No grades were entered" ); 122 } // end method displayGradeReport 123 } // end class GradeBook