← Java tutorial

Java

Conditionals

if, else if, and else work as in most C-family languages, condition in parentheses, block in curly braces.

Example: a time-of-day greeting

public class Main {
    public static void main(String[] args) {
        int hour = 14;
        String greeting;

        if (hour < 12) {
            greeting = "Good morning";
        } else if (hour < 18) {
            greeting = "Good afternoon";
        } else {
            greeting = "Good evening";
        }

        System.out.println(greeting);
    }
}
Good afternoon

Notice greeting is declared without a value first, then assigned inside whichever branch actually runs, Java requires it be assigned exactly once along every possible path before it's used, or the compiler refuses to build the program, another example of Java catching a potential mistake before the code ever runs.

Example
public class Main {
    public static void main(String[] args) {
        int hour = 14;
        String greeting;

        if (hour < 12) {
            greeting = "Good morning";
        } else if (hour < 18) {
            greeting = "Good afternoon";
        } else {
            greeting = "Good evening";
        }

        System.out.println(greeting);
    }
}
Output
Good afternoon
Ready to go further?

These free tutorials are a preview, our Backend Development cohort covers it in depth, with a real project and a cohort alongside you. Active

Enroll in Backend Development
Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account