Java Program to find the second largest digit of a number


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


12321 => 2

24568 => 6

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

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("Second largest digit is:" + sl);

    }
}

Output:

Enter a number:2341
Second largest digit is:3