Max of 3 Using Nested If in Java

Find the maximum of three numbers using nested if statements.

BeginnerModule 2: Conditional ProgramsExample 9 of 20
max-of-3-using-nested-if.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6
7 System.out.print("Enter first number: ");
8 int a = sc.nextInt();
9 System.out.print("Enter second number: ");
10 int b = sc.nextInt();
11 System.out.print("Enter third number: ");
12 int c = sc.nextInt();
13
14 int max;
15 if (a >= b) {
16 if (a >= c) {
17 max = a;
18 } else {
19 max = c;
20 }
21 } else {
22 if (b >= c) {
23 max = b;
24 } else {
25 max = c;
26 }
27 }
28
29 System.out.println("Maximum = " + max);
30
31 sc.close();
32 }
33}

Output

Enter first number: 3
Enter second number: 9
Enter third number: 7
Maximum = 9

What's going on

We use nested if inside another if to compare three numbers step by step.