Java If...else in Java
if-else in Java
The if-else statement in Java is used to perform a decision-making operation. It allows you to execute a block of code if a specified condition is true, and a different block of code if the condition is false.
Syntax:
if (condition) { // block of code if condition is true} else { // block of code if condition is false}Explanation:
ifcondition: Theifstatement evaluates the boolean condition. If it evaluates totrue, the block of code inside theifstatement is executed.elseblock: If the condition evaluates tofalse, the block of code inside theelseis executed.
Example 1: Simple if-else Statement
public class IfElseExample { public static void main(String[] args) { int number = 10; if (number > 0) { System.out.println("The number is positive."); } else { System.out.println("The number is not positive."); } }}Output:
The number is positive.Example 2: if-else with else if
You can use else if to test multiple conditions.
public class IfElseIfExample { public static void main(String[] args) { int number = 0; if (number > 0) { System.out.println("The number is positive."); } else if (number < 0) { System.out.println("The number is negative."); } else { System.out.println("The number is zero."); } }}Output:
The number is zero.Example 3: Nested if-else
You can also nest if-else statements inside one another.
public class NestedIfElseExample { public static void main(String[] args) { int number = 5; if (number != 0) { if (number > 0) { System.out.println("The number is positive."); } else { System.out.println("The number is negative."); } } else { System.out.println("The number is zero."); } }}Output:
The number is positive.Ternary Operator (Shorter Version of if-else)
Java provides a shorthand version of if-else known as the ternary operator. It's used when you want to assign a value based on a condition.
Syntax:
variable = (condition) ? value_if_true : value_if_false;Example:
public class TernaryOperatorExample { public static void main(String[] args) { int number = 10; String result = (number > 0) ? "Positive" : "Negative or Zero"; System.out.println(result); }}Output:
PositiveKey Points to Remember:
ifevaluates the condition. If it’s true, the associated block of code is executed.else ifallows you to test additional conditions if the previous ones are false.elseis executed if none of theiforelse ifconditions are true.Use the ternary operator for simpler conditional assignments.
Let me know if you'd like more examples or explanations! ?