Java:Java If...Else and Ternary Conditional Statements
Java•Conditionals

Java If...Else and Ternary Conditional Statements

Control program flow by testing boolean expressions. In Java, conditions must be of strict boolean type.

Syntax

if (condition) { // block } else { // fallback }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
conditionbooleanStrict boolean expression; non-zero numbers are not allowed.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Java locally:

public class Main {
    public static void main(String[] args) {
        int memoryUtilizationPercent = 88;

        if (memoryUtilizationPercent >= 90) {
            System.out.println("[CRITICAL] Memory exhausted! Triggering pod restart.");
        } else if (memoryUtilizationPercent >= 75) {
            System.out.println("[WARN] High memory usage: Scaling worker nodes.");
        } else {
            System.out.println("[OK] Memory within optimal operational bounds.");
        }

        // Ternary operator
        String alertStatus = (memoryUtilizationPercent >= 80) ? "TRIGGERED" : "NOMINAL";
        System.out.println("Alert Status: " + alertStatus);
    }
}
Expected Output:
[WARN] High memory usage: Scaling worker nodes.
Alert Status: TRIGGERED

How It Works: Step-by-Step

  • Lines 5-11: Evaluates memory threshold through chained conditional branches.
  • Line 14: Ternary operator assigns alertStatus in a concise expression.

Key Concepts

  • Java requires strict boolean conditions in if statements (e.g. if (count) is invalid).
  • The first matching branch executes; subsequent elif/else blocks are skipped.
  • Braces {} are best practice to prevent dangling else ambiguities.

Common Mistake: Passing an integer to if (number) like in C or JavaScript

In Java, if (count) does not compile. You must explicitly write if (count != 0).

❌ Incorrect
int x = 5;
if (x) { /* Compile Error: incompatible types: int cannot be converted to boolean */ }
✅ Correct
int x = 5;
if (x != 0) { /* Valid */ }

Related Java Tutorials & Compiler

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler