Lecture 3: Topics If-then-else Operator precedence While loops Static methods Recursion
Boolean expressions continued If I can get an outdoor court tomorrow and it’s not raining or I can get an indoor court, we can play tennis English can be ambiguous, but in programming, AND always has higher precedence than OR
If-then-else if (i > j) if (a > b) ____; else // which if does it match? ____; The “else” clause matches the most recent unmatched “if” in the same {…} block
What’s the difference? boolean x; if (x == true) ______ if (x) ______ if (x = true) ______
What’s the difference? Between x++ and ++x They are both short for x = x+1, but they have different meanings in y = x++ and y = ++x The first means y = x; x++; while the second means x++ y = x Potentially confusing, better to use the longer versions in my opinion
Mixing assignments in one line a = b += c = 5 assignment operators are evaluated right to left, but other binary operators with same precedence are evaluated left to right, such as: a – b + c Very confusing! Better to avoid mixing assignment statements in one line in my opinion OK to use a+=5 instead of a = a + 5, etc, but this is not necessary
Operator precedence postfix ++, - - unary +, -, prefix ++, - - (avoid) casting ! *,/,% binary +,-, >= ==, != & (avoid) ^ (avoid) | (avoid) && || =, +=, -=, *=, /=, %= (I avoid except =) Use (,) when needed AND ALSO FOR CLARITY!
While loop demo Extracting the letters from a string
Static methods In older programming languages these were called “procedures” (when they did not return a value) and “functions” (when they returned a value) Modifiers: static, public, private Return value: void, or a type The formal parameters (or parameters) are the ones listed in the method header The actual parameters (or arguments) are the ones provided when the method is called Together, the name of the method and its list of parameter types constitute the method signature
Why do we need methods? To organize programs into manageable chunks of code Abstraction, encapsulation Always think of how to simplify code by using methods appropriately
Local variables and their scope A variable declared inside a method is local to the method and cannot be accessed outside it A variable declared in a loop or a block {…} cannot be accessed outside it Example for (int i=0; i<10; i++){ … } System.out.println(i); // error, i is not accessible
Method overloading When two methods have the same name but different signatures Many examples in the Java libraries
The call stack “Stack” of info about the method call history, including space for local variables
Recursion (chapter 19!) When a method calls itself classic example: factorial but factorial can just as well be programmed with a loop recursion really useful when the method makes two recursive calls bad example: Fibonacci (easy to write recursive code but it is very inefficient)