Q.
Explain any two conditional statements in java
Conditional Statements in Java
Conditional statements in Java allow you to control the flow of execution based on certain
conditions. These statements help in decision-making by executing a block of code only when a
specific condition is true. Two common conditional statements in Java are:
1. if statement
2. switch statement
1. if Statement
The if statement is used to evaluate a condition and execute a block of code if the condition is
true.
Syntax:
if (condition) {
// Block of code to be executed if the condition is true
}
Example:
public class IfExample {
public static void main(String[] args) {
int number = 10;
// Check if the number is positive
if (number > 0) {
System.out.println("The number is positive."); } }}
Explanation:
The condition number > 0 is checked. If it is true, the block of code inside the if statement is
executed. Since 10 > 0 is true, the message "The number is positive." is printed.
---2. switch Statement
The switch statement is used when you have multiple conditions based on the value of a single
variable or expression. It is more efficient when dealing with multiple possible values of a
variable.
Syntax:
switch (variable) {
case value1:
// Block of code executed when variable equals value1
break;
case value2:
// Block of code executed when variable equals value2
break;
// More cases can be added
default:
// Block of code executed if no case matches}
Conclusion:
The if statement is ideal for checking a single condition, while the switch statement is more
efficient when comparing a variable against multiple possible values. Both are useful for
controlling program flow based on specific conditions.