web analytics

Java if else statement

General mathematical logic based conditions are supported in java e.g.

  • Equal to: x == y (will be true of both x and y are equal other wise false)
  • Less than x < y ( we be true of x is less than y)
  • Less than or equal to: x <= y (will be true if x is less y or both have hold same value)
  • Greater than: x > y (will be true if x holds a value greater than that of y)
  • Greater than or equal to: x >= y (will be true if x holds a value greater than y or both hold same value)
  • Not equal to: x != y (will be true if x and y hold different values)

These conditions are used in java to perform decisions for different actions
Java supports if, ifelse, ifelseif and switch to control flow of execution of a program based on above conditions:

Note: if, else and switch are in lower case and upper case letters will generate error because java is a case sensitive language.

Java if statement

Java code in if statement is executed when the condition is true

Syntax for if statement

if ( condition) {
// java code placed here will be executed if condition is true
}

Example:

int x = 10;
int y = 8;
if (x > y) {
System.out.println("value in variable x is greater than that of y");
}

Java if-else statement

Java code in if statement is executed when the condtion is true. Otherwise code in else block will be executed.

Syntax for if-else statement

if ( condition) {
// java code placed here will be executed if condition is true
} else
{
//Java code placed here will be executed if condition is false.
}

Example:

int x = 10;
int y = 8;
if (x > y) {
System.out.println("value in variable x is greater than that of y");
}else
{
System.out.println("value in variable x is not greater than that of y, may be equal!");
}

Java if-else-if statement

We can test a new condition instead of execution of else block.

Syntax for if-else-if statement

if ( condition) {
// java code placed here will be executed if condition is true
} else if(condition2){
//Java code placed here will be executed if condition2 is true.
}

Example:

int x = 10;
int y = 8;
if (x > y) {
System.out.println("value in variable x is greater than that of y");
}else if(x == y)
{
System.out.println("value in variable x is equal to the value in y");
}else{
System.out.println("value in variable x is greater than the value in y");
}