CT 229 Java Syntax Continued 29/09/2006 CT229
Lab Assignments One Week Extension for Lab Assignment 1. Due Date: Oct 8 th Before submission make sure that the name of each.java file matches the name given in the assignment sheet!!!! Remember: Electronic Submission @ http://ecrg-vlab01.it.nuigalway.ie/uploader/submissions.html or email: edward.scully@nuigalway.ie Where does Eclipse put my.java files???? By default Eclipse will put your.java files in your F:\ drive. Look in your F:\My Documents\workspace\<name of project> 29/09/2006 CT229 1
Tutorials Tutorial Commence next week. Tutorials 1hr/Week BE(EE) Tues AC213 (12-1) BE(E&CE) Tues AC213 (12-1) BSc(IT) Thurs IT203 (12-1) BSc(P&A) Thurs IT203 (12-1) 29/09/2006 CT229 2
Review of Last Week Difference between an operand and an operator Operators can be classified as unary, binary or ternary Operator Types Arithmetic (+, -, etc.) Relational (>, >=, etc) Boolean (&&,, ^, etc) Difference between (&& and &) and ( and ) Assignment Operators (*=, +=, etc) Bitwise Operators Bitwise AND(&) OR( ) XOR(^) Complement (~) Bitwise Shift (>>, >>>, <<) NEXT: Precedence and Associativity 29/09/2006 CT229 3
Precedence and Associativity It is possible to combine multiple arithmetic operations in one statement int answer = 1 + 2 + 3 + 4 + 5; The value of answer is obviously 15 However, if you use different operators on the same line it's not always clear what the result will be. int answer = 1-2 * 3-4 + 5; Is answer equal to -2? You might think so if you just calculate from left to right. According to Java answer is -4 Why? 29/09/2006 CT229 4
Precedence and Associativity int answer = 1-2 * 3-4 + 5; Java derived a value of -4 because it performs all multiplications before it performs any additions or subtractions. You can think of the calculation Java did as being: int answer = 1 (2 * 3) - 4 + 5; This is an issue of precedence. In Java the * operator has a higher precedence than the or + arithmetic operators 29/09/2006 CT229 5
Precedence and Associativity Precedence determines the order in which operators act in an expression with more than one operator. The Operator Precedence Table gives the precedence rating for each operator, the lower the number indicating higher precedence For example, in the example on the previous slide the * operator will have a lower precedence number than the + or - operator 29/09/2006 CT229 6
Full Precedence & Associativity Table Prec. Operators Associativity 1 () []. Left to right 2! ~ ++ -- +(unary) -(unary) Right to left ~(unary) (type-cast) 3 * / % Left to right 4 + - Left to right 5 << >> >>> Left to right 6 < <= > >= instanceof Left to right 7 ==!= Left to right 8 & Left to right 9 ^ Left to right 10 Left to right 11 && Left to right 12 Left to right 13?: Right to left 14 = += -= *= /= %= &= ^= = <<= >>= Right to left 29/09/2006 CT229 7
An Example of Precedence Example int num1 = 2; int num2 = 3; int num3 = 4; int num4 = 3; The value of num5 is 17 int num5 = num1 += num2 * num3 + num4; System.out.println( The value of num5 is + num5); 29/09/2006 CT229 8
Precedence and Associativity What happens when the operations in an expression all have the same precedence rating? The associativity rule specifies the correct order. Associativity Rule Unary and Assignment: Others: right-to-left left-to-right e.g.: x + y + z is evaluated as (x + y) + z x + y - z is evaluated as (x + y) - z 29/09/2006 CT229 9
Precedence and Associativity Consider the following: a - b + c Precedence Ranking is equal The associativity rule dictates (left to right), that is b will be subtracted from a before it is added to c a * b / c (Again this is evaluated left to right) Parentheses have highest level of Precedence. For example, if I wanted b and c to be summed first in the above equation I could write it as: a (b + c) 29/09/2006 CT229 10
Full Precedence & Associativity Table Prec. Operators Associativity 1 () []. Left to right 2! ~ ++ -- +(unary) -(unary) Right to left ~(unary) (type-cast) 3 * / % Left to right 4 + - Left to right 5 << >> >>> Left to right 6 < <= > >= instanceof Left to right 7 ==!= Left to right 8 & Left to right 9 ^ Left to right 10 Left to right 11 && Left to right 12 Left to right 13?: Right to left 14 = += -= *= /= %= &= ^= = <<= >>= Right to left 29/09/2006 CT229 11
Precedence and Associativity Example: int x =5; int y = 2; x += y *= 10; System.out.println(x); What is the answer? 29/09/2006 CT229 12
Full Precedence & Associativity Table Prec. Operators Associativity 1 () []. Left to right 2! ~ ++ -- +(unary) -(unary) Right to left ~(unary) (type-cast) 3 * / % Left to right 4 + - Left to right 5 << >> >>> Left to right 6 < <= > >= instanceof Left to right 7 ==!= Left to right 8 & Left to right 9 ^ Left to right 10 Left to right 11 && Left to right 12 Left to right 13?: Right to left 14 = += -= *= /= %= &= ^= = <<= >>= Right to left 29/09/2006 CT229 13
Precedence and Associativity Example: int x =5; int y = 2; x += y *= 10; System.out.println(x); *= and += are assignment operators. Therefore the Associativity rule dictates that the expression be evaluated from right to left The answer is 25 2 *= 10 => 20 5 += 20 => 25 29/09/2006 CT229 14
Flow of Control in Java Program When Java Program Run: Statements in main() executed in sequence Program ends at last statement in main(), or at System.exit() (which can appear anywhere in code) System.exit(n); n = 0 -> normal successful completion n!= 0 -> indicates error to operating system Along the way, control structures and method calls change flow of control Conditions for program ending stay the same 29/09/2006 CT229 15
Statement Blocks and Empty Statements Empty Statement: Semi-colon on its own, or empty Considered a statement by compiler; does nothing Avoid stray semi-colons in code! Statement Blocks Anywhere you can have a single statement in Java, you can write a compound statement instead Block of statements between if (condition) action1; action2; Compound statements are statements that contain lists of statements enclosed in braces " statements " Compound statements can be decision/loop structure 29/09/2006 CT229 16
Decisions if Statements Basic if statement: if (condition) action; condition: an expression that evaluates to a boolean action: an executable statement if/else: Specifies alternative action if condition false if (condition) action_if_true; else action_if_false; 29/09/2006 CT229 17
Decisions if Statements if/else if if (condition1) action_if_condition1_true; else if (condition2) action_if_condition1_true; else action_if_all_conditions_false; 29/09/2006 CT229 18
Note: Decisions if Statements if statements should always use braces. Avoid the following error-prone form: if (condition) action; Note: AVOID if (condition) Java differs from C and C++ because an if takes a boolean expression and not a numeric one. action; 29/09/2006 CT229 19
Decisions: if ladder Avoids excessive indentation of complex nested ifs if (mark < 0 mark > 100) System.out.println("ERROR: mark is invalid\n"); else if (mark < 40.0) grade = 'F'; else if (mark < 55.0) grade = 'D'; else if (mark < 70.0) grade = 'C'; else if (mark < 85.0) grade = 'B'; else grade = 'A'; 29/09/2006 CT229 20
Multiple decision structure: switch carry out different actions corresponding to different values of an integer-type variable int choice; /* user enters 1, 2, 3, or 4 for choice */ Examples: - Switch.java - MonthSwitch.java switch (choice) case 1: doactionone(); // done if choice == 1 break; // don't do next stmt case 2: doactiontwo(); // if choice == 2 break; case 3: case 4: doactiontwothreefour(); // if choice == 2,3,4 break; default: displayerror(); // all other cases 29/09/2006 CT229 21
Repetition: while while: Repeat a statement/block while a condition is true Useful when we don't know in advance how many times to repeat (for used more often when we do know) Format while (condition) action; 29/09/2006 CT229 22
Repetition - While int count = 1; while (count < 5) System.out.println("Count is: " + count); count++; Count is: 1 Count is: 2 Count is: 3 Count is: 4 29/09/2006 CT229 23
Repetition - do/while do/while: Like while, but condition tested after action first done Action guaranteed to be executed at least once Useful when action initialises variable used in condition Format: do action; while (condition); 29/09/2006 CT229 24
Repetition do/while int count = 1; do System.out.println("Count is: " + count); count++; while (count < 5); Count is: 1 Count is: 2 Count is: 3 Count is: 4 Examples: - DoWhileExample2.java 29/09/2006 CT229 25
Repetition: for Used to repeat block of code specified number of times Useful when number of repetitions known E.g. print 10 lines for (i = 0 ; i < 10 ; i++) System.out.println("Line " + i); Initialise control variable: once, at very start of loop Test: every time, before executing loop body Increment: every time, after loop body, before next test 1: Initialise 2: Test All sections of for header are optional Leave in ; E.g. no initialisation required; endless loop; no increment 3: Increment 29/09/2006 CT229 26
For: Notes Initialise Section: Can declare the control variable: for (int x=10; x>5; x--) Scope of variable is until end of loop Test Section: If testing (variable == value) ensure variable does not miss the exact value, particularly with float/double Using >= or <= may be safer Increment Section: Can increment, decrement, add 7, whatever For clarity, use combined assignment operator (x += 7) 29/09/2006 CT229 27