What is if and else condition

  • Allows program to check if a condition is true and runs that certain code block otherwise it will run the other code block
if(condition) {
    // code block for if condition is true
} else {
    // code block for if condition is not true
}

If and Else if condition

  • If the first condition is not true you can use a else if to see if that condition is true
if (condition) {
    // code block 1 for if condition is true
} else if(condition2) {
    // checks if condition 2 is true and runs this code block
}

Last if/else statement

  • Checks two conditions and if neither are True then results to last code block with no condition
if (condition) {
    // code block 1
} else if (condition2) {
    // code block 2
} else {
    // last code block where neither condition or condition2 are true
}
import java.util.Scanner;

public class ConditionStatements {
    public void go() {
        Scanner scan = new Scanner(System.in);
        int num = scan.nextInt();
        if (num == 1) {
            System.out.println("Number 1 was selected");
        } else if (num == 2) {
            System.out.println("Number 2 was selected");
        } else if (num ==3) {
            System.out.println("Number 3 was selected");
        } else if (num ==4) {
            System.out.println("Number 4 was selected");
        } else if (num ==5) {
            System.out.println("Number 5 was selected");
        } else {
            System.out.println("Number was not 1-5");
        }
    }

    public static void main(String[] args) {
        ConditionStatements cond = new ConditionStatements();
        cond.go();
    }
}

ConditionStatements.main(null);
Number 2 was selected

Switch Statement

  • Similar to if and else statement but in a neater way in my opinion
import java.util.Scanner;

public class SwitchStatement {
    public void go() {
        Scanner scan = new Scanner(System.in);
        int num = scan.nextInt();

        switch (num){
            case 1:
                System.out.println("Number 1 was selected");
                break;
            case 2:
                System.out.println("Number 2 was selected");
                break;
            case 3:
                System.out.println("Number 3 was selected");
                break;
            case 4:
                System.out.println("Number 4 was selected");
                break;
            case 5:
                System.out.println("Number 5 was selected");
                break;
            default:
                System.out.println("Number was not 1-5");
        }
    }

    public static void main(String[] args) {
        SwitchStatement cond = new SwitchStatement();
        cond.go();
    }
}

SwitchStatement.main(null);
Number 2 was selected

De Morgan's law

  • Similar to Logic Gates from CSP
  • Talks about how || (or) and && (and)
if (!((true == true) && (true == false))) {
    System.out.println("De Morgans law is true");
}
De Morgans law is true