Skip to content

Week 6

Conditionals

You Will Understand Why We Need Conditions

  • To make decisions based off different inputs.
  • Perform different actions in the same program.

Basics

  • if, switch, else if
  • boolean expression, boolean variable, boolean method call
  • executes or bypasses statements in block
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    if (x > 0) {
        System.out.println("x is positive");
    } else if(x == 0) {
        System.out.println("x is 0");
    } else {
        if( x > -10 ) {
            System.out.println("x is negative, but barely");
        }
        System.out.println("x is negative");
    }
    

Relational operators OR Comparison Operators

1
2
3
4
5
6
7
8
    x == y // x is equal to y
    x != y // x is not equal to y
    x > y  // x is greater than y
    x < y  // x is less than y
    x >= y // x is greater than or equal to y
    x <= y // x is less than or equal to y
    // Strings are different because they are special/immutable objects
    aStr.equals("abc");

Logical operators

1
2
3
    &&  Logical and Returns true if both statements are true    x < 5 &&  x < 10    
    ||  Logical or  Returns true if one of the statements is true   x < 5 || x < 4  
    !   Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)

Short Circuit Evaluation

  • The first condition that satisfies the condition stops evaluation

DeMorgan’s Law

1
2
    !(A && B) isthesameas !A || !B
    !(A || B) isthesameas !A && !B

DeMorgan's Law Truth Table

Recursion is Important

  • But we’re not going to cover that much in this class

Review

  • Modulus
  • Variables in methods
  • Why we use methods
  • class/static vs public/object/instance