2005 pearson education, inc. all rights reserved. 1 a class a class is the blueprint from which...

60
1 2005 Pearson Education, Inc. All rights rese A class A class is the blueprint from which objects are generated. In other words, if we have six cars we do not need to define a car six times. We will define a car once (in a class) and then generate as many objects as we want from this class blueprint.

Upload: sophie-patterson

Post on 13-Dec-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

1

2005 Pearson Education, Inc. All rights reserved.

A class

• A class is the blueprint from which objects are generated. In other words, if we have six cars we do not need to define a car six times. We will define a car once (in a class) and then generate as many objects as we want from this class blueprint.

2

2005 Pearson Education, Inc. All rights reserved.

Classes, Objects, Methods and Instance Variables

• Class provides one or more methods

• Method represents task in a program

• Classes contain one or more attributes (data members in C++)

– Specified by instance variables

– Carried with the object as it is used

Manipulating Numbers

• In Java, to add two numbers x and y, we writex + y

• But before the actual addition of the two numbers takes place, we must declare their data type. If x and y are integers, we write

int x, y;

orint x;int y;

Variables

• When the declaration is made, memory space is allocated to store the values of x and y.

• x and y are called variables. A variable has three properties:

– A memory location to store the value,

– The type of data stored in the memory location, and

– The name used to refer to the memory location.

• Sample variable declarations:int x;int v, w, y;

Numerical Data Types

• There are six numerical data types: byte, short, int, long, float, and double.

• Sample variable declarations:

int i, j, k;float numberOne, numberTwo;long bigInteger;double bigNumber;

• At the time a variable is declared, it also can be initialized. For example, we may initialize the integer variables count and height to 10 and 34 as

int count = 10, height = 34;

Data Type Precisions

The six data types differ in the precision of values they can store in memory.

Assignment Statements

• We assign a value to a variable using an assignment statements.

• The syntax is

<variable> = <expression> ;• Examples:

sum = firstNumber + secondNumber;avg = (one + two + three) / 3.0;

Constants

• We can change the value of a variable. If we want the value to remain the same, we use a constant.

final double PI = 3.14159;final int MONTH_IN_YEAR = 12;final short FARADAY_CONSTANT = 23060;

These are constants, also called named constant.

These are constants, also called named constant.

The reserved word final is used to declare constants.

The reserved word final is used to declare constants.

These are called literal constant.

These are called literal constant.

Primitive Data Declaration and Assignments

Code State of Memory

int firstNumber, secondNumber;firstNumber = 234;secondNumber = 87;

AAint firstNumber, secondNumber;int firstNumber, secondNumber;

BBfirstNumber = 234;firstNumber = 234;secondNumber = 87;secondNumber = 87;

int firstNumber, secondNumber;int firstNumber, secondNumber;firstNumber = 234;firstNumber = 234;secondNumber = 87;secondNumber = 87;

firstNumber

secondNumber

A. A. Variables are allocated in memory.

A. A. Variables are allocated in memory.

B. B. Values are assigned to variables.

B. B. Values are assigned to variables.

234

87

Assigning Numerical Data

Code State of Memory

int number;int number;number = 237;number = 237;number = 35;number = 35; number

A. A. The variable is allocated in memory.

A. A. The variable is allocated in memory.

B. B. The value 237237 is assigned to numbernumber.

B. B. The value 237237 is assigned to numbernumber.

237

int number;int number;

number = 237;number = 237;

number = 35;number = 35;

AAint number;int number;

BBnumber = 237;number = 237;

CCnumber = 35;number = 35;

C. C. The value 3535 overwrites the

previous value 237.237.

C. C. The value 3535 overwrites the

previous value 237.237.

35

Assigning Objects

Code State of Memory

Customer var;Customer var;var = new Customer( );var = new Customer( );var = new Customer( );var = new Customer( );

var

A. A. The variable is allocated in memory.

A. A. The variable is allocated in memory.Customer var;Customer var;

var = new Customer( );var = new Customer( );

var = new Customer( );var = new Customer( );

AA

Customer var;Customer var;BB

var = new Customer( );var = new Customer( );

CC

var = new Customer( );var = new Customer( );B. B. The reference to the

new object is assigned to varvar.

B. B. The reference to the new object is assigned to varvar.

CustomerCustomer

C. C. The reference to another object overwrites the reference in var.var.

C. C. The reference to another object overwrites the reference in var.var.

CustomerCustomer

Having Two References to a Single Object

Code State of Memory

Customer clemens, twain;Customer clemens, twain;clemens = new Customer( );clemens = new Customer( );twain = clemens;twain = clemens;

Customer clemens, twain,Customer clemens, twain,

