Java Program to find the Smallest of Three Numbers

Write a Java program to find the smallest number among the given three numbers using Else If, Nested If, and ternary operators. In this Java example, we used the else if to check whether each number is smaller than the other two.

package RemainingSimplePrograms;

import java.util.Scanner;

public class SmallestofThree1 {
	private static Scanner sc;
	public static void main(String[] args) {
		int x, y, z;
		sc = new Scanner(System.in);		
		System.out.println("Please Enter three Numbers: ");
		x = sc.nextInt();
		y = sc.nextInt();
		z = sc.nextInt();
		
		if (x < y && x < z) {
			System.out.format("\n%d is the Smallest Number", x);
		}
		else if (y < x && y < z) {
			System.out.format("\n%d is the Smallest Number", y);
		}	
		else if (z < x && z < y) {
			System.out.format("\n%d is the Smallest Number", z);
		}		
		else {
			System.out.println("\nEither any 2 values or all of them are equal");
		}
	}
}
Please Enter three Numbers: 
44
99
128

44 is the Smallest Number

Java Program to find the Smallest of Three Numbers using Nested If statement

package RemainingSimplePrograms;

import java.util.Scanner;

public class SmallestofThree3 {
	private static Scanner sc;
	public static void main(String[] args) {
		int x, y, z;
		
		sc = new Scanner(System.in);	
		
		System.out.println("Please Enter three Numbers: ");
		x = sc.nextInt();
		y = sc.nextInt();
		z = sc.nextInt();
		
		if (x - y < 0 && x - z < 0) {
			System.out.format("\n%d is Smaller Than both %d and %d", x, y, z);
		}
		else {
			if (y -z < 0) {
				System.out.format("\n%d is Smaller Than both %d and %d", y, x, z);
			}
			else {
				System.out.format("\n%d is Smaller Than both %d and %d", z, x, y);
			}
		}
	}
}
Please Enter three Numbers: 
98
11
129

11 is Smaller Than both 98 and 129

In this Java smallest of three numbers example, we used the ternary operator twice. The first one checks whether x is greater than y and z, and the second one checks whether y is less than z.

package RemainingSimplePrograms;

import java.util.Scanner;

public class SmallestofThree2 {
	
	private static Scanner sc;
	
	public static void main(String[] args) {
		
		int x, y, z, smallest;
		
		sc = new Scanner(System.in);	
		
		System.out.println("Please Enter three Numbers: ");
		x = sc.nextInt();
		y = sc.nextInt();
		z = sc.nextInt();
		
		smallest = ((x < y && x < z)? x: (y < z)?y:z);
		System.out.format("Smallest number among three is: %d", smallest);
	}
}
Java Program to find the Smallest of Three Numbers 2