Conditional Statements (if/else) in Java

Master conditional statements in Java including if, if-else, if-else-if, nested conditionals, ternary operators, and boolean expressions for the OCP 21 exam.

Table of Contents

1. The if Statement

The if statement is the most basic conditional statement. It executes a block of code only if a condition is true.

1.1 Basic Syntax

Syntax:
if (condition) {
    // code to execute if condition is true
}

1.2 Examples

Example:
int age = 18;

if (age >= 18) {
    System.out.println("You are an adult");
}

// Single statement (braces optional but recommended)
if (age >= 18)
    System.out.println("You are an adult");

// Multiple conditions
int score = 85;
if (score >= 90) {
    System.out.println("Grade: A");
}
if (score >= 80 && score < 90) {
    System.out.println("Grade: B");
}
Best Practice: Always use braces {} even for single statements. This improves readability and prevents errors when adding more statements later.

2. The if-else Statement

The if-else statement provides an alternative block of code to execute when the condition is false.

2.1 Basic Syntax

Syntax:
if (condition) {
    // code to execute if condition is true
} else {
    // code to execute if condition is false
}

2.2 Examples

Example:
int age = 16;

if (age >= 18) {
    System.out.println("You are an adult");
} else {
    System.out.println("You are a minor");
}

// Checking number parity
int number = 7;
if (number % 2 == 0) {
    System.out.println("Even number");
} else {
    System.out.println("Odd number");
}

// Finding maximum of two numbers
int a = 10;
int b = 20;
int max;
if (a > b) {
    max = a;
} else {
    max = b;
}
System.out.println("Maximum: " + max);

3. The if-else-if Statement

The if-else-if statement allows checking multiple conditions sequentially.

3.1 Basic Syntax

Syntax:
if (condition1) {
    // code if condition1 is true
} else if (condition2) {
    // code if condition2 is true
} else if (condition3) {
    // code if condition3 is true
} else {
    // code if all conditions are false
}

3.2 Examples

Example:
// Grade classification
int score = 85;
String grade;

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("Grade: " + grade);

// Age category
int age = 25;
String category;

if (age < 13) {
    category = "Child";
} else if (age < 20) {
    category = "Teenager";
} else if (age < 65) {
    category = "Adult";
} else {
    category = "Senior";
}
System.out.println("Category: " + category);
Important: Conditions are evaluated from top to bottom. Once a condition is true, its block executes and the remaining conditions are not evaluated.

4. Nested Conditionals

Conditional statements can be nested inside other conditional statements to create complex decision logic.

4.1 Nested if Statements

Example:
// Checking if a number is positive and even
int number = 8;

if (number > 0) {
    if (number % 2 == 0) {
        System.out.println("Positive even number");
    } else {
        System.out.println("Positive odd number");
    }
} else {
    System.out.println("Number is not positive");
}

// Login validation
String username = "admin";
String password = "secret123";

if (username != null && !username.isEmpty()) {
    if (password != null && password.length() >= 8) {
        System.out.println("Login successful");
    } else {
        System.out.println("Password must be at least 8 characters");
    }
} else {
    System.out.println("Username cannot be empty");
}

4.2 Complex Nested Logic

Example:
// Ticket pricing based on age and day
int age = 25;
boolean isWeekend = false;
double price = 0.0;

if (age < 5) {
    price = 0.0;  // Free for children under 5
} else if (age < 18) {
    if (isWeekend) {
        price = 15.0;  // Child weekend price
    } else {
        price = 10.0;  // Child weekday price
    }
} else if (age < 65) {
    if (isWeekend) {
        price = 25.0;  // Adult weekend price
    } else {
        price = 20.0;  // Adult weekday price
    }
} else {
    price = 12.0;  // Senior discount
}

System.out.println("Ticket price: $" + price);
Tip: While nesting is useful, avoid excessive nesting (more than 3 levels) as it reduces readability. Consider refactoring complex nested conditionals.

5. Ternary Operator

The ternary operator (?:) provides a concise way to write simple if-else statements.

5.1 Syntax

Syntax:
variable = condition ? valueIfTrue : valueIfFalse;

5.2 Examples

Example:
// Finding maximum
int a = 10;
int b = 20;
int max = (a > b) ? a : b;

// Checking even/odd
int number = 7;
String result = (number % 2 == 0) ? "Even" : "Odd";

// Assigning based on condition
int age = 18;
String status = (age >= 18) ? "Adult" : "Minor";

// Nested ternary (use sparingly)
int score = 85;
String grade = (score >= 90) ? "A" : 
               (score >= 80) ? "B" : 
               (score >= 70) ? "C" : "F";

// Returning values
public int getAbsoluteValue(int x) {
    return (x >= 0) ? x : -x;
}
Best Practice: Use ternary operator for simple, readable conditions. Avoid nested ternary operators as they can be hard to read. Prefer if-else for complex logic.

6. Boolean Expressions

Conditional statements rely on boolean expressions that evaluate to true or false.

6.1 Relational Operators

