Java if-else Statement (control statement) is not different from other programming languages. The Java if-else statement is used to test the condition. It checks boolean conditions: true or false. There are various types of if statements in Java.
- if statement
- if-else statement
- if-else-if ladder Statement
- nested if statement
If statement:
Java’s if statement examines the condition. It performs the if block if the condition is true or false.
Syntax:
if(condition){
written code to be executed
}
Example of Java If statement:
public class IfExample {
public static void main(String[] args) {
//defining an 'age' as a variable
int age=30;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
Output of the following code:
Java If-Else statement:
Like other programming languages, Java if-else Statement is also working similarly to others. The second form of IF
statement adds the keyword ELSE
, followed by an alternative sequence of statements. If the condition is not satisfied with the IF clause, then the value will go in else block. You can also see the flow chart to know how Java if-else Statement is working.
Syntax:
if(condition){
//written code to be executed if condition is true
}else{
//written code to be executedif condition is false
}
Example:
public class IfExample {
public static void main(String[] args) {
int age=15;
if(age>18){
System.out.print("Age is greater than 18");
}
else{
System.out.print("Age is less than 18");
}
}
}
Output:
If-else-if Statement
The if-else-if statement performs one condition from multiple statements. For example:
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Output: C grade
Nested if statement
Nested if-else statements means that we can use one if or else if statement inside another if or else if statement.
For example:
public class Example{
public static void main(String args[]) {
int x = 30;
int y = 10;
if( x == 30 ) {
if( y == 10 ) {
System.out.print("X = 30 and Y = 10");
}
}
}
}
1. What is Ternary Operator?
Ans: Ternary operator (? 🙂 can be used instead of perform the task of if…else statement. For example:
public class IfElseTernary {
public static void main(String[] args) {
int number=15;
// ternary operator use
String output=(number%2==0)?”even number”:”odd number”;
System.out.println(output);
}
}
Must Read: