Java If … else

In Java, you can use logical conditions from mathematics to perform different actions based on different decisions. Here are some of the conditions you can use:

  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Equal to: a == b
  • Not equal to: a != b




Conditional Statements in Java

Java provides the following conditional statements to control the flow of your programs:

  • if statement: Executes a block of code if a specified condition is true.
  • else statement: Executes a block of code if the same condition is false.
  • else if statement: Specifies a new condition to test if the first condition is false.
  • switch statement: Executes one of many blocks of code based on the value of an expression.




The If Statement

Use the if statement to specify a block of Java code to be executed if a condition is true.

Syntax

if (condition) {
  // block of code to be executed if the condition is true
}

Note that if must be written in lowercase letters. Using uppercase letters (e.g., If or IF) will generate an error.




Example: Basic If Statement

In the example below, we test two values to determine if 20 is greater than 18. If the condition is true, it prints some text:

// Example
if (20 > 18) {
  System.out.println("20 is greater than 18");
}




Example: Testing Variables

In the example below, we use two variables, carSpeed and speedLimit, to test whether carSpeed is greater than speedLimit (using the > operator). Since carSpeed is 120 and speedLimit is 100, the condition is true, and we print to the screen that “The car is speeding.”:

// Example
int carSpeed = 120;
int speedLimit = 100;
if (carSpeed > speedLimit) {
  System.out.println("The car is speeding");
}

Scroll to Top