Java Conditional Statement

if-else statement

There are many situations where simply skipping code based on a false test expression isn't enough.We need a way for the program to react differently based on whether the Test Expression is true or false. If it's false, we don't want to skip code, but rather execute a separate block entirely.


This is where conditional statements like if-else come in.


In java if-else statements, if the condition evaluates to true the code within the “if” block is executed otherwise the code within the “else” block is executed.


Note: “Else” block is optional in code.There can only be one “else” block per “if” statement.

Syntax:

if (Test Expression):
{ // if body }
else:
{//else body}

#java program to demonstrate if statement

Program-1

import java.util.Scanner;
    public class ApnaStudy{
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter a number: ");
    int num = scanner.nextInt();

    if (num % 2 == 0) {
    System.out.println(num + " is even.");
    } else {
    System.out.println(num + " is odd.");
    }
    scanner.close();
   }
}


/*OUTPUT*/

Enter a number: 33
33 is odd.


Program-2: Program to check if a person is eligible to vote based on age

import java.util.Scanner;
    public class ApnaStudy{
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter your age: ");
    int age = scanner.nextInt();

    if (age >= 18) {
    System.out.println("You are eligible to vote.");
    } else {
    System.out.println("You are not eligible to vote yet.");
    }
    scanner.close();
   }
}


/*OUTPUT*/

Enter your age: 34
You are eligible to vote.

Previous Next