Study guide

2.1 Conditional Logic: if-else and Ternary Operators

Oracle Java SE 21 Developer 1Z0-830

Track your progress as you read

Finished sections get a check mark.

1 Chapter 1: Java Basics, Primitive Types, and Operators

1.1 Program Structure, Primitives, Literals, Scopes, and var 1.2 Operators, Precedence, and Type Casting 1.3 Strings, Text Blocks, and StringBuilder 1.4 Date and Time APIs (java.time)

2 Chapter 2: Controlling Program Flow & Pattern Matching

2.1 Conditional Logic: if-else and Ternary Operators 2.2 Switch Statements and Switch Expressions 2.3 Pattern Matching for switch and instanceof 2.4 Loops and Branching Statements

3 Chapter 3: Object-Oriented Design & Class Architecture

3.1 Class Declarations, Constructors, and Object Lifecycle 3.2 Encapsulation and Access Modifiers 3.3 Inheritance, Method Overriding, and Polymorphism 3.4 Abstract Classes and Interfaces 3.5 Nested, Inner, Local, and Anonymous Classes 3.6 Method Overloading, Overload Resolution, and Varargs

4 Chapter 4: Modern Java Data Modeling: Records, Enums, and Sealed Types

4.1 Java Records, Canonical/Compact Constructors, and Component Accessors 4.2 Java Enums: Fields, Methods, and Abstract Constant-Specific Behavior 4.3 Sealed Classes and Interfaces: permits, final, non-sealed, and Hierarchy Architecture 4.4 Advanced Record Patterns (JEP 440), Nested Deconstruction, and Sealed Hierarchy Exhaustiveness

5 Chapter 5: Exception Handling and Annotations

5.1 Exception Hierarchy: Checked vs. Unchecked Exceptions 5.2 Exception Handling: try, catch, finally, and Multi-Catch 5.3 Resource Management: try-with-resources and AutoCloseable 5.4 Custom Exceptions and Best Practices 5.5 Java Annotations: Built-in, Meta-Annotations, and Custom Types

6 Chapter 6: Generics and the Collections Framework

6.1 Generics Fundamentals and Generic Methods 6.2 Wildcards, Type Bounds, and Type Erasure 6.3 Core Collections: Lists, Sets, Queues, and Maps 6.4 Sequenced Collections in Java 21 6.5 Sorting, Comparable, and Comparator 6.6 Arrays: Creation, Multidimensional Forms, and the Arrays Utility Class

7 Chapter 7: Functional Programming & Lambda Expressions

7.1 Built-in Functional Interfaces in java.util.function 7.2 Lambda Expressions, Variable Scopes, and Effectively Final 7.3 Method References: Four Varieties and Edge Cases 7.4 Working with java.util.Optional

8 Chapter 8: The Stream API and Data Pipelines

8.1 Stream Creation and Intermediate Operations 8.2 Terminal Operations and Reductions 8.3 Advanced Collectors, Grouping, Partitioning, and Teeing 8.4 Primitive Streams and Parallel Stream Processing

9 Chapter 9: Concurrency, Multithreading, and Virtual Threads

9.1 Thread Fundamentals, Creation, and Lifecycle 9.2 Thread Safety, Synchronization, and the Java Memory Model 9.3 Concurrency Utilities: ExecutorService, Callable, and Future 9.4 Concurrent Collections, Atomics, and Explicit Locks 9.5 Virtual Threads in Java 21 (Carrier Threads, Pinning, and Best Practices)

10 Chapter 10: The Java Platform Module System (JPMS)

10.1 Module Architecture and module-info.java Declarations 10.2 Module Directives: requires, exports, opens, provides, and uses 10.3 Modular Compilation, Packaging, and CLI Execution 10.4 Module Types, Migration Strategies, ServiceLoader SPI, and JLink

11 Chapter 11: Java I/O, NIO.2, and Object Serialization

11.1 Classic Java I/O Streams and Readers/Writers 11.2 Java NIO.2 File API: Path, Paths, and File System Operations 11.3 Advanced NIO.2 Stream Operations and Directory Traversal 11.4 Java Object Serialization and Record Serialization

12 Chapter 12: Implementing Localization and Internationalization

12.1 Locales and Resource Bundles 12.2 Formatting and Parsing Numbers, Currencies, Dates, Times, and Messages

