If Statement
java if statement condition boolean expression nested if equals logical operators && short-circuit voting eligibility login ATM withdrawal
Introduction
Imagine you're building a banking application.
If the customer has enough balance, allow the withdrawal.
If the password is correct, log the user in.
If the student scores more than 35 marks, mark the student as "Pass."
These decisions are made using the if statement.
The if statement is the simplest and most commonly used decision-making statement in Java.
It allows your program to execute a block of code only when a specified condition is true.
Almost every real-world Java application uses if statements—from authentication systems and payment gateways to inventory management and cloud applications.
In this lesson, you'll learn:
- What an
ifstatement is - Syntax
- How conditions work
- Boolean expressions
- Nested
ifstatements - Real-world examples
- Best Practices
- Common Mistakes
- Hands-on Exercises
- Professional Interview Questions
What is an If Statement?
An if statement evaluates a condition.
If the condition is true, Java executes the associated block of code.
If the condition is false, Java skips that block.
Syntax:
if (condition) {// code to execute}
Your First If Statement
int age = 20;if (age >= 18) {System.out.println("Eligible to Vote");}
Output:
Eligible to Vote
Since the condition is true, the message is printed.
False Condition
int age = 15;if (age >= 18) {System.out.println("Eligible to Vote");}
Output:
(No Output)
The condition is false, so Java skips the block.
Understanding the Condition
The expression inside parentheses must evaluate to a boolean value (true or false).
Example:
int marks = 80;if (marks >= 35) {System.out.println("Pass");}
Here:
marks >= 35↓80 >= 35↓true
Using Boolean Variables
Conditions don't always need comparison operators.
You can use a boolean variable directly.
boolean loggedIn = true;if (loggedIn) {System.out.println("Welcome!");}
Output:
Welcome!
Multiple Conditions
Logical operators can combine multiple conditions.
int age = 25;boolean citizen = true;if (age >= 18 && citizen) {System.out.println("Eligible to Vote");}
Both conditions must be true.
Real-World Example: ATM Withdrawal
double balance = 5000;double withdrawAmount = 2500;if (balance >= withdrawAmount) {balance -= withdrawAmount;System.out.println("Withdrawal Successful");System.out.println("Remaining Balance: " + balance);}
Output:
Withdrawal SuccessfulRemaining Balance: 2500.0
Real-World Example: Login Verification
String username = "admin";String password = "secret";if (username.equals("admin")&& password.equals("secret")) {System.out.println("Login Successful");}
Output:
Login Successful
Notice the use of .equals() for comparing strings.
Nested If Statement
An if statement can exist inside another if statement.
boolean loggedIn = true;boolean admin = true;if (loggedIn) {if (admin) {System.out.println("Admin Dashboard");}}
Output:
Admin Dashboard
The inner if executes only if the outer condition is true.
Flow Diagram
Condition↓True?↓Yes → Execute Block↓Continue ProgramNo↓Skip Block↓Continue Program
If Statement with Method Calls
public static boolean isEligible(int age) {return age >= 18;}int age = 22;if (isEligible(age)) {System.out.println("Eligible");}
Using methods keeps your code clean and reusable.
Real-World Enterprise Example
An e-commerce application allows checkout only if:
- The customer is logged in.
- The cart is not empty.
boolean loggedIn = true;int cartItems = 3;if (loggedIn && cartItems > 0) {System.out.println("Proceed to Checkout");}
This kind of logic is common in enterprise applications.
Best Practices
Keep Conditions Readable
Instead of writing long expressions directly inside an if, use descriptive variables.
boolean eligible =age >= 18 && citizen;if (eligible) {System.out.println("Eligible");}
Always Use Curly Braces
Good:
if (age >= 18) {System.out.println("Adult");}
Even for a single statement, braces improve readability and reduce bugs.
Avoid Deep Nesting
Instead of many nested if statements, consider breaking the logic into smaller methods or using early returns where appropriate.
Compare Strings Correctly
Use:
name.equals("Rahul")
Avoid:
name == "Rahul"
== compares object references, not string contents.
Common Mistakes
Using Assignment Instead of Comparison
Incorrect:
if (age = 18)
Correct:
if (age == 18)
Forgetting Braces
Although Java allows single-line if statements without braces, always include braces for clarity.
Comparing Strings with ==
Always use .equals() when comparing string values.
Writing Complex Conditions
If a condition is difficult to read, split it into smaller boolean variables.
Hands-on Exercise
Create a Java program that:
- Checks whether a person is eligible to vote.
- Checks whether a student has passed.
- Verifies whether a user is logged in.
- Allows ATM withdrawal only if the balance is sufficient.
- Uses a nested
ifstatement for admin access. - Uses a helper method that returns a boolean and calls it inside an
ifstatement. - Refactors one complex condition into descriptive boolean variables.
Summary
The if statement is the foundation of decision-making in Java.
It allows your program to execute code only when a condition evaluates to true.
From authentication and payment validation to business rules and user permissions, the if statement is one of the most frequently used constructs in professional Java development.
Mastering it will make learning more advanced control flow statements much easier.
Key Takeaways
- The
ifstatement executes code only when its condition istrue. - Conditions must evaluate to a boolean value.
- Logical operators allow multiple conditions to be combined.
- Nested
ifstatements enable multi-level decision-making. - Use
.equals()for comparingStringvalues. - Keep conditions simple, readable, and well-formatted.
Professional Interview Questions
1What is the purpose of the if statement in Java?
Professional Answer
The if statement is used for conditional execution. It evaluates a boolean expression, and if the expression is true, the associated block of code is executed. If the expression is false, the block is skipped.
Follow-up Questions
- What type of expression can be used inside an if statement?
- Can you nest if statements?
Interview Tip: Mention that Java requires a boolean expression in an if statement, unlike some languages that allow numeric values.
2Can you use multiple conditions in an if statement?
Professional Answer
Yes. Multiple conditions can be combined using logical operators such as && (AND), || (OR), and ! (NOT) to create more complex decision-making logic.
Follow-up Questions
- What is short-circuit evaluation?
- What is the difference between && and &?
Interview Tip: Explain that && and || use short-circuit evaluation, which can improve performance and avoid unnecessary evaluations.
3Why should you always use curly braces with if statements?
Professional Answer
Although Java allows braces to be omitted for a single statement, using braces consistently improves readability, prevents accidental bugs during future modifications, and aligns with professional coding standards.
Follow-up Questions
- Does Java require braces for a single statement?
- What coding standards do you follow?
Interview Tip: Emphasize maintainability and team collaboration rather than just syntax.