Using if Statements in Java
Course: Core Java Training
Topic: Using if Statements
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy Official Website
1. Introduction to if Statements
In Java, an if statement is a decision-making statement that allows a program to execute a block of code only when a specified condition evaluates to true. It helps a program make decisions based on input, calculations, and Boolean expressions.
Without conditional statements, a program would generally execute instructions sequentially. The if statement introduces decision-making logic, allowing the program to respond differently to different situations.
For example, an application may use an if statement to check whether a user is eligible to vote, whether a student has passed an examination, whether an account balance is sufficient, or whether a number is positive.
2. Learning Objectives
- Understand the purpose and syntax of an
if statement.
- Learn how Java evaluates Boolean conditions.
- Write simple conditional programs.
- Use relational and logical operators in conditions.
- Understand the difference between independent and nested conditions.
- Identify common errors in conditional statements.
- Apply
if statements to practical programming problems.
3. What Is a Condition in Java?
A condition is an expression that evaluates to either true or false. An if statement uses this Boolean result to decide whether its body should execute.
Conditions are commonly created using comparison operators such as:
| Operator |
Meaning |
Example |
Result |
== |
Equal to |
5 == 5 |
true |
!= |
Not equal to |
5 != 3 |
true |
> |
Greater than |
8 > 4 |
true |
< |
Less than |
2 < 7 |
true |
>= |
Greater than or equal to |
5 >= 5 |
true |
<= |
Less than or equal to |
4 <= 3 |
false |
Java requires the condition in an if statement to be a Boolean expression. Unlike some programming languages, Java does not automatically treat integers such as 1 or 0 as Boolean values.
4. Syntax of an if Statement
The basic syntax of an if statement is:
if (condition) {
// Code executes when condition is true
}
Explanation:
if is the Java keyword that begins the conditional statement.
- The condition is written inside parentheses.
- The condition must evaluate to a Boolean value.
- The statements inside the braces execute only when the condition is
true.
- If the condition is
false, the body is skipped.
5. How an if Statement Works
When Java encounters an if statement, it evaluates the condition and chooses whether to execute the associated block.
- The program reaches the
if statement.
- Java evaluates the condition inside the parentheses.
- If the condition evaluates to
true, the statements inside the block execute.
- If the condition evaluates to
false, the block is skipped.
- Execution continues with the next statement after the block.
The following example demonstrates this process.
public class IfExample {
public static void main(String[] args) {
int age = 20;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
System.out.println("Program completed.");
}
}
Output:
You are eligible to vote.
Program completed.
Explanation: The variable age contains 20. Since 20 >= 18 evaluates to true, the first message is printed. The final statement executes regardless of whether the condition is true or false.
6. Simple if Statement Example
A simple if statement is useful when a particular action should occur only if a condition is satisfied.
public class PositiveNumber {
public static void main(String[] args) {
int number = 15;
if (number > 0) {
System.out.println("The number is positive.");
}
}
}
Output:
The number is positive.
If the value of number changes to -15, the condition number > 0 becomes false, so no message is printed.
7. Using if Statements with Variables
Variables store values that can be evaluated in conditional expressions. The condition determines which action is performed for the current value.
public class TemperatureCheck {
public static void main(String[] args) {
int temperature = 35;
if (temperature > 30) {
System.out.println("It is a hot day.");
}
if (temperature < 15) {
System.out.println("It is a cold day.");
}
}
}
Output:
It is a hot day.
Explanation: The first condition is true because 35 is greater than 30. The second condition is false because 35 is not less than 15. Since these are two independent if statements, Java evaluates both conditions.
8. Using if Statements with Relational Operators
Relational operators compare two values and produce a Boolean result. They are frequently used in conditions involving marks, ages, prices, salaries, and numeric ranges.
public class MarksCheck {
public static void main(String[] args) {
int marks = 75;
if (marks >= 40) {
System.out.println("Student has passed.");
}
if (marks >= 90) {
System.out.println("Excellent performance.");
}
}
}
Output:
Student has passed.
The first condition evaluates to true, while the second evaluates to false. Therefore, only the pass message is printed.
9. Using if Statements with Logical Operators
Logical operators allow multiple conditions to be combined into one expression.
| Operator |
Name |
Purpose |
&& |
Logical AND |
True only when both conditions are true. |
|| |
Logical OR |
True when at least one condition is true. |
! |
Logical NOT |
Reverses a Boolean result. |
9.1 Logical AND Example
Use && when every specified condition must be satisfied.
public class AdmissionCheck {
public static void main(String[] args) {
int age = 20;
int marks = 80;
if (age >= 18 && marks >= 60) {
System.out.println("Eligible for admission.");
}
}
}
Output:
Eligible for admission.
Both conditions are true, so the message is displayed.
9.2 Logical OR Example
Use || when at least one of the specified conditions must be true.
public class DiscountEligibility {
public static void main(String[] args) {
int age = 65;
boolean membership = false;
if (age >= 60 || membership) {
System.out.println("Eligible for a discount.");
}
}
}
Output:
Eligible for a discount.
The age condition is true, so the overall OR expression is true even though membership is false.
9.3 Logical NOT Example
The ! operator reverses the Boolean value of an expression.
public class LoginCheck {
public static void main(String[] args) {
boolean loggedIn = false;
if (!loggedIn) {
System.out.println("Please log in first.");
}
}
}
Output:
Please log in first.
10. Using if Statements with String Values
Strings are objects in Java. To compare their text content, use the equals() method rather than the == operator in most cases. The == operator compares object references, not necessarily the text contained in the strings.
public class StringConditionExample {
public static void main(String[] args) {
String role = "admin";
if (role.equals("admin")) {
System.out.println("Welcome, administrator.");
}
}
}
Output:
Welcome, administrator.
10.1 Case-Insensitive Comparison
If capitalization should not affect the comparison, use equalsIgnoreCase().
public class RoleCheck {
public static void main(String[] args) {
String role = "ADMIN";
if (role.equalsIgnoreCase("admin")) {
System.out.println("Administrator access selected.");
}
}
}
Output:
Administrator access selected.
10.2 Handling Null String References
If a string variable might be null, calling a method directly on it can cause a NullPointerException. A safe pattern is to place a known non-null string first in the comparison.
String username = null;
if ("admin".equals(username)) {
System.out.println("Administrator");
} else {
System.out.println("Username is not admin.");
}
Output:
Username is not admin.
11. Using if Statements with User Input
Java programs often use conditions to process values entered by users. The Scanner class can read keyboard input from the console.
import java.util.Scanner;
public class UserInputIfExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
if (age >= 18) {
System.out.println("You are an adult.");
}
scanner.close();
}
}
Sample Input:
Enter your age: 21
Output:
You are an adult.
Explanation: The program reads an integer, checks whether it is at least 18, and prints a message when the condition is true. In a larger application, validate input and handle invalid data appropriately.
12. Using if Statements for Even and Odd Numbers
The remainder operator (%) can be used to determine whether an integer is even or odd. An integer is even if its remainder when divided by 2 is zero.
public class EvenOddCheck {
public static void main(String[] args) {
int number = 14;
if (number % 2 == 0) {
System.out.println("Even number");
}
if (number % 2 != 0) {
System.out.println("Odd number");
}
}
}
Output:
Even number
For this input, the first condition is true and the second is false. Notice that both conditions are evaluated because they are separate if statements.
13. Using if Statements for Positive, Negative, and Zero Values
Three independent if statements can test whether a number is positive, negative, or zero. These conditions are mutually exclusive for an ordinary integer value.
public class NumberClassification {
public static void main(String[] args) {
int number = -7;
if (number > 0) {
System.out.println("Positive number");
}
if (number < 0) {
System.out.println("Negative number");
}
if (number == 0) {
System.out.println("Zero");
}
}
}
Output:
Negative number
This example uses independent conditions. When only one of several mutually exclusive alternatives should execute, an if-else-if structure can express the intention more clearly.
14. The Difference Between if and if-else
A simple if statement executes its block only when the condition is true. An if-else statement provides an alternative block that executes when the condition is false.
| Feature |
if |
if-else |
| Condition true |
Executes the if block. |
Executes the if block. |
| Condition false |
Skips the if block. |
Executes the else block. |
| Alternative block |
Not provided. |
Provided. |
| Typical use |
Perform an action only when required. |
Choose between two alternatives. |
Example
public class IfElseExample {
public static void main(String[] args) {
int marks = 32;
if (marks >= 40) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}
Output:
Fail
15. Nested if Statements
A nested if statement is an if statement placed inside another conditional block. Nested conditions are useful when a second decision should be evaluated only after an earlier condition has been satisfied.
Example: Login Validation
public class NestedIfExample {
public static void main(String[] args) {
boolean usernameValid = true;
boolean passwordValid = true;
if (usernameValid) {
if (passwordValid) {
System.out.println("Login successful.");
}
}
}
}
Output:
Login successful.
Explanation: The inner condition is evaluated only when usernameValid is true. Both conditions must be true for the success message to appear.
15.1 Nested if with an Inner else
public class NestedIfElseExample {
public static void main(String[] args) {
boolean accountActive = true;
boolean passwordCorrect = false;
if (accountActive) {
if (passwordCorrect) {
System.out.println("Access granted.");
} else {
System.out.println("Incorrect password.");
}
} else {
System.out.println("Account is inactive.");
}
}
}
Output:
Incorrect password.
Indentation helps show which else belongs to which if. Java associates an else with the nearest unmatched if, so braces are strongly recommended.
16. Using if Statements with Multiple Conditions
Multiple conditions can be combined to check ranges, eligibility rules, and business requirements.
Example: Checking a Valid Age Range
public class AgeRangeCheck {
public static void main(String[] args) {
int age = 25;
if (age >= 18 && age <= 60) {
System.out.println("Age is within the specified range.");
}
}
}
Output:
Age is within the specified range.
The condition is true only when the age is at least 18 and no greater than 60. The logical AND operator ensures that both comparisons must be true.
17. Using if Statements for Business Logic
Conditional statements are widely used to implement business rules in applications. The following example checks whether a purchase qualifies for a discount.
public class DiscountCalculator {
public static void main(String[] args) {
double purchaseAmount = 2500.0;
if (purchaseAmount >= 2000.0) {
double discount = purchaseAmount * 0.10;
double finalAmount = purchaseAmount - discount;
System.out.println("Discount: " + discount);
System.out.println("Final amount: " + finalAmount);
}
}
}
Output:
Discount: 250.0
Final amount: 2250.0
Explanation: Since the purchase amount is at least 2,000, the program calculates a 10% discount. If the amount is lower, the calculation block is skipped. A complete checkout system would also need to define what happens when the purchase does not qualify.
18. Using if Statements with Boolean Variables
A Boolean variable stores either true or false. It can be used directly as an if condition without a comparison.
public class BooleanIfExample {
public static void main(String[] args) {
boolean isAvailable = true;
if (isAvailable) {
System.out.println("Product is available.");
}
}
}
Output:
Product is available.
Writing if (isAvailable) is clearer than writing if (isAvailable == true). Similarly, use if (!isAvailable) to test whether the variable is false.
19. The Importance of Curly Braces
Curly braces define the block of statements controlled by an if condition. Although Java permits a single statement without braces, using braces consistently makes code easier to understand and safer to maintain.
Example Without Braces
int age = 20;
if (age >= 18)
System.out.println("Eligible");
System.out.println("Finished");
Only the first print statement is controlled by the if statement. The second print statement executes regardless of the condition.
Recommended Style with Braces
int age = 20;
if (age >= 18) {
System.out.println("Eligible");
}
System.out.println("Finished");
Braces make the intended block explicit and reduce the risk of introducing errors when adding more statements later.
20. Common Mistakes When Using if Statements
| Mistake |
Explanation |
Correct Approach |
Using = instead of == |
= assigns a value; == compares values. |
Use the correct comparison operator. |
| Missing parentheses |
The condition must be enclosed in parentheses. |
Write if (condition). |
| Missing braces for multiple statements |
Only the first statement may be controlled by the condition. |
Use braces to group related statements. |
| Using an integer as a Boolean condition |
Java does not treat numeric values as true or false. |
Use a Boolean expression such as count > 0. |
Comparing strings with == |
The operator compares references rather than text content. |
Use equals() for text comparison. |
| Using incorrect logical operators |
The condition may not match the intended rule. |
Use && when all conditions must be true and || when at least one must be true. |
| Incorrect boundary conditions |
Using > instead of >= may exclude the boundary value. |
Test values at, below, and above the boundary. |
| Unclear nested conditions |
Incorrect indentation can hide which block belongs to an if. |
Use consistent indentation and braces. |
21. Debugging if Statements
When an if statement produces an unexpected result, use a systematic debugging process.
- Check the actual values stored in the variables.
- Verify that the comparison operators match the intended requirement.
- Evaluate each part of a compound condition separately.
- Check whether a string might be
null.
- Confirm that braces group the statements correctly.
- Test boundary values such as zero, the minimum permitted value, and the maximum permitted value.
- Use temporary print statements or a debugger to inspect variable values and program flow.
Debugging Example
public class DebugIfExample {
public static void main(String[] args) {
int marks = 40;
System.out.println("Marks: " + marks);
System.out.println("Pass condition: " + (marks >= 40));
if (marks >= 40) {
System.out.println("Pass");
}
}
}
Output:
Marks: 40
Pass condition: true
Pass
Printing the condition result helps confirm whether the program's decision matches the expected rule.
22. Best Practices for Writing if Statements
- Write clear conditions that are easy to read and understand.
- Use meaningful variable names such as
isEligible, hasPermission, and isAvailable.
- Always use braces, even when the block contains only one statement.
- Use
== for primitive value comparisons when appropriate and equals() for string content comparisons.
- Keep complex Boolean expressions manageable by breaking them into clearly named variables or helper methods.
- Use parentheses when combining logical operators to make the intended grouping clear.
- Test boundary values and unexpected inputs.
- Avoid duplicating conditions when a clearer structure can express the same logic.
- Do not confuse a condition that evaluates to false with a program error; skipping the block is normal behavior.
23. Practice Exercises
Exercise 1: Check Whether a Number Is Positive
Write a Java program that prints a message only when a number is greater than zero.
int number = 10;
if (number > 0) {
System.out.println("Positive");
}
Expected Output:
Positive
Exercise 2: Check Voting Eligibility
Write an if statement that prints a message if the age is 18 or above.
int age = 19;
if (age >= 18) {
System.out.println("Eligible to vote");
}
Expected Output:
Eligible to vote
Exercise 3: Check Whether Marks Meet a Passing Score
Write a condition that prints Passed when marks are at least 40.
int marks = 65;
if (marks >= 40) {
System.out.println("Passed");
}
Expected Output:
Passed
Exercise 4: Check a Password Length
Write a condition that prints a message when a password contains at least eight characters.
String password = "java1234";
if (password.length() >= 8) {
System.out.println("Password length accepted");
}
Expected Output:
Password length accepted
This example checks only the password length; it does not provide complete password security validation.
Exercise 5: Check Whether a Number Is Between 10 and 50
int number = 25;
if (number >= 10 && number <= 50) {
System.out.println("Number is within range");
}
Expected Output:
Number is within range
24. Mini Project: Student Eligibility Checker
Create a small Java program that checks whether a student meets the eligibility criteria for a course based on age and examination marks.
Project Requirements
- Store the student's age and marks in variables.
- Check whether the student is at least 18 years old.
- Check whether the student has scored at least 50 marks.
- Use a logical AND operator to combine both conditions.
- Print an eligibility message only when both conditions are true.
Sample Implementation
public class StudentEligibilityChecker {
public static void main(String[] args) {
int age = 20;
int marks = 75;
if (age >= 18 && marks >= 50) {
System.out.println("Student is eligible for the course.");
}
System.out.println("Eligibility check completed.");
}
}
Output:
Student is eligible for the course.
Eligibility check completed.
Project Extension
- Change the age to 16 and observe the output.
- Change marks to 35 and test the condition again.
- Use Boolean variables to represent age eligibility and marks eligibility.
- Extend the program with an
if-else statement to display an alternative message when the student is not eligible.
25. Interview Questions and Answers
Q1. What is an if statement in Java?
An if statement executes a block of code only when its Boolean condition evaluates to true.
Q2. What is the syntax of an if statement?
if (condition) {
// Statements to execute when condition is true
}
Q3. What happens when an if condition is false?
The statements inside the if block are skipped, and execution continues after the block.
Q4. Can an if statement contain multiple conditions?
Yes. Conditions can be combined using logical operators such as && and ||.
Q5. What is the difference between if and if-else?
A simple if statement executes code only when its condition is true. An if-else statement also provides an alternative block for when the condition is false.
Q6. What is a nested if statement?
A nested if statement is a conditional statement placed inside another conditional block.
Q7. Can an if condition use a number directly in Java?
No. The condition must evaluate to a Boolean value. For example, if (number > 0) is valid, while if (number) is not valid when number is an integer.
Q8. What is the difference between = and ==?
The = operator assigns a value to a variable. The == operator compares primitive values or checks whether two object references refer to the same object.
Q9. How do you compare two strings inside an if statement?
Use equals() to compare string content, or equalsIgnoreCase() when capitalization should be ignored. Consider null safety when a string reference may be null.
Q10. Are curly braces mandatory for an if statement?
Braces are optional when the controlled body contains only one statement, but using them consistently is recommended for readability and to prevent errors.
Q11. What is short-circuit evaluation?
With &&, Java skips evaluating the second operand when the first is false. With ||, Java skips the second operand when the first is true.
Q12. When should you use a nested if statement?
Use nested conditions when one decision depends on the result of an earlier decision. For complex rules, consider whether combining conditions or using another control structure would be clearer.
26. Quick Revision Checklist
- An
if statement is used for conditional execution.
- The condition must evaluate to
true or false.
- The condition is enclosed in parentheses.
- The block executes only when the condition is true.
- Relational operators compare values.
&& combines conditions that must all be true.
|| combines conditions where at least one must be true.
! reverses a Boolean value.
- Nested
if statements support dependent decisions.
- Use
equals() to compare string content.
- Use braces consistently to improve readability.
- Test boundary values and review conditions carefully.
27. Conclusion
The if statement is one of the fundamental building blocks of Java programming. It allows programs to make decisions based on conditions and execute code selectively. By combining if statements with comparison operators, logical operators, variables, and user input, developers can implement useful rules for real-world applications.
Practise writing simple conditions first, then move on to compound conditions, nested statements, and practical projects. Understanding these concepts will provide a strong foundation for learning if-else, else-if ladders, switch statements, loops, and other Java control-flow structures.
Continue learning with the Core Java Training Course, register for a course demo, or visit the JustAcademy official website.