2.1 Conditional Logic: if-else and Ternary Operators

Key Takeaways Explain This Topic AI

Java if conditions require boolean expressions; assignments like if (x = 5) fail to compile for non-boolean types, while boolean assignments like if (b = true) assign and evaluate to true.

The dangling else problem is resolved by binding each else clause to the closest preceding unmatched if statement within the same block scope.

Short-circuit operators (&&, ||) skip evaluation of the right operand once the outcome is determined, unlike eager bitwise/logical operators (&, |, ^) which always evaluate both operands.

Ternary expressions (condition ? expr1 : expr2) apply binary numeric promotion across branches and trigger runtime NullPointerExceptions if unboxing occurs on a null reference.

Last updated: September 2026

Decision Making with if-else and Ternary Operators

Conditional decision making forms the backbone of control flow in Java. For the Oracle Certified Professional: Java SE 21 Developer (1Z0-830) exam, questions test not merely basic branching, but subtle language grammar rules, short-circuit evaluation side effects, the dangling else problem, variable scoping quirks, and type resolution mechanics in ternary expressions.

  • 1. The if and if-else Statement Grammar
  • Boolean Condition Strictness

In Java, the condition inside if (...) must strictly evaluate to a boolean primitive or a java.lang.Boolean object (which undergoes automatic unboxing). Unlike C, C++, or JavaScript, Java does not treat integers, non-null object references, or non-empty strings as truthy values.

if (1) -> Compilation Error : incompatible types: int cannot be converted to boolean .

if (null) -> Compilation Error : incompatible types: <nulltype> cannot be converted to boolean .

Boolean b = null; if (b) -> Compiles cleanly , but throws a NullPointerException at runtime due to the automatic unboxing call b.booleanValue() .

The Assignment vs. Equality Trap

A classic certification trap involves confusing the assignment operator ( = ) with the equality operator ( == ) inside an if condition: boolean isAvailable = false;

if (isAvailable = true) { // Assigns true to isAvailable, and evaluates to true!

System.out.println("Available"); // Executes!

}

  • int score = 0;
  • // if (score = 100) { } // COMPILATION ERROR: score = 100 evaluates to int (100), not boolean

When evaluating a boolean variable, if (isAvailable = true) reassigns isAvailable and evaluates the expression result to true , causing the branch to execute. With non-boolean primitive types, the assignment expression evaluates to the assigned value (such as an int ), which the compiler rejects immediately because int cannot be converted to boolean .

Solitary Statements and Variable Scope

In Java, a local variable declaration cannot be a solitary statement directly following an if , else , while , or for statement without enclosing curly braces {} : int score = 95;

  • if (score > 90)
  • int grade = 1; // COMPILATION ERROR: variable declaration not allowed here

// Legal syntax requires explicit block braces:

  • if (score > 90) {
  • int grade = 1; // Legal: scoped to this block
  • }

The Java Language Specification (JLS §14.9) prohibits declarations directly inside unblocked branches because a local variable declared without a block would immediately go out of scope on the very next line, rendering it completely inaccessible and logically useless.

2. The Dangling else Problem and Resolution

When if-else statements are nested without curly braces, Java resolves ambiguities using the dangling else rule : an else clause always pairs with the nearest preceding unmatched if statement within the same block level, regardless of how the code is indented.

  • Consider the following snippet: int x = 5;
  • int y = 15;
  • if (x > 10)
  • if (y > 10)
  • System.out.println("A");
  • else
  • System.out.println("B");

Although the visual indentation suggests that else belongs to if (x > 10) , the compiler associates the else with the nearest inner if (y > 10) .

Step-by-Step Execution Trace:

x > 10 evaluates to 5 > 10 which is false .

The outer if condition fails, skipping the entire sub-statement (which consists of if (y > 10) System.out.println("A"); else System.out.println("B"); ).

Nothing is printed to the console!

  • To make else bind to the outer if , explicit block braces {} are mandatory: if (x > 10) {
  • if (y > 10) {
  • System.out.println("A");
  • }
  • } else {
  • System.out.println("B"); // Prints "B" because x <= 10
  • }
  • 3. Short-Circuit vs. Eager Evaluation and Side Effects

Java provides both short-circuit logical operators ( && , || ) and eager bitwise/logical operators ( & , | , ^ ):

