Java If Statement
The if
statement in Java is used to execute a block of code if a specified condition is true. It's a fundamental control structure that allows your program to make decisions.
Key Topics
1. Syntax
The basic syntax of an if
statement is:
if (condition) {
// Code to execute if condition is true
}
2. Example
Here's a simple example of using an if
statement:
public class IfExample {
public static void main(String[] args) {
int number = 10;
if (number > 5) {
System.out.println("The number is greater than 5.");
}
}
}
3. Nested If Statements
You can place an if
statement inside another if
statement to create a nested structure.
if (condition1) {
// Executes if condition1 is true
if (condition2) {
// Executes if condition2 is true
}
}
Key Takeaways
- The
if
statement executes code only if a specified condition is true. - Conditions must result in a boolean value (
true
orfalse
). - Nested
if
statements allow for more complex decision-making.