DEV Community

Rittwick Bhabak
Rittwick Bhabak

Posted on

5. If-then block in JAVA

Example:

        boolean isAlien = false;
        if(isAlien == false)
            System.out.println("It is not an alien!");
Enter fullscreen mode Exit fullscreen mode

Example 2:

            if(isAlien == false){
            System.out.println("It is not an alien!");
            System.out.println("and I'm scared of aliens");
        }
Enter fullscreen mode Exit fullscreen mode

Example 3:

        int a = 60;
        int b = 70;
        if(a < b && a < 100){
            System.out.println("I am happy");
        }
        if(a>50 || b<30) {
            System.out.println("Logical OR operator");
        }
Enter fullscreen mode Exit fullscreen mode

Assignment vs Equal to Operator

        boolean isCar = false;
        if( isCar = true ) {
            System.out.println("This is not supposed to happen");
        }
Enter fullscreen mode Exit fullscreen mode

if( isCar = true ) in this line, isCar = true returns true, similarly isValue=50 returns 50
So, the following code is not a valid code but the above code is valid as if statement accepts true or false

        int newValue = 50;
        if(newValue = 50) {
            System.out.println("This is true");
        }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)