Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

If

Java Conditions and If Statements

Java incorporates standard mathematical logical conditions, including:

  • 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)

You can utilize these conditions to execute various actions based on different decisions. Java provides the following conditional statements:

  • ‘if’: To specify a block of code for execution if a specified condition is true.
  • ‘else’: To specify a block of code for execution if the same condition is false.
  • ‘else if’: To specify a new condition for testing if the first condition is false.
  • ‘switch’: To specify multiple alternative code blocks for execution.

The if Statement

Use an if statement to define a block of Java code that will be executed if a specified condition is true.

Syntax

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

 

Keep in mind that “if” must be written in lowercase letters. Using uppercase letters (If or IF) will result in an error.

In the given example, we evaluate two values to determine whether 20 exceeds 18.
If this condition proves true, display a specified text.

Example

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

Variables can also undergo testing:

Example

int x = 20;
int y = 18;
if (x > y) {
System.out.println("x is greater than y");
}

Example explained

In the example above, we use two variables, x and y, to check if x is greater than y using the > operator. Since x is 20 and y is 18, and we know that 20 is greater than 18, we print "x is greater than y" to the screen.