clemens = new Customer( );clemens = new Customer( );

twain = clemens;twain = clemens;

AA

Customer clemens, twain;Customer clemens, twain; BB

clemens = new Customer( );clemens = new Customer( );

CC

twain = clemens;twain = clemens;

A. A. Variables are allocated in memory.

A. A. Variables are allocated in memory.

clemens

twain

B. B. The reference to the new object is assigned to clemensclemens.

B. B. The reference to the new object is assigned to clemensclemens.

CustomerCustomer

C. C. The reference in clemensclemens is assigned to

customer.customer.

C. C. The reference in clemensclemens is assigned to

customer.customer.

Object Creation

myWindow = new JFrame ( ) ;

MoreExamples

customer = new Customer( );jon = new Student(“John Java”);car1 = new Vehicle( );

Object NameName of the object we are creating here.

Object NameName of the object we are creating here.

Class NameAn instance of this class is created.

Class NameAn instance of this class is created.

ArgumentNo arguments are used here.

ArgumentNo arguments are used here.

Declaration vs. Creation

Customer customer;

customer = new Customer( );

Customer customer;

customer = new Customer( );

1. The identifier customer is declared and space is allocated in memory.

1. The identifier customer is declared and space is allocated in memory.

2. A Customer object is created and the identifier customer is set to refer to it.

2. A Customer object is created and the identifier customer is set to refer to it.

1

2

customer

1

: Customer2

State-of-Memory vs. Program

customer

: Customer

State-of-MemoryNotation

customer : Customer

Program DiagramNotation

Class NameClass NameObject NameObject Name

Name vs. Objects

Customer customer;

customer = new Customer( );

customer = new Customer( );

Customer customer;

customer

customer = new Customer( );

customer = new Customer( );

: Customer : CustomerCreated with the first new.

Created with the first new.

Created with the second new. Reference to the first Customer object is lost.

Created with the second new. Reference to the first Customer object is lost.

Sending a Message

myWindow . setVisible ( true ) ;

MoreExamples

account.deposit( 200.0 );student.setName(“john”);car1.startEngine( );

Object NameName of the object to which we are sending a message.

Object NameName of the object to which we are sending a message.

Method NameThe name of the message we are sending.

Method NameThe name of the message we are sending.

ArgumentThe argument we are passing with the message.

ArgumentThe argument we are passing with the message.

JFrame myWindow;

myWindow = new JFrame( );

myWindow.setSize(300, 200);

myWindow.setTitle (“My First Java Program”);

myWindow.setVisible(true);

Execution Flow

myWindow.setSize(300, 200);

Jframe myWindow;

myWindow

myWindow.setVisible(true);

State-of-Memory Diagram

: JFrame

width

height

title

visible

200

My First Java …

300

true

myWindow = new JFrame( );

myWindow.setTitle (“My First Java Program”);

The diagram shows only four of the many data members of a JFrame object.

The diagram shows only four of the many data members of a JFrame object.

Program Code

Program Components

• A Java program is composed of

– comments,

– import statements, and

– class declarations.

Three Types of Comments

/*

This is a comment with

three lines of

text.

*/

Multiline CommentMultiline Comment

Single line CommentsSingle line Comments

// This is a comment

// This is another comment

// This is a third comment

28

2005 Pearson Education, Inc. All rights reserved.

Declaring a Class with a Method

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

29

2005 Pearson Education, Inc. All rights reserved.

Class GradeBook

• keyword public is an access modifier

• Class declarations include:

class GradeBook

{

}

30

2005 Pearson Education, Inc. All rights reserved.

Common Programming Error

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

31

2005 Pearson Education, Inc. All rights reserved.

Method declarations

publicpublic voidvoid displayMessage() displayMessage()

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

} } // end method displayMessage// end method displayMessage

– Keyword public indicates method is available to public

– Keyword voidvoid indicates no return type

32

2005 Pearson Education, Inc. All rights reserved.

Outline 1

2 // Class declaration with one method.

3

4 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

33

2005 Pearson Education, Inc. All rights reserved.

Class GradeBookTest– Programmers can create new classes

• Class instance creation expression– Using keyword new– To create a GradeBook object and assign it to myGradeBook

GradeBook myGradeBook ;GradeBook myGradeBook ; myGradeBook = new GradeBook();myGradeBook = new GradeBook();

• Calling a method// call myGradeBook's displayMessage method

myGradeBook.displayMessage();

34

2005 Pearson Education, Inc. All rights reserved.

•GradeBookTest.java

1

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

35

2005 Pearson Education, Inc. All rights reserved.

The complete program GradeBookTest.java • // Create a GradeBook object and call its displayMessage method.

