conditional-statements
Conditional statements are core features in Java that let you control how your program behaves based on certain conditions. They allow your code to make decisions and choose between different actions, making your programs more dynamic and responsive.
Why Use Conditional Statements?
Example:
Example:
Example:
- Decision Making: Execute different code depending on specific conditions.
- Flexibility: Handle various scenarios and user inputs.
- Logic Control: Direct the flow of your program for better logic and organization.
Main Types of Conditional Statements in Java
1. if-else Statement
The if-else statement checks a condition. If the condition is true, one block of code runs; if it’s false, another block runs.
Syntax:
1. if-else Statement
The if-else statement checks a condition. If the condition is true, one block of code runs; if it’s false, another block runs.
Syntax:
if (condition) { // Executes if condition is true} else { // Executes if condition is false}
Example:
int age = 20;if (age >= 18) { System.out.println("You are an adult.");} else { System.out.println("You are not an adult.");}
2. switch Statement
The switch statement is helpful when you need to choose between multiple possible options based on the value of a variable or expression.
Syntax:
The switch statement is helpful when you need to choose between multiple possible options based on the value of a variable or expression.
Syntax:
switch (expression) { case value1: // Code for value1 break; case value2: // Code for value2 break; // ... more cases ... default: // Code if no case matches}
Example:
int day = 3;switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; default: System.out.println("Another day");}
3. Ternary Operator (Conditional Operator)
The ternary operator is a shorthand way to write simple if-else statements in one line. It returns one of two values based on a condition.
Syntax:
The ternary operator is a shorthand way to write simple if-else statements in one line. It returns one of two values based on a condition.
Syntax:
variable = (condition) ? value_if_true : value_if_false;
Example:
int number = 10;String result = (number % 2 == 0) ? "Even" : "Odd";System.out.println(result);
Key Points
- Conditional statements are essential for making decisions in your programs.
- Use if-else for binary decisions, switch for multiple choices, and the ternary operator for concise conditions.
- These statements help your code react to different situations and inputs, making your applications smarter and more interactive.