Conditional statements are an essential part of any programming language, including Java. The if...else statement allows you to make decisions in your code by executing different blocks of code based on specified conditions. In this tutorial, we will explore the if...else statement in Java, its syntax, usage, and common scenarios.
Purpose and Usage: The if...else statement in Java is used for conditional execution of code. It allows your program to make decisions based on specified conditions. Depending on whether a condition is true or false, different blocks of code will be executed.
Conditional Execution: With if...else, you can specify that if a certain condition is met (evaluates to true), one block of code should execute, and if the condition is not met (evaluates to false), another block of code should execute.
if (condition) { // Code to execute if the condition is true } else { // Code to execute if the condition is false }
Nested if...else Statements: You can also nest if...else statements to handle more complex conditions.
Comparing Values: if...else conditions often involve comparisons using relational operators like == (equal), != (not equal), < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to).
Logical Operators: Logical operators (&& for logical AND, || for logical OR, ! for logical NOT) allow you to combine multiple conditions.
int age = 18; if (age >= 18) { System.out.println("You are an adult."); } else { System.out.println("You are a minor."); }
int number = 7; if (number > 0) { System.out.println("The number is positive."); } if (number % 2 == 0) { System.out.println("The number is even."); }
int score = 85; if (score >= 90) { System.out.println("A"); } else if (score >= 80) { System.out.println("B"); } else if (score >= 70) { System.out.println("C"); } else { System.out.println("D"); }
The if...else statement is a fundamental tool for controlling the flow of your Java programs based on specific conditions. By mastering the syntax and understanding conditional expressions and relational operators, you can write code that responds dynamically to different situations, making your Java applications more flexible and responsive.