Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2005 Pearson Education, Inc. All rights reserved. 1 A class A class is the blueprint from which objects are generated. In other words, if we have six.

Similar presentations


Presentation on theme: " 2005 Pearson Education, Inc. All rights reserved. 1 A class A class is the blueprint from which objects are generated. In other words, if we have six."— Presentation transcript:

1  2005 Pearson Education, Inc. All rights reserved. 1 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. 2 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

3 Manipulating Numbers In Java, to add two numbers x and y, we write x + 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; or int x; int y;

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

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

6 Data Type Precisions The six data types differ in the precision of values they can store in memory.

7 Assignment Statements We assign a value to a variable using an assignment statements. The syntax is = ; Examples: sum = firstNumber + secondNumber; avg = (one + two + three) / 3.0;

8 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. The reserved word final is used to declare constants. These are called literal constant.

9 Primitive Data Declaration and Assignments Code State of Memory int firstNumber, secondNumber; firstNumber = 234; secondNumber = 87; A A int firstNumber, secondNumber; B B firstNumber = 234; secondNumber = 87; int firstNumber, secondNumber; firstNumber = 234; secondNumber = 87; firstNumber secondNumber A. A. Variables are allocated in memory. B. B. Values are assigned to variables. 234 87

10 Assigning Numerical Data Code State of Memory int number; number = 237; number = 35; number A. A. The variable is allocated in memory. B. 237 number B. The value 237 is assigned to number. 237 int number; number = 237; number = 35; A A int number; B B number = 237; C C number = 35; C. 35 237. C. The value 35 overwrites the previous value 237. 35

11 Assigning Objects Code State of Memory Customer var; var = new Customer( ); var A. A. The variable is allocated in memory. Customer var; var = new Customer( ); A A Customer var; B B var = new Customer( ); C C B. var B. The reference to the new object is assigned to var. Customer C. var. C. The reference to another object overwrites the reference in var. Customer

12 Having Two References to a Single Object Code State of Memory Customer clemens, twain; clemens = new Customer( ); twain = clemens; Customer clemens, twain, clemens = new Customer( ); twain = clemens; A A Customer clemens, twain; B B clemens = new Customer( ); C C twain = clemens; A. A. Variables are allocated in memory. clemens twain B. clemens B. The reference to the new object is assigned to clemens. Customer C. clemens customer. C. The reference in clemens is assigned to customer.

13 Object Creation myWindow = new JFrame ( ) ; More Examples customer = new Customer( ); jon= new Student(“John Java”); car1= new Vehicle( ); Object Name Name of the object we are creating here. Object Name Name of the object we are creating here. Class Name An instance of this class is created. Class Name An instance of this class is created. Argument No arguments are used here. Argument No arguments are used here.

14 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. 2. A Customer object is created and the identifier customer is set to refer to it. 1 2 customer 1 : Customer 2

15 State-of-Memory vs. Program customer : Customer State-of-Memory Notation customer : Customer Program Diagram Notation Class Name Object Name

16 Name vs. Objects Customer customer; customer = new Customer( ); Customer customer; customer customer = new Customer( ); : Customer Created with the first new. Created with the second new. Reference to the first Customer object is lost.

17

18

19

20

21

22

23

24 Sending a Message myWindow. setVisible ( true ) ; More Examples account.deposit( 200.0 ); student.setName(“john”); car1.startEngine( ); Object Name Name of the object to which we are sending a message. Object Name Name of the object to which we are sending a message. Method Name The name of the message we are sending. Method Name The name of the message we are sending. Argument The argument we are passing with the message. Argument The argument we are passing with the message.

25 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. Program Code

26 Program Components A Java program is composed of –comments, –import statements, and –class declarations.

27 Three Types of Comments /* This is a comment with three lines of text. */ Multiline Comment Single line Comments // This is a comment // This is another comment // This is a third comment

28  2005 Pearson Education, Inc. All rights reserved. 28 Declaring a Class with a Method publicEach 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.

29  2005 Pearson Education, Inc. All rights reserved. 29 Class GradeBook keyword public is an access modifier Class declarations include: class GradeBook { }

30  2005 Pearson Education, Inc. All rights reserved. 30 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. 31 Method declarations public void displayMessage() { System.out.println( "Welcome to the Grade Book!" ); } // end method displayMessage – Keyword public indicates method is available to public void – Keyword void indicates no return type

32  2005 Pearson Education, Inc. All rights reserved. 32 Outline Print line of text to output

33  2005 Pearson Education, Inc. All rights reserved. 33 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 ; myGradeBook = new GradeBook(); Calling a method // call myGradeBook's displayMessage method myGradeBook.displayMessage();

34  2005 Pearson Education, Inc. All rights reserved. 34 GradeBookTest.java 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. 35 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. 36 Control Statements: Part 1

37  2005 Pearson Education, Inc. All rights reserved. 37 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. 38 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. 39 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. 40 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. 41 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. 42 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. 43 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. 44 if ( testScore < 70 ) JOptionPane.showMessageDialog(null, "You did not pass" ); else JOptionPane.showMessageDialog(null, "You did pass " ); Syntax for the if Statement if ( ) else Then Block Else Block Boolean Expression

45  2005 Pearson Education, Inc. All rights reserved. 45 Control Flow JOptionPane. showMessageDialog (null, "You did pass"); JOptionPane. showMessageDialog (null, "You did pass"); false 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. 46 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. 47 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 or block has multiple statements. Then Block Else Block

48  2005 Pearson Education, Inc. All rights reserved. 48 if ( ) { … } else { … } Style Guide if ( ) { … } else { … } Style 1 Style 2

49  2005 Pearson Education, Inc. All rights reserved. 49 The if-then Statement if ( ) if ( testScore >= 95 ) JOptionPane.showMessageDialog(null, "You are an honor student"); Then Block Boolean Expression

50  2005 Pearson Education, Inc. All rights reserved. 50 Control Flow of if-then testScore >= 95? false JOptionPane. showMessageDialog (null, "You are an honor student"); JOptionPane. showMessageDialog (null, "You are an honor student"); true

51  2005 Pearson Education, Inc. All rights reserved. 51 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. 52 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 ? true 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. 53 Writing a Proper if Control if (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; 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. 54 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 ScoreGrade 90  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. 55 Matching else if (x < y) if (x < z) System.out.print("Hello"); else System.out.print("Good bye"); A A if (x < y) if (x < z) System.out.print("Hello"); else System.out.print("Good bye"); B B Are and different? A A B B if (x < y) { if (x < z) { System.out.print("Hello"); } else { System.out.print("Good bye"); } Both and means… A A B B

56  2005 Pearson Education, Inc. All rights reserved. 56 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. 57 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. 58 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. 59 Mystery.java public 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. 60 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


Download ppt " 2005 Pearson Education, Inc. All rights reserved. 1 A class A class is the blueprint from which objects are generated. In other words, if we have six."

Similar presentations


Ads by Google