Practical Applications of If-Else
One of the most common applications of if-else
statements is to handle user input. You can use if-else
statements to validate and process user input, ensuring that the program behaves as expected.
Here's an example of using if-else
to check user input:
import java.util.Scanner;
public class UserInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
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.");
}
}
}
In this example, the program prompts the user to enter a number, and then uses an if-else
statement to determine whether the number is positive, negative, or zero.
Implementing Business Logic
if-else
statements are also commonly used to implement business logic in applications. You can use if-else
statements to make decisions based on various conditions and execute the appropriate code accordingly.
For example, consider a simple e-commerce application that calculates the total cost of an order based on the customer's location and the order amount. You can use if-else
statements to handle different scenarios:
double orderAmount = 100.0;
String customerLocation = "USA";
double shippingCost;
if (customerLocation.equals("USA")) {
if (orderAmount >= 50.0) {
shippingCost = 0.0; // Free shipping for orders over $50
} else {
shippingCost = 5.0;
}
} else {
shippingCost = 10.0; // International shipping cost
}
double totalCost = orderAmount + shippingCost;
System.out.println("Total cost: $" + totalCost);
In this example, the if-else
statements are used to determine the shipping cost based on the customer's location and the order amount, and then calculate the total cost of the order.
Conditional Execution in Loops
if-else
statements can also be used within loops to control the execution of code based on certain conditions. This is particularly useful when you need to perform different actions for different elements in a collection or during each iteration of a loop.
Here's an example of using if-else
statements within a for
loop:
int[] numbers = {5, 10, -3, 0, 8};
for (int number : numbers) {
if (number > 0) {
System.out.println(number + " is positive.");
} else if (number < 0) {
System.out.println(number + " is negative.");
} else {
System.out.println(number + " is zero.");
}
}
In this example, the if-else
statements are used within the for
loop to determine whether each number in the numbers
array is positive, negative, or zero, and then print the appropriate message.
These are just a few examples of the practical applications of if-else
statements in Java programming. The versatility of if-else
statements allows you to implement a wide range of decision-making logic in your applications.