Operator Description Example
== Equal to x == 5
!= Not equal to x != 5
< Less than x < 10
<= Less than or equal to x <= 10
> Greater than x > 5
>= Greater than or equal to x >= 5

6.2 Examples

Example:
int x = 10;
int y = 5;

if (x == y) {
    System.out.println("x equals y");
}

if (x != y) {
    System.out.println("x does not equal y");
}

if (x > y) {
    System.out.println("x is greater than y");
}

if (x >= 10) {
    System.out.println("x is greater than or equal to 10");
}

// Comparing strings (use equals(), not ==)
String str1 = "Hello";
String str2 = "Hello";

if (str1.equals(str2)) {
    System.out.println("Strings are equal");
}

// Comparing objects
if (str1 == str2) {
    System.out.println("Same reference");  // May be true if interned
}

7. Logical Operators in Conditionals

Logical operators allow combining multiple boolean expressions.

7.1 Logical AND (&&)

Example:
int age = 25;
boolean hasLicense = true;

if (age >= 18 && hasLicense) {
    System.out.println("Can drive");
}

// Range checking
int score = 85;
if (score >= 80 && score < 90) {
    System.out.println("Grade B");
}

// Multiple conditions
String username = "admin";
String password = "secret123";
if (username != null && !username.isEmpty() && password.length() >= 8) {
    System.out.println("Valid credentials");
}

7.2 Logical OR (||)

Example:
int dayOfWeek = 6;  // Saturday

if (dayOfWeek == 6 || dayOfWeek == 7) {
    System.out.println("Weekend");
}

// Multiple options
char grade = 'B';
if (grade == 'A' || grade == 'B' || grade == 'C') {
    System.out.println("Passing grade");
}

// Combining with AND
int age = 65;
boolean isStudent = false;
if ((age >= 65 || isStudent) && age > 0) {
    System.out.println("Eligible for discount");
}

7.3 Logical NOT (!)

Example:
boolean isLoggedIn = false;

if (!isLoggedIn) {
    System.out.println("Please log in");
}

// Negating conditions
int age = 16;
if (!(age >= 18)) {
    System.out.println("Not an adult");
}

// Checking for null or empty
String name = "";
if (name == null || name.isEmpty()) {
    System.out.println("Name is required");
}

// Using De Morgan's laws
int x = 5;
int y = 10;
// !(x > 5 && y < 10) is equivalent to (x <= 5 || y >= 10)
if (!(x > 5 && y < 10)) {
    System.out.println("Condition is true");
}
Short-Circuit Evaluation: && and || use short-circuit evaluation. If the left operand determines the result, the right operand is not evaluated.

8. Common Pitfalls

8.1 Assignment vs Comparison

Common Mistake:
int x = 5;

// WRONG: Assignment instead of comparison
if (x = 10) {  // Compilation error: int cannot be converted to boolean
    System.out.println("x is 10");
}

// CORRECT: Use == for comparison
if (x == 10) {
    System.out.println("x is 10");
}

8.2 String Comparison

Common Mistake:
String str1 = "Hello";
String str2 = new String("Hello");

// WRONG: Comparing references, not content
if (str1 == str2) {
    System.out.println("Equal");  // May not execute
}

// CORRECT: Use equals() for content comparison
if (str1.equals(str2)) {
    System.out.println("Equal");  // Will execute
}

// Also check for null to avoid NullPointerException
if (str1 != null && str1.equals(str2)) {
    System.out.println("Equal");
}

// Or use Objects.equals() (Java 7+)
if (Objects.equals(str1, str2)) {
    System.out.println("Equal");
}

8.3 Floating-Point Comparison

Common Mistake:
double d1 = 0.1 + 0.2;
double d2 = 0.3;

// WRONG: Direct comparison may fail due to floating-point precision
if (d1 == d2) {
    System.out.println("Equal");  // May not execute
}

// CORRECT: Compare with tolerance
double epsilon = 0.0001;
if (Math.abs(d1 - d2) < epsilon) {
    System.out.println("Equal");  // Will execute
}

9. Exam Key Points

Critical Concepts for OCP 21 Exam:

  • if Statement: Executes code block only if condition is true
  • if-else: Provides alternative code block when condition is false
  • if-else-if: Allows checking multiple conditions sequentially
  • Braces: Always use braces even for single statements (best practice)
  • Ternary Operator: condition ? valueIfTrue : valueIfFalse
  • Relational Operators: ==, !=, <, <=, >, >=
  • Logical Operators: && (AND), || (OR), ! (NOT)
  • Short-Circuit Evaluation: && and || may not evaluate right operand
  • String Comparison: Use equals(), not == for content
  • Null Safety: Check for null before calling methods on objects
  • Assignment vs Comparison: Use == for comparison, not =
  • Floating-Point Comparison: Use tolerance for floating-point comparisons
  • Nested Conditionals: Can nest if statements for complex logic
  • Condition Evaluation: Conditions evaluated top to bottom, stops at first true
  • Boolean Expressions: Must evaluate to true or false
  • De Morgan's Laws: !(A && B) = !A || !B, !(A || B) = !A && !B

Post a Comment

0 Comments