FreeCode

Donate HTML/CSS JavaFX Java Home
Array Data Structures Array List Data Structures Linked List Data Structures Stack Data Structures Queue Data Structures While Loops Do-While Loops For Loops For-each Loops If, Else, and Multi-Way If Statements Switch Statements Try-Catch Blocks Comment Types and Javadoc Java Classes Java Methods

If, Else, and Multi-Way If Statements

Code Description:

If statements allow a section of code to be executed based on whether a certain condition is met. The If statement will always start off with an "if" with the conditions in parenthesis. You can also add on an "else" statement which will execute if the conditions are not met. Lastly, you can have an "else if" in between the "if" and the "else" in order to check a different set of conditions if the first set fails. You can have as many "else if"s as you would like and they will all execute sequentially until one set of conditions is passed.

Basic If Statement Syntax:

boolean isTrue = true;

if (isTrue) {
    // Execute code if condition passes
}

Two-Way If-Else Statement Syntax:

boolean isTrue = true;

if (isTrue) {
    // Execute code if condition passes
} else {
    // Execute code if condition fails
}

Multi-Way If Statement Syntax:

boolean isTrue = true;
boolean otherIsTrue = true;

if (isTrue) {
    // Execute code if condition passes
} else if (otherIsTrue) {
    // Execute code if first condition fails but second condition passes
} else {
    // Execute if both conditions fail
}

Runnable If Statement Example Code:

public class Demo {

    public static void main(String[] args) {

	if (1 + 1 == 1) {
	    // Skipped
	    System.out.println("1 + 1 = 1");
	} else if (1 + 1 == 2) {
	    // Printed
	    System.out.println("1 + 1 = 2");
	} else if (1 + 1 == 3) {
	    // Condition never evaluated
	    System.out.println("1 + 1 = 3");
	} else {
	    // Unused as a condition was satisfied
	    System.out.println("Nothing was correct");
	}
		
    }

}

How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.

Output:

If Statement Output Image

Important Notes:

  • If a single statement is used in the body of an if statement, the curly braces can be omitted. While this simplifies the code, the code is less prone to errors and looks more consistent when they are used anyway.
  • If statements can be nested, in which an if statement is inside of another if statement.

Related Links:

Switch Statements