if statements
If Statements in Java
The if
statement is one of the most fundamental control structures in Java. It allows you to execute a block of code based on whether a condition is true or false. In this section, we'll explore the different types of if
statements in Java and how to use them effectively with examples.
1. What is an if
Statement?
if
Statement?An if
statement in Java is used to make decisions in your code. It evaluates a condition (an expression that returns a boolean value: true
or false
), and if the condition is true, the block of code inside the if
statement is executed. If the condition is false, the code inside the if
statement is skipped.
Syntax:
Example:
In this example, the condition age >= 18
is checked. Since the condition is true, the message "You are eligible to vote." is printed.
2. if-else
Statement
if-else
StatementThe if-else
statement allows you to execute one block of code if the condition is true and another block of code if the condition is false.
Syntax:
Example:
In this example, the condition age >= 18
is false, so the message "You are not eligible to vote." is printed.
3. if-else if-else
Ladder
if-else if-else
LadderThe if-else if-else
ladder is used when you have multiple conditions to check. It allows you to execute different blocks of code depending on which condition is true.
Syntax:
Example:
In this example, the program checks multiple conditions to determine the grade based on the value of marks
.
4. Nested if
Statements
if
StatementsYou can place one if
statement inside another if
statement. This is called a nested if
statement. It allows you to check for a condition inside another condition.
Syntax:
Example:
In this example, the program first checks if the number is positive. If it is, it then checks if the number is even.
5. Ternary Operator (Shortcut for if-else
)
if-else
)The ternary operator is a shorthand way of writing an if-else
statement. It takes three operands and is used to evaluate a condition and return one of two values based on whether the condition is true or false.
Syntax:
Example:
In this example, the ternary operator checks if age >= 18
. If true, it assigns "Eligible to vote" to result
; otherwise, it assigns "Not eligible to vote".
Conclusion
The if
statement is a powerful tool for making decisions in your Java programs. By using if
, if-else
, and if-else if-else
statements, you can control the flow of your program based on various conditions. Nested if
statements and the ternary operator provide additional flexibility for more complex decision-making.
For more Java tutorials and resources, visit codeswithpankaj.com.
Last updated