Intermediate Java
Jim White
Java Developer
boolean isLoggedIn = true;
boolean isAdmin = true;
// Both are true
if (isLoggedIn && isAdmin) {
System.out.println("Welcome admin!");
} else {
System.out.println("You shall not pass.");
}
Welcome admin!
&&
returns falseboolean isLoggedIn = false;
boolean isAdmin = true;
// Only one is true, so else is executed
if (isLoggedIn && isAdmin) {
System.out.println("Welcome admin!");
} else {
System.out.println("You shall not pass.");
}
You shall not pass.
true
boolean isAdmin = true;
boolean isModerator = false;
// Only one condition is true
if (isAdmin || isModerator) {
System.out.println("Welcome!");
} else {
System.out.println("You shall not pass.");
}
Welcome!
true
if either or both conditions are true
boolean isAdmin = true;
boolean isModerator = true;
// Both conditions are true
if (isAdmin || isModerator) {
System.out.println("Welcome!");
} else {
System.out.println("You shall not pass.");
}
Welcome!
true
to false
and false
to true
boolean isLoggedIn = false;
// isLoggedIn is false, so !isLoggedIn is true
if (!isLoggedIn) {
System.out.println("You need to log in!");
} else {
System.out.println("You are logged in, continue!");
}
You need to log in!
int score = 90;
boolean isAttending = false;
if (score > 80 && isAttending) {
System.out.println("Excellent work!");
} else if (score > 80 && !isAttending) {
System.out.println("Good work, but attendance is important.");
} else if (score <= 80 && isAttending) {
System.out.println("You need to work harder.");
} else {
System.out.println("You need to work harder and attend classes.");
}
Good work, but attendance is important.
The following table summarizes the values for &&
, ||
, and !
operators:
a |
b |
a && b |
a | | b | !a |
---|---|---|---|---|
true |
true |
true |
true |
false |
true |
false |
false |
true |
false |
false |
true |
false |
true |
true |
false |
false |
false |
false |
true |
boolean a = true && (!false || (true && false)); // a is true
boolean b = (7 <= 3) || (3 >= 5); // b is false
Intermediate Java