If Statements

If

If is a conditional statement, meaning it will only execute code within the block if the statement is true. If the code executed within the condition returns true, then code will run. This code in the conditional can be very complex, or could even be a whole method call. It just needs to return true or false.

import java.util.Scanner;

public class cheese {
    public static void main(String[] args) {
        Scanner yesNoScan = new Scanner(System.in); // scanner initiate
        String yesNo =  yesNoScan.nextLine();
        System.out.println(yesNo);
        
        // if statement: if matches yes, then say yes
        if (yesNo.matches("yes")) {
            System.out.println("yes!");
        }
    }
}

cheese.main(null);
yes
yes!

As seen in this example, the program calls for user input. If the user inputs yes, the condition returns true, and the code block runs. The console will say "yes!"

If-else

If-else builds off of an if statement, but adds the else part. If the condition in the if statement is false, then the code in the else block will execute instead. The else does not have a conditional.

import java.util.Scanner;

public class cheese {
    public static void main(String[] args) {
        Scanner yesNoScan = new Scanner(System.in); // scanner initiate
        String yesNo =  yesNoScan.nextLine();
        System.out.println(yesNo);
        
        // if statement: if matches yes, then say yes
        if (yesNo.matches("yes")) {
            System.out.println("yes!");
        } else { // if not yes, then print that
            System.out.println("not yes :(");
        }
    }
}

cheese.main(null);
nope
not yes :(

As seen, when an input that isn't yes is entered, the "not yes :(" is triggered to run.

If-elseif-else

This code structure combines both if and else statements. If the first conditional under the if statement returns false, then it goes to the next part: else if. The else if does have a conditional, basically a second conditional to check if the first one is false. If that one is true, it will run the code, but if not, it goes to the next block. There can be an indefinite chain of elseifs, but they always run from top to bottom and the statement exits if one of them is true. If they all return false, the else statement at the end will execute the code if everything is false.

import java.util.Scanner;

public class cheese {
    public static void main(String[] args) {
        Scanner yesNoScan = new Scanner(System.in); // scanner initiate
        String yesNo =  yesNoScan.nextLine();
        System.out.println(yesNo);
        
        // if statement: if matches yes, then say yes
        if (yesNo.matches("yes")) {
            System.out.println("yes!");
        } else if (yesNo.matches("no")) { // if no, then print
            System.out.println("no? :(");
        } else { // if not yes or no
            System.out.println("bruh u messed up");
        }
    }
}

cheese.main(null);
fdasdfagsa
bruh u messed up

As seen above, when it is neither yes or no, it outpus the else block of code.

Switch Case

Sometimes, when you only need to test expressions matching only a single integer, value, or String, a Switch Case is the better option. It is similar to an if-elseif-elseif...-else chain, except it has less functionality.

In an if-elseif chain, each section has its own conditional. These conditionals can be extremely complex and do not have to relate to each other at all. However, in a switch case, the switch takes in an input, and then checks against the "cases". Basically, the conditionals in all of the cases are only determining whether the input matches the set case.

For example, to match a string in if-elseif, it would look something like:

import java.util.Scanner;

public class cheesePicker {
    public static void main(String[] args) {
        System.out.println("Type a type of cheese, and find out the best meat to pair it with: ");
        Scanner cheeseScan = new Scanner(System.in); // scanner initiate
        String cheese =  cheeseScan.nextLine();
        System.out.println(cheese);
        
        // if statement: if matches types of cheese, say the sandwich
        if (cheese.matches("gouda")) {
            System.out.println("salami");
        } else if (cheese.matches("parmesan")) { 
            System.out.println("prosciutto");
        } else if (cheese.matches("havarti")) { 
            System.out.println("soppressata");
        } else if (cheese.matches("monterey jack")) { 
            System.out.println("salami");
        } else if (cheese.matches("ricotta")) { 
            System.out.println("ground beef");
        } else {
            System.out.println("search it up");
        }
    }
}

cheesePicker.main(null);
Type a type of cheese, and find out the best meat to pair it with: 
gouda
salami

However, by using switch case, these conditionals can be made more readable as they are just matching strings:

import java.util.Scanner;

public class cheesePickerCase {
    public static void main(String[] args) {
        System.out.println("Type a type of cheese, and find out the best meat to pair it with: ");
        Scanner cheeseScan = new Scanner(System.in); // scanner initiate
        String cheese =  cheeseScan.nextLine();
        System.out.println(cheese);
        
        // switch case: take cheese as input, check against list of cheeses
        switch (cheese) {
            case "gouda":
                System.out.println("salami");
                break; // break to get out of switch, so no default case
            case "parmesan":
                System.out.println("prosciutto");
                break;
            case "havarti":
                System.out.println("soppressata");
                break;
            case "monterey jack":
                System.out.println("salami");
                break;
            case "ricotta":
                System.out.println("ground beef");
                break;

            default: // case if nothing matches
                System.out.println("google it");
        }
       
    }
}

cheesePickerCase.main(null);
Type a type of cheese, and find out the best meat to pair it with: 
monterey jack
salami

De Morgan's Law

These are laws named after Augustus De Morgan, a 19th C British Mathemetician. It uses the NOT operator, which takes precedent over AND and OR. It can be used to simplify expressions of true and false, and as boolean values are being compared in an if conditional, applying De Morgan's law to simplify a program's logic will be very helpful.

Overall, the idea is that: when distributing or factoring a negation from a boolean expression, the operators all switch. || changes to && and vice versa. In addition, < changes to =>, and vice versa. PunApps AP Comp Sci

In addition:

  • < becomes >=
  • > becomes <=
  • == becomes !=
  • <= becomes >
  • >= becomes <
  • != becomes ==

For example:

!(!A || !B) --> A && B

As you can see, the ! in the front propogates and distributes into the condition, negating the ! inside as well as changing the || (or) to && (and). If you plug in the values, you will see that they equate to the same thing. It may not make intuitive sense exactly, but it is a proven law.

Seen below is an example of this law:

import java.util.Scanner;

public class DeMorgan {

    // define variables
    public static String email = null;
    public static String username = null;
    public static String password = null;

    // take the input for the variables using scanner
    public static String inputDetails(String detail) {
        System.out.print(detail + ": ");
        Scanner detailScan = new Scanner(System.in); // scanner initiate
        String inputDetail = detailScan.nextLine();
        System.out.println(inputDetail);
        detailScan.close();
        return inputDetail; // return the input
    }

    public static void main(String[] args) {
        

        System.out.println("type your email, username, then password to sign up: ");
        
        // take user input
        email = inputDetails("email");
        username = inputDetails("username");
        password = inputDetails("password");

        // conditional, if not all requirements met then throw error
        if (!(email != "" && username != "" && password != "")) {
            throw new Error("Not all requirements are met");
        }
    }

}

DeMorgan.main(null);
type your email, username, then password to sign up: 
email: f
username: d
password: 
---------------------------------------------------------------------------
java.lang.Error: Not all requirements are met
	at DeMorgan.main(#13:1)
	at .(#35:1)

As seen, it takes user input and checks if all of them have some sort of input. If they do not, the NOT operator turns that false into true for the conditional, throwing the error. In essence, it is saying that NOT all conditions are met.

import java.util.Scanner;

public class DeMorgan {

    // define variables
    public static String email = null;
    public static String username = null;
    public static String password = null;

    
    public static String inputDetails(String detail) {
        System.out.print(detail + ": ");
        Scanner detailScan = new Scanner(System.in); // scanner initiate
        String inputDetail = detailScan.nextLine();
        System.out.println(inputDetail);
        detailScan.close();
        return inputDetail;
    }

    // take the input for the variables using scanner
    public static void main(String[] args) {
        
        System.out.println("type your email, username, then password to sign up: ");

        // take user input
        email = inputDetails("email");
        username = inputDetails("username");
        password = inputDetails("password");

        // conditional with de morgans law applied
        if (email == "" || username == "" || password == "") {
            throw new Error("Not all requirements are met");
        }
    }

}

DeMorgan.main(null);
type your email, username, then password to sign up: 
email: f
username: d
password: 
---------------------------------------------------------------------------
java.lang.Error: Not all requirements are met
	at DeMorgan.main(#13:1)
	at .(#30:1)

After applying De Morgan's law and switching all of the comparators, such as != to == and && to ||, the code becomes much more readable. It reads that if any one of the inputs are not filled in, then the condition is true and the error is thrown. In essence: if any of the inputs are empty, throw an error. As seen, it has the same output, so it demonstrates that the law is true.

Inspiration from Patrick Divine