Boolean
A logical statement that evaluates to true or false. In some languages, true is interchangeable(可互换的) with the number 1 and false is interchangeable with the number 0.
Conditional Statements
The basic syntax used by Java (and many other languages) is:
if(condition) {
// do this if 'condition' is true
}
else {
// do this if 'condition' is false
}
where condition is a boolean statement that evaluates to true or false. You can also use an if
without an else
, or follow an if(condition)
with else if(secondCondition)
if you have a second condition that only need be checked when condition is false. If the if
(or else if
) condition evaluates to true, any other sequential statements connected to it (i.e.: else
or an additional else if
) will not execute.
Logical Operators
Customize your condition checks by using logical operators. Here are the three to know:
||
is the OR operator, also known as logical disjunction.&&
is the AND operator, also known as logical conjunction.!
is the NOT operator, also known as negation.
Another great operator is the ternary operator for conditional statements (? :
). Let's say we have a variable, v, and a condition, c. If the condition is true, we want v to be assigned the value of a; if condition c is false, we want v to be assigned the value of b. We can write this with the following simple statement:
v = c ? a : b;
In other words, you can read c ? a : b
as "if c is true, then a; otherwise, b". Whichever value is chosen by the statement is then assigned to v.
Switch Statement
This is a great control structure for when your control flow depends on a number of known values. Let's say we have a variable, condition, whose possible values are val0, val1, val2, and each value has an action to perform (which we will call some variant of behavior). We can switch between actions with the following code:
switch (condition) {
case val0: behavior0;
break;
case val1: behavior1;
break;
case val2: behavior2;
break;
default: behavior;
break;
}
Note: Unless you include break;
at the end of each case statement, the statements will execute sequentially. Also, while it's good practice to include a default:
case (even if it's just to print an error message), it's not strictly necessary.
Additional Language Resources
C++ Statements and Flow Control
Python Control Flow Tools