Java Selection Statements: Making Smart Decisions in Your Code
Satish Jassal
?? Full Stack Engineer ? | Elevate your digital presence! Crafting brilliance for portfolios, e-commerce, podcasts, events & custom web apps. ???? #nextjs #nodejs #innovation
if statement: The if statement in Java allows you to execute a block of code only if a given condition is true. If the condition is false, the code block is skipped.
Syntax:
f (condition){
? ? // Code block to execute if the condition is true
}
Example:
int x = 10;
if (x > 5) {
? ? System.out.println("x is greater than 5");
}
if-else statement: The if-else statement in Java allows you to execute one block of code if the condition is true, and another block if the condition is false.
Syntax:
if (condition)
? ? // Code block to execute if the condition is true
} else {
? ? // Code block to execute if the condition is false
}{
Example:
int x = 3;
if (x > 5) {
? ? System.out.println("x is greater than 5");
} else {
? ? System.out.println("x is not greater than 5");
}
领英推荐
if-else if-else statement: The if-else if-else statement in Java allows you to check multiple conditions in sequence and execute different code blocks based on the first true condition encountered.
if (condition1) {
? ? // Code block to execute if condition1 is true
} else if (condition2) {
? ? // Code block to execute if condition2 is true
} else {
? ? // Code block to execute if all conditions are false
}
Example:
int x = 7
if (x > 10) {
? ? System.out.println("x is greater than 10");
} else if (x > 5) {
? ? System.out.println("x is greater than 5 but not greater than 10");
} else {
? ? System.out.println("x is not greater than 5");
};
Switch statement: Java has a built-in switch statement, which allows you to perform multi-way branching based on the value of an expression.
Syntax:
int variable = 2;
switch (variable) {
? ? case value1:
? ? ? ? // Code block for case value1
? ? ? ? break;
? ? case value2:
? ? ? ? // Code block for case value2
? ? ? ? break;
? ? // Add more cases as needed
? ? default:
? ? ? ? // Code block for default case
}
Example:
int dayOfWeek = 3;
switch (dayOfWeek) {
? ? case 1:
? ? ? ? System.out.println("Sunday");
? ? ? ? break;
? ? case 2:
? ? ? ? System.out.println("Monday");
? ? ? ? break;
? ? // Add more cases as needed
? ? default:
? ? ? ? System.out.println("Invalid day");
}
In Java, you can choose the appropriate control flow statement depending on the complexity and requirements of your code logic. if-else statements are often used for simple branching, while switch statements are useful for multi-case scenarios with constant expressions.
This is all about Selection Statement in next article i will post Iteration and jump staments.
That's It For Now!
If it's helpful like or comment for any suggestions.
If you have any query, please feel free to contact me.
Cheers ??.
--
6 个月Superb...