Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-1 l Branching l Loops l exit(n) method l Boolean data type.

Slides:



Advertisements
Similar presentations
Branching Loops exit(n) method Boolean data type and expressions
Advertisements

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
ITM352 Loops Lecture #6. 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 2 Announcements r Lab class dates have changed!!! m Check the “Weekly Schedule”
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
Chapter 31 Flow of Control Chapter 3. 2 Reminders Project 1 was due last night Project 2 released: due Sept 10:30 pm - No Late Submissions Follow.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Edited by JJ Shepherd
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing.
Comp 248 Introduction to Programming Chapter 3 – Flow of Control Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control.
Flow of Control Module 3. Objectives Use Java branching statements Compare values of primitive types Compare objects such as strings Use the primitive.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
ITM 352 Flow-Control: if and switch. ITM © Port, KazmanFlow-Control - 2 What is "Flow of Control"? Flow of Control is the execution order of instructions.
Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1.
1 Week 6 Branching. 2 What is “Flow of Control”? l Flow of Control is the execution order of instructions in a program l All programs can be written with.
Flow of Control Chapter 3 Flow of control Branching Loops
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Introduction To Scientific Programming Chapter 3.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/29 The switch Statement The switch statement provides another way.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Chapter 3 1 l Branching l Loops l exit(n) method l Boolean data type and logic expressions Flow of Control – Part 1.
Control Flow Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Control statements Mostafa Abdallah
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control.
COMP Loop Statements Yi Hong May 21, 2015.
Flow of Control Joe McCarthy CSS 161: Fundamentals of Computing1.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
1 Week 9 Loops. 2 Repetition: Loops l Structure: »Usually some initialization code »body of loop »loop termination condition l Several logical organizations.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
Chapter 3 Branching Statements
ITM 352 Flow-Control: if and switch
JavaScript: Control Statements.
Branching Loops exit(n) method Boolean data type and expressions
3 Control Statements:.
Web Programming– UFCFB Lecture 20
Boolean Expressions to Make Comparisons
Flow of Control Chapter 3.
Chapter 4 - Program Control
Announcements/Reminders
Presentation transcript:

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-1 l Branching l Loops l exit(n) method l Boolean data type and expressions Flow of Control

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-2 What is “Flow of Control”? l Flow of Control is the execution order of instructions in a program l All programs can be written with three control flow elements: 1. Sequence - just go to the next instruction 2. Branching or Selection - a choice of at least two –either go to the next instruction –or jump to some other instruction 3. Loop or Repetition - a loop (repeat a block of code) at the end of the loop –either go back and repeat the block of code –or continue with the next instruction after the block

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-3 Java Flow Control Statements Sequence l the default l Java automatically executes the next instruction unless you use a branching statement Branching l if l if-else l if-else if-else if- … - else l switch Loop l while l do-while l for

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-4 Java if Statement l Simple selection l Do the next statement if test is true or skip it if false l Syntax: if (Boolean_Expression) Action if true; //execute only if true next action; //always executed l Note the indentation for readability (not compile or execution correctness)

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-5 if Example l The body of the if statement is conditionally executed l Statements after the body of the if statement always execute if(eggsPerBasket < 12) //begin body of the if statement System.out.println(“Less than a dozen eggs per basket”); //end body of the if statement totalEggs = numberOfEggs * eggsPerBasket; System.out.println(“You have a total of + totalEggs + “ eggs.”);

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-6 Multiple Statements Action if true can be either a single Java statement or a set of statements enclosed in braces { }. l A set of statements in braces is called a compound statement and can be used anywhere a single statement can be used. if(eggsPerBasket < 12) { //begin body of the if statement System.out.println(“Less than a dozen...”); costPerBasket = 1.1 * costPerBasket } //end body of the if statement totalEggs = numberOfEggs * eggsPerBasket; System.out.println(“You have a total of “ + totalEggs + “ eggs.”); All statements between braces are controlled by if

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-7 Two-way Selection: if-else l Select either one of two options l Either do Action1 or Action2, depending on test value l Syntax: if (Boolean_Expression) { Action1 //execute only if true } else { Action2//execute only if false } Action3//always executed

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-8 if-else Examples l Example with single-statement blocks: if(time < limit) System.out.println(“You made it.”); else System.out.println(“You missed the deadline.”); l Example with compound statements: if(time < limit) { System.out.println(“You made it.”); bonus = 100; } else { System.out.println(“You missed the deadline.”); bonus = 0; }

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-9 Definition of Boolean Values l Branching: there is more than one choice for the next instruction l Which branch is taken depends on a test condition which evaluates to either true or false l In general: if test is true then do this, otherwise it is false, do something else l Variables (or expressions) that are either true or false are called boolean variables (or expressions) So the value of a boolean variable (or expression) is either true or false boolean is a primitive data type in Java

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-10 Boolean Expressions l Boolean expressions can be thought of as test conditions (questions) that are either true or false l Often two values are compared l For example: Is A greater than B? Is A equal to B? Is A less than or equal to B? etc. l A and B can be any data type (or class), but they should be the same data type (or class)

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-11 Java Comparison Operators

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-12 Compound Boolean Expressions Use && to AND two or more conditions »Expression will be true if both parts are true. »A && B will be true if both A and B are true Use || to OR two or more conditions »Expression will be true if either part is true, or if both parts are true. »A || B will be true if either A or B is true, or if both A and B are true.

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-13 Compound Boolean Expressions l Example: write a test to see if B is either 0 or between the values of B and C (B == 0) || (A <= B && B < C) l In this example the parentheses are not required but are added for clarity »See text (and later slides) for Precedence rules »Note the short-circuit, or lazy, evaluation rules in text (and later in slides) »Use a single & for AND and a single | for OR to avoid short-circuit evaluation and force complete evaluation of a boolean expression

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-14 Java Comparison Methods for String Class l “==“ does not do what you may think for String objects »When “==“ is used to test objects (such as String objects) it tests to see if the storage addresses of the two objects are the same –are they stored in the same location? –more will be said about this later l Use “.equals” method to test if the strings, themselves, are equal String s1 = “Mondo”; String s2; s2 = SavitchIn.readLine(); //s1.equals(s2) returns true if the user enters Mondo, false otherwise.equals() is case sensitive Use.equalsIgnoreCase() to ignore case

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-15 Alphabetical Ordering Use compareTo method of String class l Uses ASCII lexicographic ordering where all uppercase letters come before all lowercase letters »For example capital 'Z' comes before small 'a' »Convert strings to all uppercase (or all lowercase) to avoid problems l s1.compareTo(s2) »returns a negative value if s1 comes before s2 »returns zero if the two strings are equal »returns a positive value if s2 comes before s1 // Assume s1 and s2 are two string variables // that have been given string values. String upperS1 = s1.toUpper(); String upperS2 = s2.toUpper(); if (upperS1.compareTo(upperS2) < 0) System.out.println(s1 + " precedes " + s2);

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-16 Nested if Statements One if statement can have another if statement inside it. These are called nested if statements. l Inner statements are indented more than outer statements. if (balance >= 0) if (RATE >= 0) balance = balance + (RATE * balance)/12; else System.out.println("Cannot have negative rate"); else balance = balance – OVERDRAWN_PENALTY; inner statement outer statement The inner statement will be skipped entirely if balance >= 0 is false.

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-17 Multibranch selection: if-else if-else if-…-else l One way to handle situations with more than two possibilities l Syntax: if(Boolean_Expression_1) Action_1 else if(Boolean_Expression_2) Action_2. else if(Boolean_Expression_n) Action_n else Default_Action

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-18 if-else if-else if-…-else Example if(score >= 90) grade = 'A'); else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'E'; Note indentation. Even though these are nested if statements, they are all indented the same amount to indicate a multibranch selection.

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-19 Multibranch selection: switch l Another way to program multibranch selection Uses Controlling_Expression to decide which way to branch Controlling_Expression must be char, int, short or byte. Controlling Expression and Case_Label must be same type. switch(Controlling_Expressi on) { case Case_Label: statements … break; case Case_Label: statements … break; default: statements … break; }

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-20 Multibranch selection: switch When a break statement is encountered, control goes to the first statement after the switch. break may be omitted l Can have any number of cases default case is optional switch(Controlling_Expressi on) { case Case_Label: statements … break; case Case_Label: statements … break; default: statements … break; }

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-21 switch Example switch(seatLocationCode) { case 1: System.out.println(“Orchestra”); price = 40.00; break; case 2: System.out.println(“Mezzanine”); price = 30.00; break; case 3: System.out.println(“Balcony”); price = 15.00; break; default: System.out.println(“Unknown seat code”); break; } Output if seatLocationCode is 2: Mezzanine

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-22 Repetition: Loops l Structure: »Usually some initialization code »body of loop »loop termination condition l Several logical organizations »counting loops »sentinel-controlled loops »infinite loops »minimum of zero or minimum of one iteration l Several programming statement variations »while »do-while »for

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-23 while Loop l Syntax: while(Boolean_Expression) { //body of loop First_Statement;... Last_Statement; } l Initialization statements usually precede the loop. Boolean_Expression is the loop termination condition. The loop will continue executing as long as Boolean_Expression is true. l May be either counting or sentinel loop »Good choice for sentinel loop Something in body of loop should eventually cause Boolean_Expression to be false.

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-24 Semantics of the while Statement while (Boolean_Expression) Body Start Evaluate Boolean_Expression End loop false Execute Body true

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-25 while : A Counting Loop Example l A loop to sum 10 numbers entered by user int next; //Loop initialization int count = 1; int total =0; while(count <= 10) //Loop termination condition { //Body of loop next = SavitchIn.readLineInt(); total = total + next; count++; //Loop termination counter }

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-26 while : A Sentinel Controlled Loop Example l A loop to sum positive integers entered by the user next is the sentinel l The loop terminates when the user enters a negative number //Initialization int next = 0; int total = 0; while(next >= 0) //Termination condition { //Body total = total + next; next = SavitchIn.readLineInt(); }

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-27 while : A Minimum of Zero Iterations Because the first input value read and the test precedes the loop, the body the while loop body may not execute at all //Initialization int next; int total = 0; next = SavitchIn.readLineInt(); while(next >= 0)//Termination condition { //Body total = total + next; next = SavitchIn.readLineInt(); } l If the first number the user enters is negative the loop body never executes

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-28 do-while Loop Syntax do { //body of loop First_Statement;... Last_Statement; } while(Boolean_Expression); l Initialization code may precede loop body l Loop test is after loop body so the body must execute at least once (minimum of at least one iteration) l May be either counting or sentinel loop »Good choice for sentinel loop Something in body of loop should eventually cause Boolean_Expression to be false.

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-29 Semantics of the do-while Statement do Body while (Boolean_Expression); Start End loop false true Execute Body Evaluate Boolean_Expression

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-30 do-while Example int count = 1; int number = 5; do //Display integers 1 to 5 on one line { System.out.print(count + " "); count++; } while(count <= number); Note that System.out.print() is used and not System.out.println() so the numbers will all be on one line. Output:

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-31 for Loop l Good choice for counting loop l Initialization, loop test, and loop counter change are part of the syntax l Syntax: for(Initialization; Boolean_Expression; Update_Action) loop body;

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-32 Semantics of the for Statement for(Initialization; Boolean_Expression; Update_Action) loop body; Start Evaluate Boolean_Expression End loop false Execute Body true Execute Initialization Execute Update_Action

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-33 for Example l Count down from 3 to 1 for(int count = 3; count >= 1; count--) { System.out.print("T = " + count); System.out.println(" and counting"); } System.out.println("Blast off!"); Output: T = 3 and counting T = 2 and counting T = 1 and counting Blast off!

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-34 The exit Method If you have a program situation where it is pointless to continue execution you can terminate the program with the exit(n) method. n is often used to identify if the program ended normally or abnormally. n is conventionally 0 for normal termination and non-zero for abnormal termination.

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-35 exit Method Example System.out.println("Enter e to exit or c to continue"); char userIn = SavitchInReadLineChar(); if(userIn == 'e') System.exit(0); else if(userIn == 'c') { //statements to do work } else { System.out.println("Invalid entry"); //statements to something appropriate }

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-36 Nested Loops l The body of a loop can have any kind of statements, including another loop. l Each time the outer loop body is executed, the inner loop body will execute 5 times, making a total of 20 times. for (line = 0; line < 4; line++) for (star = 0; star < 5; star++) System.out.print('*'); System.out.println(); body of inner loop body of outer loop Output: *****

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-37 Some Practical Considerations When Using Loops l The most common loop errors are unintended infinite loops and off-by-one errors in counting loops. l Sooner or later everyone writes an unintentional infinite loop »To get out of an unintended infinite loop enter ^C (control-C) l Loops should be tested thoroughly, especially at the boundaries of the loop test, to check for off-by-one and other possible errors.

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-38 Tracing a Variable in a Loop l Tracing a variable: print out the variable each time through the loop l A common technique is to test loop counters and troubleshoot off-by-one and other loop errors. l Some systems provide a built-in tracing system that allows you to trace a variable without having to change your program. l If no built-in utility is available, insert temporary output statements to print values.

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-39 The Type boolean l A primitive type l Can have expressions, values, constants, and variables just as with any other primitive type Only two values: true and false Can use a boolean variable as the condition in an if statement l Using a boolean variable as the condition can make an if statement easier to read by avoiding a complicated expression. if (systemsAreOK) System.out.println("Initiate launch sequence."); else System.out.println("Abort launching sequence");

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-40 boolean Variables in Assignments A boolean expression evaluates to one of the two values true or false. The value of a boolean expression can be assigned to a boolean variable: int number = -5; boolean isPositive; isPositive = (number > 0); if (isPositive) System.out.println(“positive”); else System.out.println(“negative or zero”); There are simpler and easier ways to write this small program, but boolean variables are useful in keeping track of conditions that depend on a number of factors. Parentheses are not necessary here. Parentheses are necessary here.

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-41 Truth Tables for boolean Operators Value of AValue of BA && B truetruetrue truefalsefalse falsetruefalse falsefalsefalse Value of AValue of BA || B truetruetrue truefalsetrue falsetruetrue falsefalsefalse Value of A!A truefalse falsetrue && (and)|| (or) ! (not)

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-42 Precedence An example of using precedence rules to see which operators in following expression should be done first: score 90 l Division operator has highest precedence of all operators used here so treat it as if it were parenthesized: score 90 l Subtraction operator has next highest precedence : score 90 l The operators have equal precedence and are done in left-to- right order : (score 90) l The last expression is a fully parenthesized expression that is equivalent to the original. It shows the order in which the operators in the original will be evaluated.

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-43 Precedence Rules Highest Precedence First: the unary operators: +, -, ++, --, and ! Second: the binary arithmetic operators: *, /, % Third: the binary arithmetic operators: +, - Fourth: the boolean operators:, = = Fifth: the boolean operators: ==, != Sixth: the boolean operator & Seventh: the boolean operator | Eighth: the boolean operator && Ninth: the boolean operator || Lowest Precedence

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-44 Short-Circuit Evaluation l Short-circuit evaluation—only evaluating as much of a boolean expression as necessary. l Example: If assign > 0 is false, then the complete expression cannot be true because AND is only true if both operands are true. l Java will not evaluate the second part of the expression. Short-circuit evaluation prevents a divide-by-zero exception when assign is 0. if ((assign > 0) && ((total/assign) > 60)) System.out.println(“Good work”); else System.out.println(“Work harder.”);

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-45 Summary Part 1 Java selection statements: if, if-else, if-else if, and switch Java repetition (loop) statements: while, do-while, and for l Loops can be counter or sentinel controlled l Any loop can be written any of the three loop statements, but »while and do-while are good choices for sentinel loops »for is a good choice for counting loops

Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-46 Summary Part 2 Unintended infinite loops can be terminated by entering ^C (control-C) l The most common loop errors are unintended infinite loops and off-by-one errors in counting loops Branching and loops are controlled by boolean expressions »boolean expressions are either true or false »boolean is a primitive data type in Java exit(n) is a method that terminates a program »n = 0 is the conventional value for normal termination