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:
| Parameter | Type | Description |
|---|---|---|
| condition | boolean | Strict boolean expression; non-zero numbers are not allowed. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Java Switch Statement and Modern Switch Expressions (Java 14+)
Learn classic switch and modern Java 14+ arrow switch expressions with yield.
Java For Loops and Enhanced For-Each Loop with Examples
Master traditional counting for loops and enhanced for-each iteration over arrays and collections.
Java Break and Continue Loop Control Statements
Interrupt or skip loop iterations using break and continue in Java.
Java Online Compiler
Open in Compilra IDE
Run and test Java on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.