Conditional Statements?
Conditional statements in Java help programs make decisions by running code when specific conditions become true.
For example:
- If a user enters a correct password, grant access.
- If the temperature is below 10°C, suggest wearing a coat.
- If the bank balance is below the required amount, deny a withdrawal.
In Java, we use conditional statements to write programs that can react differently based on inputs and conditions.
Types of Conditional Statements in Java
Java provides several types of conditional statements:
- if Statement: Runs code only if a specific condition is true.
- if-else Statement: Runs one set of code if the condition is true, or another set if it’s false.
- if-else-if Ladder: Checks several conditions in order, running the code for the first condition that’s true.
- Nested if Statements: Uses one if statement inside another to handle multiple conditions in layers.
- Ternary Operator (?:): A shorter way to write simple if-else conditions in a single line.
What is an if Statement?
The if
statement in Java runs code only when something is true. If the condition isn’t true, Java skips that code.
Syntax:
if([variable][comparison operator][value]) {
// If the condition is true, execute this code block within curly braces in Java-like syntax.
}
Explanation:
- The “if” keyword initiates the condition.
- The condition is enclosed within parentheses ( ).
- When the condition holds true, the statements enclosed within the curly braces `{ }` are triggered and executed accordingly.
- If the condition evaluates to false, the instructions within the curly braces { } are bypassed, and the program proceeds without executing that block.
Example of a Simple if
Statement
Output:
The number is positive.
Program execution continues…
Program execution continues…
Since number > 0
evaluates to true
, the statement inside the if
block runs.
Using if
with Relational Operators
You can use different comparison operators inside an if
condition:
Operator | Meaning | Example |
---|---|---|
== | Equal to | if (a == b) |
!= | Not equal to | if (a != b) |
> | Greater than | if (a > b) |
< | Less than | if (a < b) |
>= | Greater than or equal to | if (a >= b) |
<= | Less than or equal to | if (a <= b) |
Example: Check if a Number is Even
Visited 1 times, 1 visit(s) today