If Statement

     

    If Statement


    I. Java if statement



    Syntax
    if(condition){  
    //code to be executed  
    }
    Example

    public class IfStatementExample {
        public static void main(String[] args) {
            int x, y;
            x = 10;
            y = 20;
            if (x < y) {
                System.out.println("x is less than y");
            }
            x = x * 2;
            if (x == y) {
                System.out.println("x now equal to y");
            }
            x = x * 2;
            if (x > y) {
                System.out.println("x now greater than y");
            }
            // this won't display anything
            if (x == y)
                System.out.println("you won't see this");
        }
    }
    Output:
    x is less than y
    x now equal to y
    x now greater than y

    II. Java if-else statement

    Syntax
    if(condition){  
         statement 1; //code if condition is true  
    }else{  
         statement 2; //code if condition is false  
    }  
    Example
    public class IfElseDemo {
        public static void main(String[] args) {
    
            int testscore = 76;
            char grade;
    
            if (testscore >= 90) {
                grade = 'A';
            } else if (testscore >= 80) {
                grade = 'B';
            } else if (testscore >= 70) {
                grade = 'C';
            } else if (testscore >= 60) {
                grade = 'D';
            } else {
                grade = 'F';
            }
            System.out.println("Grade = " + grade);
        }
    }
    Output:
    Grade = C

    III. Java if-else-if statement


    Syntax
    Syntax:
    
    if(condition1){  
    //code to be executed if condition1 is true  
    }else if(condition2){  
    //code to be executed if condition2 is true  
    }  
    else if(condition3){  
    //code to be executed if condition3 is true  
    }  
    ...  
    else{  
    //code to be executed if all the conditions are false  
    }  
    Example
    public class IfElseIfStatementExample {
        public static void main(String args[]) {
            int month = 4; // April
            String season;
            if (month == 12 || month == 1 || month == 2)
                season = "Winter";
            else if (month == 3 || month == 4 || month == 5)
                season = "Spring";
            else if (month == 6 || month == 7 || month == 8)
                season = "Summer";
            else if (month == 9 || month == 10 || month == 11)
                season = "Autumn";
            else
                season = "Bogus Month";
            System.out.println("April is in the " + season + ".");
        }
    }
    Output:
    April is in the Spring.