HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to JavaVariablesData TypesOperatorsStringsArraysLists (ArrayList)Conditions (if / switch)Loops (for / while)MethodsClasses (OOP)
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array & List
🔁 Condition & Loop
🧩 Method & Class
Java›Conditions (if / switch)

Conditions (if / switch)

if-else, else if, switch, and using .equals for string equality.

Simple enough for a 5-year-old to understand

if / else

Example code
1
public class Main {
2
public static void main(String[] args) {
3
int score = 75;
4
if (score >= 50) {
5
System.out.println("Passed");
6
} else {
7
System.out.println("Failed");
8
}
9
}
10
}
💡 Hint: Number equality uses ==, string equality uses .equals(). "a" == "a" is unreliable.

About this topic

Conditions give the program the ability to make decisions. In Java, the scope of a condition is determined by curly braces; indentation is purely for readability. In single-line blocks, parentheses are optional, but writing them is a strong habit — it prevents silent bugs when you add lines later.

In Java, the conditional expression MUST be a boolean. In C and JavaScript, numbers or objects can be written directly into a condition; Java does not accept this and throws a compilation error. This strictness makes classic mistakes like accidental assignment impossible right from the start.

What you will learn

  • the if, else if, and else structure
  • the switch statement and the role of break
  • modern switch statement syntax
  • making choices in a single line using the conditional operator
  • why the condition has to be a boolean

When to use?

You use conditions in input validation, permission checks, and applying business rules. If you are comparing a single value against many constants, switch is more readable.

Long if-else chains are often a sign of a design problem; the same logic can be set up much cleaner using a mapping structure or polymorphism.

Common mistakes

Wrong

int count = 5;
if (count) {
    System.out.println("var");
}

Java expects a boolean in the condition; it does not accept numbers and gives "error: incompatible types: int cannot be converted to boolean". This strictness actually provides protection: it also prevents you from making accidental assignments.

Correct

int count = 5;
if (count > 0) {
    System.out.println("var");
}

Wrong

switch (role) {
    case "admin":
        System.out.println("administrator");
    case "user":
        System.out.println("user");
}

When break is not written, the switch FALLS THROUGH to the next case; when the role is admin, both lines are printed. This is called fall-through and it is very frequently encountered even when unwanted.

Correct

switch (role) {
    case "admin":
        System.out.println("administrator");
        break;
    case "user":
        System.out.println("user");
        break;
}

Wrong

if (score > 50)
    System.out.println("passed");
    System.out.println("congratulations");

Because there are no curly braces, only the FIRST line belongs to the condition; the second line runs in every case. Indentation is misleading, Java does not care about indentation. You won't get an error message, the code will behave incorrectly silently.

Correct

if (score > 50) {
    System.out.println("passed");
    System.out.println("congratulations");
}

Frequently asked questions

which types can be used in a switch?

int and smaller integer types, char, String, and enum. String has been supported since Java 7. Floating-point types and boolean cannot be used. In modern Java versions, switch can also be written as an expression and return a value — this also eliminates the risk of forgetting to write break.

Should I write curly braces even on a single line?

Yes, writing them is a strong recommendation. Without braces, only the first line belongs to the condition; when a second line is added to that block months later, the code breaks silently. This is a classic class of security bugs experienced in real projects.

How should I perform String comparisons in a condition?

With equals, not with double equals. Also, writing the constant value on the left is a good habit for null safety; this way, even if the variable you are comparing is null, you won't get a NullPointerException.

Summary

In Java, the conditional expression must be a boolean, and the scope is determined by curly braces — indentation is not binding. Writing braces even on a single line and not omitting break in a switch are two essential protective habits.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code