Program to Find the Greatest of Two Numbers in Java
Finding the Greatest of Two Numbers
Given two integer inputs num1 and num2, the objective is to determine which number is greater using Java programming.
We will explore different methods to achieve this.
Method 1: Using if-else Statement
We use an if-else statement to compare two numbers and determine the greatest one.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter first number: "); int num1 = scanner.nextInt(); System.out.print("Enter second number: "); int num2 = scanner.nextInt(); if (num1 > num2) { System.out.println(num1 + " is the greatest number"); } else if (num2 > num1) { System.out.println(num2 + " is the greatest number"); } else { System.out.println("Both numbers are equal"); } scanner.close(); } }
Output:
Enter first number: 5 Enter second number: 10 10 is the greatest number
Method 2: Using Ternary Operator
We use the ternary operator to find the greatest number in a single line.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter first number: "); int num1 = scanner.nextInt(); System.out.print("Enter second number: "); int num2 = scanner.nextInt(); int greatest = (num1 > num2) ? num1 : num2; System.out.println(greatest + " is the greatest number"); scanner.close(); } }
Output:
Enter first number: 7 Enter second number: 3 7 is the greatest number
Method 3: Using Function
We create a function to compare two numbers and return the greatest one.
import java.util.Scanner; public class Main { public static int findGreatest(int a, int b) { return (a > b) ? a : b; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter first number: "); int num1 = scanner.nextInt(); System.out.print("Enter second number: "); int num2 = scanner.nextInt(); System.out.println(findGreatest(num1, num2) + " is the greatest number"); scanner.close(); } }
Output:
Enter first number: 4 Enter second number: 9 9 is the greatest number