For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
The if-else statement in Java programming forms the backbone of decision-making logic in programming. It allows your code to make choices based on conditions, executing different blocks of code depending on whether a condition evaluates to true or false.
If else Java constructs are essential for creating dynamic and responsive applications that can adapt to different inputs and situations. Whether you're building a simple calculator or a complex enterprise application, mastering if-else statements is important for learning Java programming.
Sharpen your Java expertise while learning full-stack development—join upGrad’s Software Engineering Course today.
The most basic form of conditional logic is the simple if statement. It executes a block of code only if a specified condition is true.
if (condition) {
// Code to execute when condition is true
}
Problem Statement
Write a program that checks if a number is positive and prints an appropriate message.
public class PositiveNumberCheck {
public static void main(String[] args) {
int number = 15;
// Check if number is positive
if (number > 0) {
System.out.println("The number " + number + " is positive.");
}
System.out.println("Program completed.");
}
}
Output
The number 15 is positive.
Program completed.
This simple if statement checks a single condition. When the condition number > 0 evaluates to true, the code block executes, printing the message. The program continues with the rest of the code afterwards.
Master Data Science and AI with experts—join IIIT-B’s Executive Diploma program now.
The if-else statement java syntax expands the basic if statement by adding an alternative path when the condition is false.
if (condition) {
// Code to execute when condition is true
} else {
// Code to execute when condition is false
}
Problem Statement
Create a program that determines if a student has passed or failed based on their score, with the passing mark set at one value.
public class PassFailCheck {
public static void main(String[] args) {
int score = 75;
int passingMark = 60;
// Check if student passed or failed
if (score >= passingMark) {
System.out.println("Congratulations! You passed the exam.");
} else {
System.out.println("Sorry, you failed the exam. Please try again.");
}
}
}
Output
Congratulations! You passed the exam.
This if-else program in java demonstrates how to handle two alternative outcomes. When the score is greater than or equal to the passing mark, it executes the first block otherwise, it executes the second block.
Ready to go beyond Java? Learn how to integrate it with cloud and DevOps through upGrad’s certification course.
When you need to check multiple conditions in sequence, the else if ladder in java is the ideal choice. It allows you to test several conditions and execute different code blocks accordingly.
if (condition1) {
// Code to execute when condition1 is true
} else if (condition2) {
// Code to execute when condition1 is false and condition2 is true
} else if (condition3) {
// Code to execute when condition1 and condition2 are false and condition3 is true
} else {
// Code to execute when all conditions are false
}
Problem Statement
Develop a grading system that assigns letter grades based on numerical scores using an if-else if ladder.
public class GradingSystem {
public static void main(String[] args) {
int score = 78;
char grade;
// Determine the grade using if-else if ladder
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Score: " + score);
System.out.println("Grade: " + grade);
}
}
Output
Score: 78
Grade: C
This if else if ladder in java example demonstrates how to evaluate multiple conditions in sequence. The program checks each condition from top to bottom until it finds one that's true, then executes the corresponding code block.
Sometimes, you need to check conditions within conditions. Nested if statements allow you to create complex decision structures where certain conditions are only evaluated if other conditions are met first.
if (outerCondition) {
// Outer code
if (innerCondition) {
// Inner code executed when both conditions are true
}
}
Problem Statement
Create a program that checks eligibility for a discount based on membership status and purchase amount in an online shopping application.
public class DiscountEligibility {
public static void main(String[] args) {
boolean isMember = true;
double purchaseAmount = 8500.50;
// Check discount eligibility with nested if
if (isMember) {
System.out.println("Welcome, member!");
if (purchaseAmount >= 7500) {
System.out.println("You qualify for a 15% discount.");
double discount = purchaseAmount * 0.15;
System.out.println("Discount amount: ₹" + discount);
System.out.println("Final price: ₹" + (purchaseAmount - discount));
} else {
System.out.println("You qualify for a 5% member discount.");
double discount = purchaseAmount * 0.05;
System.out.println("Discount amount: ₹" + discount);
System.out.println("Final price: ₹" + (purchaseAmount - discount));
}
} else {
if (purchaseAmount >= 15000) {
System.out.println("You qualify for a 10% discount.");
double discount = purchaseAmount * 0.10;
System.out.println("Discount amount: ₹" + discount);
System.out.println("Final price: ₹" + (purchaseAmount - discount));
} else {
System.out.println("Sorry, no discount available.");
System.out.println("Final price: ₹" + purchaseAmount);
}
}
}
}
Output
Welcome, member!
You qualify for a 15% discount.
Discount amount: ₹1275.075
Final price: ₹7225.425
This example demonstrates how nested if statements evaluate conditions hierarchically in a typical e-commerce scenario. The program first checks if the customer is a member, then evaluates different purchase amount thresholds based on that result, calculating appropriate discounts in Rupees.
Working with strings in conditional statements requires special handling since they are objects, not primitive types.
Problem Statement
Create a simple language translator that converts basic greetings based on the language selected.
public class GreetingTranslator {
public static void main(String[] args) {
String language = "Spanish";
String greeting;
// Translate greeting based on language using if-else
if (language.equals("English")) {
greeting = "Hello";
} else if (language.equals("Spanish")) {
greeting = "Hola";
} else if (language.equals("French")) {
greeting = "Bonjour";
} else if (language.equals("German")) {
greeting = "Guten Tag";
} else {
greeting = "Hello (Default)";
}
System.out.println("Language: " + language);
System.out.println("Greeting: " + greeting);
}
}
Output
Language: Spanish
Greeting: Hola
This example demonstrates how to use the equals() method to compare strings in if else statement java constructs. Remember that using == for string comparison often leads to unexpected results.
The ternary operator provides a concise way to write simple if-else statements in a single line.
variable = (condition) ? valueIfTrue : valueIfFalse;
Problem Statement
Write a program that finds the maximum of two numbers using the ternary operator.
public class FindMaxTernary {
public static void main(String[] args) {
int num1 = 45;
int num2 = 72;
// Find maximum using ternary operator
int max = (num1 > num2) ? num1 : num2;
System.out.println("Number 1: " + num1);
System.out.println("Number 2: " + num2);
System.out.println("Maximum: " + max);
}
}
Output
Number 1: 45
Number 2: 72
Maximum: 72
The ternary operator provides a compact alternative to if-else for simple conditional assignments. It's particularly useful when you need to assign a value based on a condition.
Problem Statement
Develop a simplified weather advisory system that provides recommendations based on temperature and weather conditions.
public class WeatherAdvisory {
public static void main(String[] args) {
double temperature = 28.5; // in Celsius
String conditions = "Sunny";
System.out.println("Current Weather: " + temperature + "°C, " + conditions);
System.out.println("Today's Recommendations:");
// Generate weather advisories using if-else statements
if (temperature > 30) {
System.out.println("- Heat advisory: Stay hydrated and avoid outdoor activities");
if (conditions.equals("Sunny")) {
System.out.println("- UV warning: Apply sunscreen SPF 50+");
System.out.println("- Wear a hat and sunglasses");
}
} else if (temperature > 25) {
System.out.println("- Warm weather alert: Stay in shade during peak hours");
if (conditions.equals("Sunny")) {
System.out.println("- Apply sunscreen SPF 30+");
} else if (conditions.equals("Cloudy")) {
System.out.println("- UV levels may still be high despite cloud cover");
}
} else if (temperature > 15) {
System.out.println("- Mild conditions: Ideal for outdoor activities");
if (conditions.equals("Rainy")) {
System.out.println("- Carry an umbrella");
}
} else if (temperature > 5) {
System.out.println("- Cool weather: Wear a light jacket");
} else {
System.out.println("- Cold weather warning: Wear warm clothing");
if (temperature < 0) {
System.out.println("- Freezing conditions: Watch for ice on roads and sidewalks");
}
}
}
}
Output
Current Weather: 28.5°C, Sunny
Today's Recommendations:
- Warm weather alert: Stay in shade during peak hours
- Apply sunscreen SPF 30+
This real-world example demonstrates how if else java statements can be used to create practical systems that respond to multiple conditions. The weather advisory system evaluates both temperature ranges and specific weather conditions to provide relevant recommendations.
To write clean and maintainable if-else statements:
The if-else statement in Java is a key tool for making decisions in your code. It allows a program to choose different paths based on certain conditions. Starting with the basic if-else for simple true/false decisions, and moving to more detailed checks using else-if ladders or nested if-else, this structure helps your program respond to different inputs or situations.
By learning how to use these conditional statements well, you can write code that is not only clean and readable, but also efficient and reliable. Whether you're working on a small tool or a large application, using if-else logic correctly helps your program behave smartly as conditions change.
If-else statements evaluate any boolean condition and are flexible for complex comparisons. Switch statements work with specific values and are more efficient for multiple equality checks on a single variable. The choice between them depends on your specific use case and the complexity of your conditions.
Yes, but only if there's a single statement to execute. However, it's best practice to always use curly braces to prevent logical errors and improve code readability. Many coding standards require curly braces even for single-line blocks to maintain consistency and reduce bug risks.
Always use the .equals() method or .equalsIgnoreCase() for case-insensitive comparison. The == operator compares object references, not string content. This is one of the most common mistakes in Java programming and can lead to subtle bugs that are difficult to track down.
The else if ladder in Java allows you to test multiple conditions in sequence and execute code based on the first true condition. It's ideal for scenarios with multiple alternative paths. This construct improves code readability compared to multiple separate if statements by clearly showing the relationship between conditions.
Break complex conditions into methods with descriptive names, use early returns for edge cases, or consider redesigning with switch statements or polymorphism for better code organization. You can also use the Strategy Pattern to encapsulate different behaviors based on conditions, making your code more maintainable.
Technically, there's no limit to the number of else-if conditions, but too many can harm readability. Consider refactoring to switch statements or separate methods if there are more than 3-4 conditions. Some development teams set specific limits in their coding guidelines to ensure code remains understandable.
The ternary operator (condition ? valueIfTrue : valueIfFalse) is a compact form of if-else for simple assignments. Use it for straightforward conditions that fit on one line. Avoid nested ternary operators as they significantly reduce code readability and can lead to bugs that are difficult to identify.
No, interfaces can only contain method signatures, constants, default methods, static methods, and nested types. If-else statements are implementation details that belong in classes. This separation is fundamental to Java's design, enforcing a clear distinction between what a class does and how it does it.
Yes, switch statements can be more efficient for multiple equality checks on a single variable as they use jump tables. For complex boolean expressions, if-else is more appropriate. Modern JVMs optimize both constructs, but the difference can be noticeable in performance-critical code with many conditions.
Use logical operators like && (AND) and || (OR) to combine multiple conditions. For complex combinations, consider breaking them into separate boolean variables with descriptive names. Remember that Java uses short-circuit evaluation, which can improve performance by skipping unnecessary condition checks.
Arrange conditions from most specific to most general, or from most likely to occur to least likely for performance optimization. Always include a final else as a catch-all. This approach not only improves code efficiency but also makes the intention clear to other developers who may need to maintain your code.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.