</>

Technology

Java Programs

Difficulty

Beginner

Interview Question

Write a Java program to find the greatest of three numbers.

Answer

Find Greatest of Three Numbers

Java
public class GreatestOfThreeNumbers {
    public static void main(String[] args) {
        int a = 50;
        int b = 100;
        int c = 20;

        if (a > b && a > c) {
            System.out.println("a is greatest");
        } else if (b > a && b > c) {
            System.out.println("b is largest");
        } else {
            System.out.println("c is greatest");
        }
    }
}

Output

CODE
b is largest

Using Scanner (User Input)

Java
import java.util.Scanner;

public class GreatestInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a, b, c: ");
        int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt();

        int greatest = Math.max(a, Math.max(b, c));
        System.out.println("Greatest: " + greatest);
        sc.close();
    }
}

Using Math.max() (Cleanest)

Java
int a = 50, b = 100, c = 20;
int greatest = Math.max(a, Math.max(b, c));
System.out.println("Greatest: " + greatest);  // → 100

Using Ternary Operator

Java
int a = 50, b = 100, c = 20;
int greatest = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
System.out.println("Greatest: " + greatest);  // → 100

Handle Equal Numbers

Java
if (a >= b && a >= c)
    System.out.println("a is greatest (or tied)");
else if (b >= a && b >= c)
    System.out.println("b is greatest (or tied)");
else
    System.out.println("c is greatest");

Automation Testing Relevance

Java
// Find the highest priced product on a page
List<WebElement> prices = driver.findElements(By.css(".price"));
int maxPrice = prices.stream()
    .mapToInt(e -> Integer.parseInt(e.getText().replace("$", "")))
    .max().orElse(0);
System.out.println("Highest price: $" + maxPrice);

Follow AutomateQA