Java Conditions

Su Suriya Ravichandran Updated 14 Nov 2026
6 min read ·Lesson 16 of 306

A condition is a boolean expression that a program evaluates to decide what to do next. Every branch, loop, and filter in Java depends on one. This lesson covers how conditions are built and which Java constructs act on them; the following lessons cover if/else and switch in detail.

What Counts as a Condition

A condition must have type boolean. It can be:

true                              // a literal
isReady                           // a boolean variable
age >= 18                         // a comparison
name.isEmpty()                    // a method returning boolean
obj instanceof String             // a type test
a > 0 && b > 0                    // a combination of the above

Java does not convert other types into booleans. Numbers, strings, and object references are never "truthy" or "falsy" as they are in JavaScript or Python:

IntentNot valid JavaValid Java
Number is non-zeroif (count)if (count != 0)
Reference is not nullif (user)if (user != null)
String has contentif (text)if (text != null && !text.isEmpty())
List has itemsif (items)if (!items.isEmpty())

Writing the full comparison makes every condition say exactly what it checks.

Comparison Operators in Conditions

int a = 10, b = 20;

a == b    // false: equal to
a != b    // true:  not equal to
a < b     // true:  less than
a > b     // false: greater than
a <= 10   // true:  less than or equal to
b >= 25   // false: greater than or equal to

For objects, == tests whether two references point to the same object. Content comparison requires equals:

String input = scanner.nextLine();
if (input == "quit") { ... }         // wrong: compares references, usually false
if (input.equals("quit")) { ... }    // correct: compares characters
if ("quit".equals(input)) { ... }    // correct and null-safe

Enum constants are the exception: each constant is a single object, so status == Status.ACTIVE is correct and idiomatic.

For ordering objects that do not support < and >, use compareTo, which returns a negative number, zero, or a positive number:

if (name1.compareTo(name2) < 0) { ... }          // name1 sorts before name2
if (date1.isBefore(date2)) { ... }               // LocalDate provides readable methods
if (price.compareTo(BigDecimal.ZERO) > 0) { ... } // BigDecimal comparison

Combining Conditions

boolean inRange = score >= 0 && score <= 100;
boolean weekend = day.equals("SAT") || day.equals("SUN");
boolean notBanned = !user.isBanned();

Java has no chained comparison: 0 <= score <= 100 is a compile error, because 0 <= score produces a boolean, which cannot be compared with 100. Each comparison must be written separately and joined with &&.

Short-circuit order matters

&& stops at the first false; || stops at the first true. Place guard conditions first:

if (list != null && !list.isEmpty() && list.get(0).equals(target)) { ... }

Each check protects the one after it. Reversing the order would throw NullPointerException or IndexOutOfBoundsException before the guard ran.

Also place cheap checks before expensive ones when either order is safe:

if (isEnabled && expensiveDatabaseLookup(id)) { ... }

Precedence and parentheses

! binds tightest, then comparisons, then &&, then ||. So:

a || b && c        // means a || (b && c)
!a && b            // means (!a) && b

When a condition mixes && and ||, add parentheses even where precedence already gives the right answer. They make the grouping explicit to the reader:

if ((isAdmin || isOwner) && !isLocked) { ... }

Naming Complex Conditions

A long condition inside an if forces the reader to decode it. Assigning parts to named variables or extracting a method documents the intent:

// Hard to read
if (order.getTotal() > 500 && customer.getYears() >= 2 && !customer.hasUnpaidInvoices()) {
    applyDiscount(order);
}

// Clear
boolean largeOrder = order.getTotal() > 500;
boolean loyalCustomer = customer.getYears() >= 2;
boolean goodStanding = !customer.hasUnpaidInvoices();

if (largeOrder && loyalCustomer && goodStanding) {
    applyDiscount(order);
}

Or, when the rule is reused:

private boolean qualifiesForDiscount(Order order, Customer customer) {
    return order.getTotal() > 500
        && customer.getYears() >= 2
        && !customer.hasUnpaidInvoices();
}

Constructs That Use Conditions

Java offers several ways to act on a condition. Each fits a different shape of decision.

ConstructUse whenExample
ifRun code only when a condition holdsif (x < 0) x = 0;
if/elseChoose between two pathsPass or fail
if/else if/elseChoose among ranges or unrelated conditionsGrade bands
switchChoose by matching one value against constants or patternsMenu option, enum, day name
Ternary ?:Choose between two values in an expressionString s = n == 1 ? "item" : "items";
Loop conditionsRepeat while a condition holdswhile (!done)

A brief view of each, before their dedicated lessons:

int temp = 31;

// if / else if / else
if (temp > 35) {
    System.out.println("Heat warning");
} else if (temp > 28) {
    System.out.println("Hot");
} else {
    System.out.println("Comfortable");
}

// ternary
String label = temp > 28 ? "hot" : "mild";

// switch expression
String day = "SAT";
String type = switch (day) {
    case "SAT", "SUN" -> "weekend";
    default -> "weekday";
};

The ternary operator is an expression: it produces a value and fits anywhere a value does, such as an assignment, a method argument, or a return. It is for choosing a value, not for running statements; use if when each branch does work.

System.out.println("Found " + count + (count == 1 ? " result" : " results"));
return balance >= amount ? balance - amount : balance;

Pattern Matching in Conditions

Since Java 16, instanceof can test a type and bind a variable in one step. The variable is in scope wherever the condition is known to be true:

Object value = getValue();

if (value instanceof String s && !s.isBlank()) {
    System.out.println("Text: " + s.strip());
} else if (value instanceof Integer n && n > 0) {
    System.out.println("Positive number: " + n);
}

s can be used on the right side of && because that side runs only when the instanceof test succeeded. It cannot be used after ||, where the test may have failed.

Floating-Point Conditions

Exact equality on double values is unreliable because of binary rounding:

double total = 0.1 + 0.2;
if (total == 0.3) { ... }                    // false
if (Math.abs(total - 0.3) < 1e-9) { ... }    // true

Range comparisons (<, >=) are usually safe. For money, use BigDecimal and compareTo.

Practical Example: Shipping Rules

public class Shipping {
    static double shippingCost(double orderTotal, double weightKg,
                               boolean isPrime, String country) {
        boolean domestic = "IN".equals(country);
        boolean freeEligible = domestic && (isPrime || orderTotal >= 499);
        boolean heavy = weightKg > 10;

        if (freeEligible && !heavy) {
            return 0;
        }

        double base = domestic ? 40 : 1200;
        double weightCharge = heavy ? (weightKg - 10) * 15 : 0;
        return base + weightCharge;
    }

    public static void main(String[] args) {
        System.out.println(shippingCost(650, 2, false, "IN"));   // 0.0
        System.out.println(shippingCost(300, 2, false, "IN"));   // 40.0
        System.out.println(shippingCost(300, 14, true, "IN"));   // 100.0
        System.out.println(shippingCost(900, 3, true, "US"));    // 1200.0
    }
}

Each business rule is a named boolean. "IN".equals(country) is null-safe. The parentheses in domestic && (isPrime || orderTotal >= 499) are required: without them the expression becomes (domestic && isPrime) || orderTotal >= 499, and every international order of 499 or more would ship free. The two ternaries choose values, while the if controls an early return. In the third call the order qualifies for free shipping but is heavy, so it pays the domestic base of 40 plus 4 kg × 15 = 60.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Conditions and get answers drawn from it.

Signed-in readers only.