Operator Type Evaluation Behavior Side Effect Implication

&& Conditional AND Evaluates right operand only if left operand is true . Skips right-hand side effects if left is false .

|| Conditional OR Evaluates right operand only if left operand is false . Skips right-hand side effects if left is true .

& Logical AND (Eager) Always evaluates both operands. Right-hand side effects always execute .

| Logical OR (Eager) Always evaluates both operands. Right-hand side effects always execute .

^ Logical XOR (Eager) Always evaluates both operands. true if exactly one operand is true .

Side Effect Consequences in Exam Questions

When expressions containing side effects (such as post-increments x++ , pre-increments ++x , or method calls) appear in the right-hand operand, short-circuiting will suppress them: int a = 10;

int b = 20;

  • if (a > 15 && ++b > 20) {
  • System.out.println("Branch executed");
  • }

System.out.println("b = " + b); // Prints "b = 20" because ++b was never evaluated!

  • if (a > 15 & ++b > 20) {
  • System.out.println("Branch executed");
  • }

System.out.println("b = " + b); // Prints "b = 21" because eager & evaluated ++b!

4. The Ternary Conditional Operator ( ? : )

The ternary operator is Java's only three-operand operator. It provides a compact expression-oriented alternative to simple if-else blocks: booleanExpression ? expression1 : expression2

Expression vs. Statement Rules

The ternary construct is an expression , not a statement. It evaluates to a single value that must be assigned to a variable, passed as a method argument, or returned from a method. It cannot stand alone as an independent executable statement: int x = 10;

// x > 5 ? System.out.println("Big") : System.out.println("Small"); // COMPILATION ERROR! Not a statement

// Valid usage:

  • System.out.println(x > 5 ? "Big" : "Small");
  • Precedence and Right-Associativity

The ternary operator has low precedence (just above assignment operators) and is right-associative . This means nested ternary expressions evaluate from right to left: int score = 85;

String result = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";

// Grouped by compiler as:

  • // score >= 90 ? "A" : (score >= 80 ? "B" : (score >= 70 ? "C" : "F"))
  • Type Promotion and Result Type Resolution (JLS §15.25)

The compiler determines the result type of a ternary expression at compile time based on the types of the second and third operands:

Identical Types : If both operands are of type T , the result is of type T .

Numeric Widening Promotion : If one operand is int and the other is double , the entire expression type is double . The int value is widened to double : int count = 5;

double price = true ? count : 10.5; // Result is 5.0 (double)

Constant Narrowing for Integral Types : If one operand is byte , short , or char and the other is a constant int expression whose value fits into that type, the result type narrows to the smaller type: byte b1 = true ? 120 : (byte) 200; // Legal: 120 fits in byte range (-128 to 127)

Boxing and Unboxing Pitfalls : When mixing a primitive type with a wrapper object, the wrapper object is unboxed. If the wrapper reference is null , an unexpected NullPointerException occurs at runtime—even if the branch returning null was not the active branch if unboxing is triggered: Integer boxedNull = null;

Double result = true ? 1.0 : boxedNull;

// Second operand is Integer, first is primitive double (1.0).

// Numeric promotion converts both to primitive double, triggering boxedNull.intValue() unboxing!

boolean flag = false;

double val = flag ? 10.0 : boxedNull; // Throws NullPointerException at runtime!

5. Summary of Key Exam Traps for if-else and Ternary

Scenario Code Example Outcome / Exam Trap

Boolean Assignment if (flag = false) Assigns false , evaluates to false , else branch executes.

Semicolon Stunner if (x > 5); { doWork(); } Semicolon terminates if-statement with an empty body; { doWork(); } always runs.

Solitary Declaration if (x > 0) int y = 10; Compilation error: variable declaration cannot be solitary sub-statement.

Dangling Else Unbracketed nested if followed by else else binds to the closest inner if , not the outer if .

Ternary Standalone flag ? foo() : bar(); Compilation error if method returns void or is used as standalone statement.

Ternary Null Unboxing int val = flag ? 1 : (Integer) null; Throws NullPointerException when flag is false during unboxing.

Dead Code in if if (false) { x = 1; } Legal in Java (unlike while(false) which causes an unreachable code compile error).

Loading diagram... Conditional Evaluation & Dangling Else Resolution