Unit 4 Control structures Content 1 statements execution




























































- Slides: 60

Unit 4 Control structures Content 1. statements execution order & flow of control (FOC) 2. relational expressions 3. Branching control structures 4. Looping control structures 5. Single-entry-single-exit principle 6. debugging techniques 1

1) Order of executing program statements Ø Program Execution Order Ø Generally, we have only one CPU q Therefore, program statements are executed one-by-one sequentially q sequence of statement execution called Flow of Control (Fo. C) Ø Fixed sequence is not desirable q Jump to another function q Jump to other statements under some conditions q Loop a set of statements 2

Program Execution Order Ø For example, q Check username match password. If success, provides services. q Otherwise, rejects it. Flow of Control Ø In all programming language, foc includes q. Expression to determine the flow q. Branching mechanism e. g. if-else, goto q. Looping mechanism e. g. for, while Ø Java also provides its own mechanisms 3

2) Relational Expressions Ø An expression is the condition to determine the flow in runtime Ø An expression returns true or false ( > 0 or <= 0 ) Ø An expression consists of operators: q Arithmetic operators [+ , - , * , / , % , ^ , += , -= , *=, /= ] q relational operators [< , > , <= , >= ] q Assignment operators [ = ] q Unary operators [ -a. Number ] Ø Result of operators depends on LHS and/or RHS values q Primitive type, reference variable, constant and even method return value 4

Java Expression Ø In Java, an expression can have no operator q A variable q Return value of a method call q Boolean or integer v if (stop) v if (obj) v if (is. Valid(obj)) q If integer, v how does the branching/looping evaluate as true or false ? q How about float or object ? 5

Relational Operators Ø Evaluate and return true or false q 6 Relational Operators, q for example : testing for A < B, v when A=1 and B=2, the result is true v when A=2 and B=1, the result is false Ø Can be used for all numeric primitive : q [ byte , short , char, int , long , float & double ] 6

Operators Relational Equality 7

Equality Operators == & != Ø == & != can be used for reference variables Ø If you are new in programming, must pay attention to the 2 operators == & != Ø != means not equal q The exclamation mark (!) in Java always means 'negation' or 'not' Ø == is equal 8

"==" (equality) VS "=" (assignment) int a = 1, b = 2 ; if (a == b) { } if (a = b) { // This block will NOT be executed? // This block will be executed } Ø the latter expression results in a = 2 & the second block will be executed Ø because "=" is assignment, totally different from "==" 9

Example Ø Java compiler will detect this error before execution public class compilation. Error { public static void main (String args[]) { final int MY_CONSTANT = 10 ; int a = 5 ; if (MY_CONSTANT == a) { System. out. println("It is OK"); } if (MY_CONSTANT = a) { System. out. println("it is Not OK"); } } } C: >javac compilation. Error. java a. java: 8: cannot assign a value to final variable MY_CONSTANT if (MY_CONSTANT = a) { ^ 1 error 10

Integer & Floating Point Ø Operators are reliable for integer but not for floating point Ø Floating point calculation results are also just approximations because of rounding-off Ø Therefore, q a / b * b == a ? q a == 0. 85 ? q Using Math. abs(a – 0. 85) < 0. 0000001 v where 0. 0000001 is an arbitrary value of the tolerable round-off error 11

Operator == and Reference Variables Ø Operators == can be applied for reference variables q But the result… Ø In unit 3, reference variables actually carry the locations of objects Ø So, == compares the locations rather than the states of the objects Ø Means they refer to the same object 12

Fig 4. 2 pp-9 Case studies about the results of : (counter 1 == counter 2) 13

14

Customize Method equals() Ø Want to compare the states of objects q Using method equals() instead of == operator Ø Class must implement its own equals() q Default implemented in java. lang. Object q The default implemented is just like == Ø For example, q class String override to compare the content of char buffer Ø So, don’t relay on default equals() (p-11) : s 1. equals(s 2) returns false King-130 : q (s 1==s 2) and s 1. equals(s 2) returns true only when different 15

Precedence and Associativity Ø Ø Determine the order in an expressions Higher precedence are performed first When same precedence, using associativity Arithmetic operators has higher precedence q relational, in turn higher precedence than v equality operators Ø remember the table ( next page ) or always using parentheses "()" in expression q suggest to use "()" 16

Precedence + - Associativity Remarks Right Unary operators * / % Left + - Left >= > < <= Left == != Left = += -= *= Right /= %= Ø "+=" means In. Crement Ø "-=" means De. Crement Assignment operators Ø Why assignment is lowest? Ø Don’t forget that the "!" operator means negation 17

Self-test 4. 1 Evaluate the following : a) 5 + 4 / 3 * 2 b) (3 + 2) * 4 c) 33 * 3 < 99 d) (4 + 3) * 2 != 12 Answer : a) 7 b) 20 c) false d) true 18

