Condition

If else

Java

 

If

Java 8
int status = 0;

if (status == 0) {
    System.out.println("Ready"); 
}

The code block {} will run if the condition specified is met.

Comparison Expressions and operators can be combined to form new condition expressions:

int status=0; boolean isDeviceOn=true;

if (isDeviceOn && (status == 0 || status == 1)) {
  System.out.println("Not done yet");
}

This will print Ready on Console.

 

If Else

Java 8
int status = 1;

if (status == 0) {
    System.out.println("Ready"); 
} else {
    System.out.println("Running or Done");
}

By using else, you can specify a portion of code to be run, in case if expression evaluates to false.

This will print Running or Done on Console.

 

Complex If

Java 8
int status = 2;

if (status == 0) {
    System.out.println("Ready"); 
} else if (status == 1){
    System.out.println("Running");
} else {
    System.out.println("Done"); 
}

You can have as many else if as you want.

This will print Done on Console.

 

Nested If

Java 8
int status = 2;

if (status > 0) {
    if (status == 1){
        System.out.println("Running");
    } else {
        System.out.println("Done"); 
    }
} else {
    System.out.println("Ready");  
}

You can nest if statements to control the logic of your algorithms.

This will print Done on Console.

 

Single If Statement

Java 8
int status = 1;

if (status == 0)
    System.out.println("Ready"); 
else
    System.out.println("Running or Done");

If you only have one statement in your if-else blocks, you can drop the curly braces { }.

This will print Running or Done on Console.