Java: If / Else Statements

What are If Statements ?

An If statement is a way in Java where a piece of code gets executed if the conditions are true. Below is an example.

If ( 33 > 4) {

System.out.println ( “This statement is true!” );

}

This statement is true gets printed because 33 > 4 is true.

 

If the statement in the parenthesis is false, the code will not get executed, but the code in the Else statement will. Here is an example.

If (2 + 3 = 6) {

System.out.println (” This statement is true”);

}

Else {

System.out.println (“The statement was false”);

}

The statement was false will be printed because 2 + 3 = 6 is not true.

Else If

You learned about if and else statements, but there can be many if statements. Look at the example below.

If (3 > 5) {

System.out.println ( “Your not so great at math.”);

}

Else If (3 > 4) {

System.out.println(“Still not so great at math.”)

}

Else If (3 == 3) {

System.out.println(“Getting closer. . .”);

}

else {

System.out.println (“None of the math statements are true.”);

}

If the if statement isn’t true, it follows the else If statements. If the else if statement isn’t true, it follows the next one. If ┬ánone of the statements are true, it follows the else statement.

Getting closer. . . will get printed because the statement 3 == 3 is true.

Leave a comment