public class GradeBookTest{ // main method begins program execution public static void main( String args[] ) { // create a GradeBook object and assign it to myGradeBook GradeBook myGradeBook = new GradeBook();

// call myGradeBook's displayMessage method myGradeBook.displayMessage(); } // end main

} // end class GradeBookTest

class GradeBook{ // display a welcome message to the GradeBook user public void displayMessage() { System.out.println( "Welcome to the Grade Book!" ); } // end method displayMessage

} // end class GradeBook

36

2005 Pearson Education, Inc. All rights reserved.

• Control Statements: Part 1

37

2005 Pearson Education, Inc. All rights reserved.

OBJECTIVES

In this chapter you will learn:

To use the if and if else selection statements to choose among alternative actions.

To use the while repetition statement to execute statements in a program repeatedly.

To use counter-controlled repetition and sentinel-controlled repetition.

To use the assignment, increment and decrement operators.

38

2005 Pearson Education, Inc. All rights reserved.

Sequence structure activity diagram.

Solid circle represents the activity’s initial state

Solid circle surrounded by a hollow circle represents the activity’s final state

39

2005 Pearson Education, Inc. All rights reserved.

Control Structures (Cont.)

• Selection Statements– if statement

• Single-selection statement

– if…else statement• Double-selection statement

– switch statement• Multiple-selection statement

40

2005 Pearson Education, Inc. All rights reserved.

 Control Structures (Cont.)

• Repetition statements– Also known as looping statements

– Repeatedly performs an action while its loop-continuation condition remains true

– while statement• Performs the actions in its body zero or more times

– do…while statement• Performs the actions in its body one or more times

– for statement• Performs the actions in its body zero or more times

41

2005 Pearson Education, Inc. All rights reserved.

if Single-Selection Statement

•if statements– Execute an action if the specified condition is true

– Can be represented by a decision symbol (diamond) in a UML activity diagram

• Transition arrows out of a decision symbol have guard conditions

– Workflow follows the transition arrow whose guard condition is true

42

2005 Pearson Education, Inc. All rights reserved.

Fig. 4.2 | if single-selection statement UML activity diagram.

Diamonds

Decision symbols (explained in section 4.5)

43

2005 Pearson Education, Inc. All rights reserved.

if…else Double-Selection Statement

•if…else statement– Executes one action if the specified condition is true or a

different action if the specified condition is false

if else double-selection statement UML activity diagram.

44

2005 Pearson Education, Inc. All rights reserved.

if ( testScore < 70 )

JOptionPane.showMessageDialog(null, "You did not pass" );

else

JOptionPane.showMessageDialog(null, "You did pass " );

Syntax for the if Statementif ( <boolean expression> )

<then block>

else

<else block>

Then BlockThen Block

Else BlockElse Block

Boolean ExpressionBoolean Expression

45

2005 Pearson Education, Inc. All rights reserved.

Control Flow

JOptionPane.showMessageDialog(null, "You did pass");

JOptionPane.showMessageDialog(null, "You did pass");

falsetestScore < 70 ?

testScore < 70 ?

JOptionPane.showMessageDialog(null, "You did not pass");

JOptionPane.showMessageDialog(null, "You did not pass");

true

46

2005 Pearson Education, Inc. All rights reserved.

testScore < 80

testScore * 2 >= 350

30 < w / (h * h)

x + y != 2 * (a + b)

2 * Math.PI * radius <= 359.99

Relational Operators

< //less than

<= //less than or equal to

== //equal to

!= //not equal to

> //greater than

>= //greater than or equal to

47

2005 Pearson Education, Inc. All rights reserved.

if (testScore < 70)

