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

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Advertisements

3 Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. Conditions can be formed using the.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 1.
 2005 Pearson Education, Inc. All rights reserved Introduction.
INSTRUCTOR: SHIH-SHINH HUANG Windows Programming Using Java Chapter4: Control Statements Part I.
Selection Statements & Exam 1 Review Recitation – 2/13/2009 CS 180 Department of Computer Science, Purdue University.
 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 4 – Introducing Algorithms, Pseudocode and.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
 2002 Prentice Hall. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
CMT Programming Software Applications
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Animated Version.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
بسم الله الرحمن الرحيم CPCS203: Programming II. Objectives After you have read and studied this chapter, you should be able to Implement a selection control.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Selection Statements.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection Statement 4.6 if else Selection Statement 4.7 while.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
Relational Operators Control structures Decisions using “if” statements  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
Part 2 Control Statements.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
Chapter Chapter 5 Selection Statements. Objectives Understand selection control statement –if statements –switch statements Write boolean expressions.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 6 – Car Payment Calculator Application: Introducing.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 4 – Wage Calculator Application: Introducing.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 6 – Car Payment Calculator Application: Introducing.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
1 C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved. 4.
Chapter 04 Control Statements: Part II. OBJECTIVES In this part you will learn: if…else Double-Selection Statement. while Repetition Statement.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Sample Slides - 1 Sample Animated Slides for Wu, Intro to OOP.
Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure 4.6 The if / else Selection Structure 4.7.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
 Pearson Education, Inc. All rights reserved Control Statements: Part 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Chapter 2 Getting Started with Java. Objectives After you have read and studied this chapter, you should be able to Identify the basic components of Java.
1 Training Lecture 1. 2 Primitive Data Declaration and Assignments Code State of Memory int firstNumber, secondNumber; firstNumber = 234; secondNumber.
Chapter 5: Objectives After you have read and studied this chapter, you should be able to Implement a selection control using if statements Implement a.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Numeric Data Types There are six numeric data types: byte, short, int, long, float, and double. Sample variable declarations: int i, j, k; float numberOne,
 2005 Pearson Education, Inc. All rights reserved. 1 Introduction to Classes and Objects.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter 3 Numerical Data. Objectives After you have read and studied this chapter, you should be able to Select proper types for numerical data. Write.
 2003 Prentice Hall, Inc. All rights reserved. 1 Will not cover 4.14, Thinking About Objects: Identifying Class Attributes Chapter 4 - Control Structures.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
3 Introduction to Classes and Objects.
Introduction to Classes and Objects
Yanal Alahmad Java Workshop Yanal Alahmad
Control Statements: Part 1
Yanal Alahmad Java Workshop Yanal Alahmad
2.5 Another Java Application: Adding Integers
Primitive and Reference Data Values
Chapter 4 Control Statements: Part I
Chapter 3 Introduction to Classes, Objects Methods and Strings
MSIS 655 Advanced Business Applications Programming
3 Control Statements:.
Chapter 4 - Control Structures: Part 1
Chapter 6 Selection Statements
Presentation transcript:

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

 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

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;

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

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

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 C. The value 35 overwrites the previous value

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

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.

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.

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

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

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.

Sending a Message myWindow. setVisible ( true ) ; More Examples account.deposit( ); 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.

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

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 Comment Single line Comments // This is a comment // This is another comment // This is a third comment

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

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

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

 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

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

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

 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

 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

 2005 Pearson Education, Inc. All rights reserved. 36 Control Statements: Part 1

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

 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

 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

 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

 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

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

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

 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

 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

 2005 Pearson Education, Inc. All rights reserved. 46 testScore < 80 testScore * 2 >= < w / (h * h) x + y != 2 * (a + b) 2 * Math.PI * radius <= Relational Operators <//less than <=//less than or equal to ==//equal to !=//not equal to >//greater than >=//greater than or equal to

 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

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

 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

 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

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

 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

 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

 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

 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

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

 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

 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

 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 /**************************************************************

 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