Professional Documents
Culture Documents
if(BooleanExpression) {
statement1;
statement2;
...
}
A Flag is
a boolean variable that signals when some condition exists in a program.
When Java compares characters, it compares the characters
Unicode values
Review
General form of an if-else statement:
if(BooleanExpression)
statement or block 1
else
statement or block 2
The if-else if Statement
Sometimes you need to be able to test a series of conditions
You can do this with the if-else if statement
General form:
if (BooleanExpression1)
statement or block 1
if else (BooleanExpression2)
statement or block 2
else
statement or block 3
If BooleanExpression1 is true, then statement or block 1 is
executed.
If BooleanExpression1 is false, then BooleanExpression2 is
tested.
If BooleanExpression2 is true, then statement or block 2 is executed.
If BooleanExpression2 is false, then statement or block 3 is executed.
Note: You can have as many if else clauses as is needed.
if-else if Example
New Topics:
if-else if Statement
Using else as an error case
Nested if Statements
Nesting is enclosing one structure inside of another.
A block in Java can contain any valid Java code, this includes other if statements:
if(BooleanExpression1) {
if(BooleanExpression2) {
statement1;
statement2;
}
statement3;
statement4;
}
If BooleanExpression1 is true and BooleanExpression2 is true , what
is executed?
statement1 , statement2 , statement3 , statement4
If BooleanExpression1 is true and BooleanExpression2 is false ,
what is executed?
statement3 , statement4
If BooleanExpression1 is false, what is executed?
Nothing
Nested if Statements Example
New Topics:
Nested if Statements
Logical Operators
Java provides logical operators.
The binary logical operators combine two boolean expressions into
one.
The unary logical operator switches the value of a boolean
expression.
Operator Meaning Kind
&& AND Binary
|| OR Binary
! NOT Unary
Op1 !Op1
true false
false true
Logical Operator Practice
2 > 3 && 4 < 5
false first operand is false
2 < 3 && 4 < 5
true
2 > 3 || 4 < 5
true
2 > 3 || 4 > 5
false both operands are false
!(2 > 3)
true operand is false
Logical AND Example
New Topics:
Logical AND
Logical AND and Nesting
If we have the && operator, do we need nesting?
if(BooleanExpression1) {
if(BooleanExpression2) {
Both conditions met
}
else {
Both conditions NOT met
}
}
else {
Both conditions NOT met
}
System.out.println("You "
+ score < 60 ? "Fail" : "Pass");