Relational and Logical Operators¶
(evaluate expressions as true or false)
Example
if (num < 0) {
System.out.println("Negative!!");
} else if (num <= 5) {
System.out.println("I'm small.");
} else {
System.out.println("I'm big.");
}
Relational Operators¶
Operator | Description |
---|---|
< | less than |
<= | less than or equal |
> | greater than |
>= | greater than or equal |
== | equal |
!= | not equal |
Logical Operators¶
Operator | Description |
---|---|
&& | and |
|| | or |
! | not |
Conditionals and Conditional Statement Structures¶
(changing execution of program depending on values)
If Conditional Statement¶
Use case: Want to execute a certain block of statement(s) in one particular case.
Pattern
if (condition) {
// code block - executed if condition is true
}
Example
int num = 5;
if (num < 10) {
System.out.println("num is smaller than 10!");
}
Output
num is smaller than 10!
If/Else Conditional Statement¶
Use case: Use when dealing with one or two cases (“this OR that!”).
Pattern
if (condition) {
// code block - executed if condition is true
} else {
// code block - executed if condition is false
}
Example
int num = 12;
if (num < 10) {
System.out.println("num is smaller than 10!");
} else {
System.out.println("num is larger or equal to 10!");
}
Output
num is larger or equal to 10!
If/Else-if Conditional Statement¶
Use case: Want to evaluate specific cases, not just one or the other.
Pattern
if (condition1) {
// code block - executed if condition1 is true
} else if (condition2) {
// code block - executed if condition2 is true (and if condition1 is false)
}
Example
int num = 10;
if (num < 10) {
System.out.println("num is smaller than 10!");
} else if (num == 10) {
System.out.println("num is equal to 10!");
}
Output
num is equal to 10!
If/Else-if/Else Conditional Statement¶
Use case: Use when you want to evaluate specific cases along with including a default case (“this OR this OR that!”).
Pattern
if (condition1) {
// code block - executed if condition1 is true
} else if (condition2) {
// code block - executed if condition2 is true (and if condition1 is false)
} else {
// code block - executed if all conditions are false
}
Example
int num = 12;
if (num < 10) {
System.out.println("num is smaller than 10!");
} else if (num == 10) {
System.out.println("num is equal to 10!");
} else {
System.out.println("num is larger than 10!");
}
Output
num is larger than 10!
If and If Conditional Statements¶
Use case: Want to evaluate multiple blocks of statements based on specific test cases.
Pattern
if (condition1) {
// code block - executed if condition1 is true
}
if (condition2) {
// code block - executed if condition2 is true
}
Example
int num = 5;
if (num < 10) {
System.out.println("num is smaller than 10!");
}
if (num < 2) {
System.out.println("num is smaller than 2!");
}
Output
num is smaller than 10!