if-else Statement in Java


☞If you have only two conditions to test, then use if-else.

☞If the condition evaluates to true, it executes the statements of if block.

☞If the condition evaluates to false, it executes the statements of else block.

Syntax :

if(condition) {
    Statement 1
    Statement 2
    ...........
}
else {
    Statement 1
    Statement 2
    ...........
}

Example

/*Finding person can vote or not
if age>=18, then he can vote*/
import java.util.*;

public class IfElseExample {
public static void main(String[] args) {
    
    Scanner sc = new Scanner(System.in);
    
    System.out.println("Enter your age");
    int age=sc.nextInt();
    
    if(num>=18){
        System.out.println("You can vote");
    }
    
    else{
        System.out.println("You cannot vote");
    }

}
}

Output

Enter your age
17
you cannot vote