Check Largest of Two Numbers
This program finds the largest of two numbers using nested if.
Problem Statement
Write a Java program that finds the largest of two numbers using nested if.
Source Code
| 1 | public class LargestTwo { |
| 2 | public static void main(String[] args) { |
| 3 | int a = 15, b = 25; |
| 4 | if(a != b) { |
| 5 | if(a > b) { |
| 6 | System.out.println("Largest: " + a + " - Eduinq"); |
| 7 | } else { |
| 8 | System.out.println("Largest: " + b + " - Eduinq"); |
| 9 | } |
| 10 | } else { |
| 11 | System.out.println("Both numbers are equal - Eduinq"); |
| 12 | } |
| 13 | } |
| 14 | } |
Program Output
Largest: 25 - Eduinq
Explanation
The program first checks if the two numbers are not equal using if(a != b). - If they are different, it enters another if block to compare them. - If a > b, it prints a as the largest; otherwise, it prints b. - If the numbers are equal, the outer else block executes. - This demonstrates nested if statements, where one condition is checked inside another, allowing more precise control flow. Conclusion: Shows how nested if can be used to handle multiple levels of conditions.