If Else Statement
The if statement tells a program to execute a certain block of code only if a particular test evaluates to true.
Syntax
if (condition) {
/* The code reaches here only if the above
* condition evaluates to true. */
}
Example
A program to increase the value of salary by 3000 if it's value is less than 5000:
public class IfExample {
public static void main(String[] args) {
double salary = 4000;
double totalSalary = 0;
if (salary > 5000) {
totalSalary = salary + 1000;
}
if (salary < 5000) {
totalSalary = salary + 3000;
}
System.out.println("Salary is = $" + totalSalary);
}
}
Output
Salary is = $7000.0
The if-else or if-then-else Statement
The if-else statement is used to execute the second block of code when if clause evaluates to false. The else statement specifies a block of code to be executed when the if condition is false.
Syntax
if (condition) {
/* The code reaches here only if the
* above condition evaluates to true. */
} else {
/* The code reaches here only if the
* above condition evaluates to false. */
}
Example
A program to increase salary by 1000 if the salary is less than 3000 else increase it by 5000:
public class IfElseExample {
public static void main(String[] args) {
double salary = 4000;
double totalSalary = 0;
if (salary < 3000) {
totalSalary = salary + 1000;
} else {
totalSalary = salary + 5000;
}
System.out.println("Salary is = $" + totalSalary);
}
}
Output
Salary is = $9000.0
The else-if Statement
The else if statement is a decision-making statement having multiple decisions.
Syntax
if (condition) {
/* The code reaches here only if the
* above condition evaluates to true. */
} else if (condition) {
/* The code reaches here only if the
* above condition evaluates to true. */
} else if (condition) {
/* The code reaches here only if the
* above condition evaluates to true. */
} else if (condition) {
/* The code reaches here only if the
* above condition evaluates to true. */
} else {
/* The code reaches here only if none
* of the above condition evaluates to true. */
}
Example
Here is a program to show the use of else if statement:
public class OperatorsExample {
public static void main(String[] args) {
double salary = 4000;
double totalSalary = 0;
if (salary < 2000) {
totalSalary = salary + 1000;
} else if (salary < 3000) {
totalSalary = salary + 500;
} else if (salary < 5000) {
totalSalary = salary + 200;
} else {
totalSalary = salary + 100;
}
System.out.println("Salary is = $" + totalSalary);
}
}
Output
Salary is = $4200.0