Learn Java - Conditionals and Control Flow Cheatsheet - Codecademy
Learn Java - Conditionals and Control Flow Cheatsheet - Codecademy
else Statement
The else statement executes a block of code when boolean condition1 = false;
the condition inside the if statement is false . The
else statement is always the last condition.
if (condition1){
System.out.println("condition1 is
true");
}
else{
System.out.println("condition1 is not
true");
}
// Prints: condition1 is not true
else if Statements
else - if statements can be chained together to int testScore = 76;
check multiple conditions. Once a condition is true , a
char grade;
code block will be executed and the conditional
statement will be exited.
There can be multiple else - if statements in a single if (testScore >= 90) {
conditional statement.
grade = 'A';
} else if (testScore >= 80) {
grade = 'B';
} else if (testScore >= 70) {
grade = 'C';
} else if (testScore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
if (false) {
System.out.println("This code
does not execute");
}
// There is no output for the above
statement
NOT Operator
The NOT logical operator is represented by ! . This boolean a = true;
operator negates the value of a boolean expression.
System.out.println(!a); // Prints: false
System.out.println(!false) // Prints:
true
The OR Operator
The logical OR operator is represented by || . This System.out.println(true || true); //
operator will return true if at least one of the
Prints: true
boolean expressions being compared has a true
value; otherwise, it will return false .
System.out.println(true || false); //
Prints: true
System.out.println(false || true); //
Prints: true
System.out.println(false || false); //
Prints: false
Conditional Operators - Order of Evaluation
If an expression contains multiple conditional boolean foo = true && (!false || true);
operators, the order of evaluation is as follows:
// true
Expressions in parentheses -> NOT -> AND -> OR.
/*
(!false || true) is evaluated first
because it is contained within
parentheses.
Print Share