If-Else Program in Java | About, Syntax, Flowchart and Examples

If-Else Program in Java | About, Syntax, Flowchart and Examples

5 mins read46 Views Comment
Esha
Esha Gupta
Associate Senior Executive
Updated on Apr 16, 2024 12:27 IST

Have you ever wondered how programs make decisions and adapt to different situations? The answer lies in the power of if-else statements. These statements allow us to control the flow of our code based on specific conditions, enabling us to write flexible and responsive programs.

The if-else statement in Java is a fundamental control flow structure that allows for the conditional execution of code. It tests a condition: if the condition is true, one block of code is executed, and if the condition is false, another block (or none at all) is executed.

Let us see the working of the if-else statement starting with syntax, flowchart, explanation and then a very basic example.

Must read Conditional Statements in Java

Syntax of if-else statement

if (condition)

{

    // statements to execute if condition is true

}

else

{

    // statements to execute if condition is false

}

Flowchart of if-else statement

 

Explanation of How if-else Works

  1. The if-else statement begins with the keyword "if".
  2. Following the "if" keyword is a condition enclosed in parentheses.
  3. The condition is a Boolean expression, which means it can only evaluate to either true or false.
  4. If the condition evaluates to true, the code block enclosed in curly braces following the "if" keyword is executed.
  5. If the condition evaluates to false, the code block enclosed in curly braces following the "else" keyword is executed.

For example


 
// Program to illustrate if-else statement in Java
public class Main {
public static void main(String[] args) {
int i = 17;
if (i < 16) {
// Print the message "i is smaller" if the condition is true
System.out.println("i is smaller");
} else {
// Print the message "i is greater" if the condition is false
System.out.println("i is greater");
}
System.out.println("Outside the if-else block");
}
}
Copy code

Output

i is greater

Outside the if-else block

This example above clearly shows how an if-else program in java works!

If-else program in Java

Let’s see some if-else programs one by one.

Example 1:  Checking if a number is even or odd

Problem statement: Write a program that checks if a given number is even or odd.


 
// Program to check if a number is even or odd
public class EvenOddChecker {
public static void main(String[] args) {
int number = 10;
// Check if the remainder of dividing 'number' by 2 is equal to 0
if (number % 2 == 0) {
// If the condition is true, print 'number' is even
System.out.println(number + " is even");
} else {
// If the condition is false, print 'number' is odd
System.out.println(number + " is odd");
}
}
}
Copy code

Output

10 is even

The condition number % 2 == 0 checks if the remainder of dividing number by 2 is equal to 0. If it is, then number is even. Otherwise, number is odd.

Example 2:  Checking if a year is a leap year

Problem statement: Write a program that checks if a given year is a leap year.


 
// Program to check if a given year is a leap year
public class LeapYearChecker {
public static void main(String[] args) {
int year = 2000;
// Initialize a boolean variable 'isLeapYear' to store whether the year is a leap year or not
boolean isLeapYear = false;
if (year % 4 == 0) {
isLeapYear = true;
if (year % 100 == 0 && year % 400 != 0) {
isLeapYear = false;
}
}
if (isLeapYear) {
System.out.println(year + " is a leap year");
} else {
System.out.println(year + " is not a leap year");
}
}
}
Copy code

Output

2000 is a leap year

A leap year is a year that has 366 days instead of the usual 365 days. A year is a leap year if it is divisible by 4, except for years that are divisible by 100 but not by 400. The code checks these conditions using nested if-else statements.

Control Statements in C | Meaning and Types
Control Statements in C | Meaning and Types
Control statements in C are used to determine the order in which the instructions within a program are executed. They are of three types: Selection, Iteration & Jump statements. Think...read more

Learning If Statement in C
Learning If Statement in C
The if statement in C is a control structure that evaluates a condition. If the condition is true, it runs the associated code; if false, the code is ignored. It’s...read more

Learning Loops in C
Learning Loops in C
In C programming, a loop is a control structure that allows a set of instructions to be executed repeatedly based on a specified condition. Loops provide an efficient way to...read more

Example 3: Scenario-based Question

Problem Statement: Imagine you are using a ride-sharing app, like Uber or Ola. Sometimes, when the demand for rides is high, these apps activate something called “surge pricing”. This means that the cost of a ride might be higher than usual to balance the high demand with the available drivers.


 
#include < stdio.h >
int main() {
int surgePricingActive = 1;
if (surgePricingActive) {
printf("Surge pricing is active. Fares might be higher now.
");
} else {
printf("No surge pricing. Good time to book a ride!
");
}
return 0;
}
Copy code

Output

Surge pricing is active. Fares might be higher now.

In this code, We used the if-else statement to decide which message to display to the user based on the status of surge pricing. If surge pricing is active, it warns the user. Otherwise, it tells the user it’s a good time to book a ride.

 

Key Takeaways

  • An if-else statement in Java is a fundamental tool for controlling the flow of a program.
  • It evaluates a condition and executes the appropriate code block based on the outcome.
  • If-else statements are essential for making decisions, handling conditional scenarios, and controlling program flow in various programming applications.

FAQs

What is an If-Else Statement in Java?

An If-Else statement in Java is a fundamental control flow mechanism that allows a program to execute one block of code if a specified condition is true and another block of code if the condition is false. It's a way to make decisions in your program based on the evaluation of expressions.

How Does the If-Else Statement Work?

The If-Else statement evaluates a boolean expression (condition). If the condition evaluates to true, the program executes the block of code following the if statement. If the condition is false, the program executes the block of code following the else statement.

Can You Nest If-Else Statements in Java?

Yes, you can nest If-Else statements within each other in Java. This means you can have an If-Else statement inside another If or Else block. Nested If-Else statements are useful for checking multiple conditions.

When Should You Use an If-Else Statement?

You should use an If-Else statement when you need to execute different blocks of code based on the evaluation of a condition. It's ideal for scenarios where there are two possible paths of execution in your program.

Are There Alternatives to Using If-Else Statements in Java?

Yes, there are alternatives to using If-Else statements in Java for decision-making. The switch statement can sometimes be used as an alternative, particularly when you are checking the same variable against multiple constant values. For more complex conditions, however, If-Else statements or nested If-Else structures might be more appropriate.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio