Java Program to find second largest digit of a number


In this program, You will learn how to find second largest digit of a number in Java.


12321 => 2

24568 => 6


Example: How to find second largest digit of a number in Java

Run it Now
import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        int r, n, l = 0, sl = 0, rev = 0;

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a Number :");
        n = sc.nextInt();

        while (n > 0) {
            r = n % 10;
            if (l < r) {
                l = r;
            }

            rev = rev * 10 + r;
            n = n / 10;
        }

        n = rev;
        while (n > 0) {
            r = n % 10;
            if (l != r) {
                if (sl < r) {
                    sl = r;
                }
            }
            n = n / 10;
        }

        System.out.println("\nThe Second Largest Digit is :" + sl);

    }
}

Output:

Enter a Number :23012
The Second Largest Digit is :2