The if-else
statement in Java allows you to execute certain code based on a condition. It helps you control the flow of your program by making decisions. The basic structure is simple:
if (condition) { // Code to execute if the condition is true } else { // Code to execute if the condition is false }
Let's start with a simple example to check if a number is positive or negative:
public class IfElseExample { public static void main(String[] args) { int number = -5; if (number > 0) { System.out.println("The number is positive."); } else { System.out.println("The number is negative."); } } }
In the code above, we used the condition number > 0
. If this condition is true (i.e., if the number is greater than 0), the program prints "The number is positive." Otherwise, it prints "The number is negative."
You can extend the if-else structure using else-if
to check for multiple conditions. Here's an example to check if a number is positive, negative, or zero:
public class ElseIfExample { 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."); } } }
You can also combine multiple conditions using logical operators like &&
(AND), ||
(OR), and !
(NOT). For example:
public class CombinedConditions { public static void main(String[] args) { int age = 20; boolean hasLicense = true; if (age >= 18 && hasLicense) { System.out.println("You can drive."); } else { System.out.println("You cannot drive."); } } }
Java allows you to use if-else statements inside other if-else statements, which are called nested if-else statements. Here's an example:
public class NestedIfElseExample { public static void main(String[] args) { int num = 15; if (num > 0) { if (num % 2 == 0) { System.out.println("The number is positive and even."); } else { System.out.println("The number is positive and odd."); } } else { System.out.println("The number is non-positive."); } } }
Java also provides the ternary operator ?
as a shorthand for simple if-else statements:
public class TernaryExample { public static void main(String[] args) { int number = 10; String result = (number > 0) ? "Positive" : "Non-positive"; System.out.println(result); } }
if
to execute code when a condition is true.else
for code to run when the condition is false.else-if
allows you to check multiple conditions.&&
, ||
, and !
help combine conditions.if-else
statements.Practice Challenge: Create a program that checks if a given year is a leap year or not using if-else statements.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!