3) Branching Ø Now you know expression and operators Ø After evaluating a condition (an expression in Java), the flow depends on the Branching or Looping statement Ø The java programming language only supports two branching structures, q if/else statement q switch/case statement 19

if Statement 20

if Statement Ø If sth is true, then the extra block of statement will be executed Ø The condition in the parentheses must be an expression return true or false Ø The statements enclosed in the curly brackets "{" and "}" are executed Ø Besides the coding, you must also know the flow chart 21

Curly brackets Ø Curly brackets, "{" and "}", must be in pair Ø Although curly brackets is not a must, highly recommended to use for maintenance if (condition) statement-1; statement-2; is interpreted as if (condition) statement-1; statement-2; 22

Indention in Statement Block Ø Usually indent the statements in a block so that q Easier to identify the block properly & enhance the readability q Not only in if, but also all block like function body 23

P. 25 Min. Max. Finder. java public class Min. Max. Finder { private int current. Min = Integer. MAX_VALUE; // the current minimum private int current. Max = Integer. MIN_VALUE; // the current maximum // Present a number to the object for testing with current minimum and maximum public void test. Number(int number) { // Compare the given number with current maximum if (number > current. Max) { current. Max = number; If the given number is greater than current maximum } then assign the given number to the current maximum // Compare the given number with the current minimum if (number < current. Min) { current. Min = number; If the given number is less than the current mininum } then assign the given number to the current minimum } // retrieve the current minimum public int get. Minimum() { return current. Min; } // retrieve the current maximum public int get. Maximum() { return current. Max; } 24 }

P. 28 Test. Min. Max. Finder. java (driver program) public class Test. Min. Max. Finder { public static void main(String args[]) { Min. Max. Finder finder = new Min. Max. Finder(); // Sending messages with numbers to the object so that // the numbers are tested one by one finder. test. Number(15); finder. test. Number(20); finder. test. Number(10); // Send messages to the object to get its current min & max value int min. Number = finder. get. Minimum(); int max. Number = finder. get. Maximum(); System. out. println("Minimum number = " + min. Number); System. out. println("Maximum number = " + max. Number); } } 25

P. 32 Greeting. Chooser. java public class Greeting. Chooser { // Determine the greeting based on the given hour public String assign. Greeting (int hour) { // A local variable for storing the result temporarily String greeting = ""; if (hour >= 0) { greeting = "morning"; } if (hour >= 12){ greeting = "afternoon"; } if (hour >= 18){ greeting = "evening"; } // Return the result to the caller return greeting; } } 26

P. 34 Test. Greeting. java ( driver program ) import javax. swing. JOption. Pane; public class Test. Greeting { public static void main(String args[]) { Greeting. Chooser chooser = new Greeting. Chooser(); // Show a dialog to get the hour from user // The obtained hour is returned as a String object String input. Hour = JOption. Pane. show. Input. Dialog("Please enter the hour"); // Obtain the integer value from the input String object int hour = Integer. parse. Int(input. Hour); String greeting = chooser. assign. Greeting(hour); String output = "Good " + greeting; // set the message to be shown JOption. Pane. show. Message. Dialog(null, output); // Show greeting with a dialog System. exit(0); // Terminate the program } 27 }

Mutually Exclusive Ø In the situation, q Perform a task if a condition is true q Otherwise, perform another task Ø It works but suffers from performance penalty because of 2 test if (number > 0) { System. out. println("Number is positive"); } else { System. out. println("Number is non-positive"); } Print a line & then start a new line 28

if/else Statement Ø Java extends if by optional else statement(s) Ø Support any number of else statements if (condition) { statement(s)-1 // statement(s) to be executed if the condition is true } else { statement(s)-2 // statement(s) to be executed if the condition is false } statement(s)-1 (if part) true condition false statement(s)-2 (else part) 29

switch/case Statement Ø Sometimes, it is necessary to test the content of a variable against a list of possible values q Can use a number of if. . else q But coding is tedious Ø Java provides a faster and more readable flow of control statement: q switch / case 30

switch/case Statement (p 64~65) “break” means end of a case “default” is optional Ø If missing, run next statement Ø Recommend to use Ø catch unexpected conditions switch (expr) { case expr-1: statements-1; true expr == statements-1 break; expr-1 case expr-2: false statements-2; true expr == statements-2 break; expr-2 case expr-3: false statements-3; true expr == statements-3 break; expr-3 default: statements-default; false statementsbreak; default } 31

switch/case vs if/else Ø switch/case can support primitive type of : q byte, short, char and int only q can check the equality for byte, short, char or int q only supports equality checking Ø if/else can support boolean type only q with proper relational operators, can support all primitive type and non-primitive type q can check the equality for long, float, double, boolean and non-primitive types q can use any relational operator. 32

switch/case vs if/else Ø Although switch/case is more restricted, q Its structure is more elegant and easier to read q Faster q Use it whenever possible 33

Example // page 58 // page 71 public class Grade. Converter { public String assign. Grade(int mark) { // The grade is first assumed to be F String grade = "F"; public class Grade. Converter 2 { public String assign. Grade(int mark) { // The grade to be returned String grade; // Set criteria for grades one by one if (mark >= 50) {grade = "E"; } if (mark >= 60) {grade = "D"; } if (mark >= 70) {grade = "C"; } if (mark >= 80) {grade = "B"; } if (mark >= 90) {grade = "A"; } // Set criteria for grades one by one switch (mark / 10) { case 9: case 10: grade = "A"; case 8: grade = "B"; case 7: grade = "C"; case 6: grade = "D"; case 5: grade = "E"; default: grade = "F"; } // Return the determined grade return grade; break; break; } } // Return the determined grade return grade; } } 34

4) Looping control structures Ø In many cases, a program needs to execute the same statement several times q eg. calculate total number of staff salaries Ø Therefore, programming language must support looping Ø Java defines 3 types: q while q do/while q for 35

Looping Ø usually a loop has of 2 parts q Condition q Statement/loop body Ø Furthermore, q Initialization q Update Ø Finally, q Execute-check or q check-execute Ø Anyway, don’t make an infinite looping q A loop never ends q Condition always true q P. 99 even server side check exit/stop event Ø Famous loop: q Windows GUI event loop q Palm event loop q Web server event loop 36

while Loop while (codition) statement(s) General format condition true statement(s) false while (condition) { statement(s) } 37

while Loop Ø Clear definition for Condition & Statement/loop body Ø No definition for Initialization & Update Ø Check-execute q The loop body can be completely ignored Ø Simple, suitable for loops require no initialization and update q E. g. GUI event loops, JDBC result set 38

Example (page 75~76) // example-1 i = 1; n = 10; while (i < n) i *= 2; // example-2 (recommended) i = 1; n = 10; while (i < n) { i *= 2; } i = 1; n = 10; i < n true i *= 2 false 39

Table 4. 4 Execution details of a loop (p-77) Value of Iteration i < n 1 1 10 true The loop body is executed, and the value of variable i becomes 2. 2 2 10 true The loop body is executed, and the value of variable i becomes 4. 3 4 10 true The loop body is executed, and the value of variable i becomes 8. 4 8 10 true The loop body is executed, and the value of variable i becomes 16. 5 16 10 false Actions to be taken The loop is terminated As a result, the value of the variable i is 16 when the loop is terminated. 40

do/while Loop (p-81) do statement(s) while (condition); condition do statement true false while (condition); do { statement(s) } while (condition); 41

do/while Loop Ø Just like while loop Ø Execute-check instead check-execute q The loop body will be executed at least once Ø Sometimes, initialization is embedded in the loop body 42

Self-Test 4. 5 (p-126) result = result * number ; eg. 4! = 4 x 3 x 2 // a buggy version of factorial public int factorial(int number) { int result = 1; do { result *= number; number-- ; } while (number > 1) ; return result ; } // a correct version of factorial public int factorial(int number) { int result = 1; while (number > 1) { result *= number; number-- ; } return result ; } Do / While Ø when input <= 1 Ø loop body runs to return 0 Ø thus, 0! = 0 ( which is wrong) While Ø when input <= 1 Ø loop body skipped & return the default, 1 43 Ø thus, 0! = 1 and (-1)! = 1

for Loop 44

for Loop Ø Clear definition for Condition & Statement/loop body Ø Clear definition for Initialization & Update Ø Check-execute like while Ø Difficult to read q Initialization, Condition & Update are in the same stement Ø Suitable for numerical loops 45

for = while Ø Which is more preferable? q If explicit initialization/update are required, for is more suitable (eg. loop all elements in a collection) q otherwise, while (eg. loop all result set of a JDBC call) 46

Example for & while java. util. Vector vec = new java. util. Vector(10) ; // update the vec java. sql. Result. Set rs = null ; for (int i = 0; i < vec. size(); i++) { java. lang. Object obj = vec. get(i) ; // process the obj } while (rs. next()) { rs. get. String(1) ; // process the result set item // update the result set } 47

Start from Zero Ø A for loop uses an integer as index to a collection q the start value is 0 instead of 1 v Thus, condition uses "<" instead of "<=" Ø Beginner must be careful Ø This introduce a lot of misunderstanding in programming q eg. Result. Set 48

Practice and Scope Ø Although meaningful variable names are recommended, there is an exception case q In for loop, the index always use simple char like j, k… q This is an acceptable exception in programming Ø Due to scope (life time of a variable), such declared variables cannot be reused outside the loop q Each loop has its own 49

Unintentional Infinite Loop (p-102) Ø Loop condition is always true Ø Pls heed the data type limitation q Max/min values q Default value Ø Logical error Ø Debug message Integer. MAX_VALUE = 32767 50

5) Single-entry-single-exit principle (p 102~3) break / return / continue / goto Ø Flow of control should be kept simple & straight-forward Ø Therefore, don't use goto (no longer supported) and continue to jump to another segment Ø Also, keep break and return as less as possible in a method or a loop 51

Which is more preferable ? public int factorial(int number) { if (number < 0) { return -1; } (p 104) public int factorial(int number) { int result; if (number < 0) { result = -1; } else { result = 1; for (int i = number; i > 1; i--) { result *= i; } } int result = 1; for (int i = number; i > 1; i--) { result *= i; } return result; } // earlier & multiple exit points // by using TWO return statements return result; } // unique exit // by using ONE return statement 52

Which is more preferable ? public String assign. Grade(int mark) { String grade = ""; switch (mark / 10) {. . . case 9: if (mark % 10 < 5) { grade = "A-"; break; } grade = "A"; break; case 10: grade = "A+"; break; } return grade; } // not clear (p 105) public String assign. Grade(int mark) { String grade = ""; switch (mark / 10) {. . . case 9: if (mark % 10 < 5) { grade = "A-"; } else { grade = "A"; } break; case 10: grade = "A+"; break; } return grade; } // more clear, but should avoid 53

Exception Ø To serve the purpose of single exit, a lot of if-else statements are used Ø programmers find it undesirable for : q Difficult to follow q More coding Ø That’s why we need exception, to throw an abnormal situation to the handler directly Ø The focuses only the normal case 54

Exception Example try { String number = new String("ABC"); java. lang. Integer an. Integer=new java. lang. Integer(number); int value = an. Integer. int. Value(); } catch (Number. Format. Exception ex) { // handle numberic exception } catch (Null. Pointer. Exception ex) { // handle null ptr exception } 55

Non-exception Example String number = new String("ABC"); if (null != number) { if (Icheck. Number(number)) { int value = convert. Number(number) ; } else { // handle numberic } } else { // handle null ptr } 56

6) Debugging Programs Ø Java or IDE Debugger Ø More popular - Print message System. out. println() System. err. println() Ø Not a good approach q Not persistent q Add/Remove must re-compile the src Ø Log 4 J – configure logging dynamically 57

Debugging with System. out. println() while (remain. Digits > 0) { // Get the least significant digit int digit = remain. Digits % 10; // Print the digit System. out. println(digit); // Dropping the last digit remain. Digits /= 10; } while (remain. Digits > 0) { // Get the least significant digit int digit = remain. Digits % 10; // Print the digit System. out. println(digit); // Dropping the last digit remain. Digits = 10; } the "/" char is missing 58

println( ) and print( ) public class List 7 { public boolean is 7 (int number) { boolean result = false; for ( int i=2; I < number; i++ ) { if (number % 7 == 0) { result = true; } } return result; } } public class List 7 Driver { public static void main(String args[]){ List 7 tester = new List 7(); for (int i=2; i <= 50; i++) { if ( tester. is 7(i) ) { System. out. print(i+"t"); } "t" is a <TAB> character start at a } new line System. out. println(); System. out. println("Done"); } } 59

Log 4 J Ø Free java package Ø 4 level logging q debug (lowest), info, warn, error Ø Configure file defines runtime log level for a package or a class q Lower level message not logged in runtime Ø Therefore, can determine runtime log message without recompile of program 60