Java – If Else If

If else If: The if-else-if ladder statement executes only block among multiple we defined based on valid condition

Check the Number is Positive or Negative or Zero

import java.util.Scanner;
class Code{
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		System.out.println("Enter n value : ");
		int n = scan.nextInt();
		if(n>0)
			System.out.println("Positive num");
		else if(n<0)
			System.out.println("Negative num");
		else
			System.out.println("Zero");
	}
}

Check the Character is Alphabet or Digit or Symbol

import java.util.Scanner;
class Code{
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		System.out.println("Enter character : ");
		char ch = scan.nextLine().charAt(0);
		if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
			System.out.println("Alphabet");
		else if(ch>='0' && ch<='9')
			System.out.println("Digit");
		else
			System.out.println("Special Symbol");
	}
}

Program to check the input year is Leap or Not:

Leap Year rules:

  • 400 multiples are leap years : 400, 800, 1200, 1600….
  • 4 multiples are leap years: 4, 8, 12, … 92, 96…
  • 100 multiples are not leap years: 100, 200, 300, 500, 600…
import java.util.Scanner;
class Code{
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		System.out.println("Enter year : ");
		int n = scan.nextInt();
		if((n%400==0))
			System.out.println("Leap year");
		else if(n%4==0 && n%100!=0)
			System.out.println("Leap Year");
		else
			System.out.println("Not leap year");
	}
}

Program to find Biggest of Three Numbers:

import java.util.Scanner;
class Code{
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		System.out.println("Enter a, b, c values : ");
		int a = scan.nextInt();
		int b = scan.nextInt();
		int c = scan.nextInt();
		if(a>b && a>c)
			System.out.println("a is big");
		else if(b>c)
			System.out.println("b is big");
		else
			System.out.println("c is big");
	}
}

Program to Calculate current bill based on units consumed:

  • 0-100 -> 0.80 per unit
  • 101-200 -> 1.2 per unit
  • 201-300 -> 1.5 per unit
  • above 300 -> 1.8 per unit
import java.util.Scanner;
class Code 
{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter number of units : ");
		int units = sc.nextInt();
		double bill=0.0;
		if(units>=0 && units<=100)
			bill = units*0.8;
		else if(units>100 && units<=200)
			bill = 80 + (units-100)*1.2;
		else if(units>200 && units<=300)
			bill = 200 + (units-200)*1.5;
		else 
			bill = 350 + (units-300)*1.8;
		System.out.println("Total bill amount : " + bill);
	}
}
Scroll to Top