In Java, conditional logic is primarily implemented using if
, if-else
, and if-else-if
statements, as well as switch
statements. Conditional logic in programming is used to execute certain pieces of code based on whether a specified condition evaluates to true or false. Conditional structures allow programs to make decisions, leading to more dynamic and flexible behavior.if Statement
The if
statement is used to specify a block of code to be executed if a condition is true.
if (condition) { // code to be executed if condition is true }
if-else Statement
The if-else
statement executes one block of code if a condition is true and another block of code if the condition is false.
if (condition) { // code to be executed if condition is true } else { // code to be executed if condition is false }
if-else-if Statement
The if-else-if
statement can be used for multiple conditions.
if (condition1) { // code to be executed if condition1 is true } else if (condition2) { // code to be executed if condition2 is true } else { // code to be executed if none of the above conditions are true }
switch Statement
The switch
statement is useful for decision-making among multiple choices based on a single variable or expression.
switch (expression) { case value1: // code to be executed if expression equals value1; break; case value2: // code to be executed if expression equals value2; break; default: // code to be executed if expression doesn't match any case; }
Ternary Operator
Java also has the ternary operator for conditional assignment, which can replace if-else
statements for simpler conditions.
int result = (condition) ? valueIfTrue : valueIfFalse;
Example
Here is an example that demonstrates the use of if
, if-else
, and if-else-if
statements:
public class ConditionalExample { public static void main(String[] args) { int num = 10; if (num > 0) { System.out.println("The number is positive."); } else if (num < 0) { System.out.println("The number is negative."); } else { System.out.println("The number is zero."); } } }
And here's an example that uses a switch
statement:
public class SwitchExample { public static void main(String[] args) { char grade = 'A'; switch (grade) { case 'A': System.out.println("Excellent!"); break; case 'B': System.out.println("Well done"); break; case 'C': System.out.println("You passed"); break; default: System.out.println("Invalid grade"); } } }