If-else Statement
Java if-else Statement
The Java if statement is used to test the condition. It checks boolean condition: true or
false. There are various types of if statement in Java.
- if statement
- if-else statement
- if-else-if ladder
- nested if statement
if statement :
Let's see the example of if statement :
- //Java Program to demonstate the use of if statement.
- public class IfExample {
- public static void main(String[] args) {
- //defining an 'age' variable
- int age=20;
- //checking the age
- if(age>18){
- System.out.print("Age is greater than 18");
- }
- }
- }
Output:
Age is greater than 18
if-else statement :
Let's see the example of if-else statement :
- //It is a program of odd and even number.
- public class IfElseExample {
- public static void main(String[] args) {
- //defining a variable
- int number=13;
- //Check if the number is divisible by 2 or not
- if(number%2==0){
- System.out.println("even number");
- }else{
- System.out.println("odd number");
- }
- }
- }
Output:
odd number
if-else-if ladder statement :
The if-else-if ladder statement executes one condition from multiple statements.
Let's see the example of if-else-if ladder statement :
Output:
C grade
Nested if statement :
The nested if statement represents the if block within another if block. Here, the inner if block condition executes only when outer if block condition is true.
Let's see the example of if-else-if ladder statement :
- public class JavaNestedIfExample {
- public static void main(String[] args) {
- //Creating two variables for age and weight
- int age=20;
- int weight=80;
- //applying condition on age and weight
- if(age>=18){
- if(weight>50){
- System.out.println("You are eligible to donate blood");
- }
- }
- }
- }
Output:
You are eligible to donate blood
Post a Comment