If/Else
The boolean values return true and false checking the conditional. For example:
int firstNumber = 4;
int secondNumber = 4;
if (firstNumber == secondNumber) {
System.out.println("4 equals 4!!");
}
We could also just do this:
int firstNumber = 5;
if (firstNumber == 5) {
System.out.println("First equals 5!!");
}
Operators
Operators are used to compare two or more values. These values can even be variables. The operators are mostly similar to standard mathematical operators. Some new ones include != which means 'not equal to', || which means 'or', && which means 'and', and ! which flips the boolean value (true/false).
int a = 3;
int b = 8;
boolean outcome;
outcome = a < b; // this statement is TRUE
outcome = a > b; // this statement is FALSE
outcome = a <= 4; // less than or equal to 4 - TRUE
outcome = b >= 10; // greater than or equal to 6 - FALSE
outcome = a == b; // a equal to b - FALSE
outcome = a != b; // a is not equal to b - TRUE
outcome = a > b || a < b; // Logical or - TRUE
outcome = 1 & a && a < 6; // Logical and - TRUE
outcome = !result; // Logical not - FALSE
The if-else statement
The if-else statement is a helpful way to write out how a function will be carried out when something is active. Let's start with the basic if statement.
if (a == b) {
// a and b are equal, you will get free pizza
}
However, the if statement does not reach its full potential until the else statement is added, which shows what happens when the if statement is not satisfied.
if (a == b) {
System.out.println("You get free pizza!");
} else {
System.out.println("No free pizza!"); // this means a and b are not equal, so the else action is implemented
}
// this can also be written as
if (a == b) {
System.out.println("You get free pizza!");
} else {
System.out.println("No free pizza!");
}