{

JOptionPane.showMessageDialog(null, "You did not pass“ );

JOptionPane.showMessageDialog(null, “Try harder next time“ );

}

else

{

JOptionPane.showMessageDialog(null, “You did pass“ );

JOptionPane.showMessageDialog(null, “Keep up the good work“ );

}

Compound Statements• Use braces if the <then> or <else> block has multiple statements.

Then BlockThen Block

Else BlockElse Block

48

2005 Pearson Education, Inc. All rights reserved.

if ( <boolean expression> ) {

}

else {

}

Style Guide

if ( <boolean expression> )

{

}

else

{

}

Style 1Style 1

Style 2Style 2

49

2005 Pearson Education, Inc. All rights reserved.

The if-then Statementif ( <boolean expression> )

<then block>

if ( testScore >= 95 )

JOptionPane.showMessageDialog(null,"You are an honor student");Then BlockThen Block

Boolean ExpressionBoolean Expression

50

2005 Pearson Education, Inc. All rights reserved.

Control Flow of if-then

testScore >= 95?

testScore >= 95?

falseJOptionPane.showMessageDialog (null, "You are an honor student");

JOptionPane.showMessageDialog (null, "You are an honor student");

true

51

2005 Pearson Education, Inc. All rights reserved.

The Nested-if Statement

• The then and else block of an if statement can contain any valid statements, including other if statements. An if statement containing another if statement is called a nested-if statement.

if (testScore >= 70) {

if (studentAge < 10) {

System.out.println("You did a great job");

} else {

System.out.println("You did pass"); //test score >= 70

} //and age >= 10

} else { //test score < 70

System.out.println("You did not pass");

}

52

2005 Pearson Education, Inc. All rights reserved.

Control Flow of Nested-if Statement

messageBox.show("You did not pass");

messageBox.show("You did not pass");

false inner if

messageBox.show("You did pass");

messageBox.show("You did pass");

false

testScore >= 70 ?

testScore >= 70 ?

true

studentAge < 10 ?

studentAge < 10 ?

messageBox.show("You did a great job");

messageBox.show("You did a great job");

true

53

2005 Pearson Education, Inc. All rights reserved.

Writing a Proper if Controlif (num1 < 0)

if (num2 < 0)

if (num3 < 0)

negativeCount = 3;

else

negativeCount = 2;

else

if (num3 < 0)

negativeCount = 2;

else

negativeCount = 1;

else

if (num2 < 0)

if (num3 < 0)

negativeCount = 2;

else

negativeCount = 1;

else

if (num3 < 0)

negativeCount = 1;

else

negativeCount = 0;

negativeCount = 0;

if (num1 < 0)

negativeCount++;

if (num2 < 0)

negativeCount++;

if (num3 < 0)

negativeCount++;

The statement

negativeCount++;

increments the variable by one

The statement

negativeCount++;

increments the variable by one

54

2005 Pearson Education, Inc. All rights reserved.

if – else if Control

if (score >= 90)

System.out.print("Your grade is A");

else if (score >= 80)

System.out.print("Your grade is B");

else if (score >= 70)

System.out.print("Your grade is C");

else if (score >= 60)

System.out.print("Your grade is D");

else

System.out.print("Your grade is F");

Test Score Grade90 score A

80 score 90

B

70 score 80

C

60 score 70

D

score 60 F

55

2005 Pearson Education, Inc. All rights reserved.

Matching else

if (x < y)

if (x < z)

System.out.print("Hello");

else

System.out.print("Good bye");

AA

if (x < y)

if (x < z)

System.out.print("Hello");

else

System.out.print("Good bye");

BB

Are and different?AA BB

if (x < y) {

if (x < z) {

System.out.print("Hello");

} else {

System.out.print("Good bye");

}

}

Both and means…AA BB

56

2005 Pearson Education, Inc. All rights reserved.

Boolean Operators

• A boolean operator takes boolean values as its operands and returns a boolean value.

• The three boolean operators are– and: &&

– or: ||

– not !

if (temperature >= 65 && distanceToDestination < 2) {System.out.println("Let's walk");

} else {System.out.println("Let's drive");

}

57

2005 Pearson Education, Inc. All rights reserved.

 while Repetition Statement

•while statement– Repeats an action while its loop-continuation condition

remains true

– Uses a merge symbol in its UML activity diagram• Merges two or more workflows

• Represented by a diamond (like decision symbols) but has:

– Multiple incoming transition arrows,

– Only one outgoing transition arrow and

– No guard conditions on any transition arrows

58

2005 Pearson Education, Inc. All rights reserved.

Calculate.java

// Calculate the sum of the integers from 1 to 10 public class Calculate { public static void main( String args[] ) { int sum; int x;

x = 1; // initialize x to 1 for counting sum = 0; // initialize sum to 0 for totaling

while ( x <= 10 ) // while x is less than or equal to 10 { sum += x; // add x to sum ++x; // increment x } // end while

System.out.printf( "The sum is: %d\n", sum ); } // end main

} // end class Calculate

59

2005 Pearson Education, Inc. All rights reserved.

Mystery.javapublic class Mystery

{ public static void main( String args[] ) { int y; int x = 1; int total = 0;

while ( x <= 10 ) { y = x * x; System.out.println( y ); total += y; ++x; } // end while

System.out.printf( "Total is %d\n", total ); } // end main

} // end class Mystery

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

60

2005 Pearson Education, Inc. All rights reserved.

Fig. 4.4 | while repetition statement UML activity diagram.

Diamonds

Decision symbols (explained in section 4.5)

Merge symbols (explained in section 4.7) int product = 3;

while (product <= 100)

product = 3 * product