Java Program to Output next Largest Number using same Digits

Java Programs

Problem: Write a program in Java to output the next largest number using the same digits if possible or else output the same.


Input:  123                                                                                               
Output: 132

Input:  1465
Output: 1546
next largest number using the same digits

The trick is to look (from right) for the digit (say a[i]) that is greater than the digit at its left (say a[i-1]).

If found then look for the digit (say min) at the right of index ‘i’ which is smaller than a[i] but greater than a[i-i].

Swap a[i-1] and min.

Sort all the digits after min in the ascending order.

The final outcome will be the nearest greatest integer using the same digits.

import java.util.*; 
public class Main { 
    public static void main(String[] args){ 
        Scanner in=new Scanner(;
        //Input a number and transform it to a char array
        System.out.print("Enter a number: ");
    	char a[]; 
    	//store the length of number in 'n'
    	int i, n=a.length; 
    	//check from back for a[i-1] < a[i]
    	for(i=n-1; i>0; i--){ 
            if(a[i-1] < a[i]) 
    	//If 'i' value reaches 0, it means digits are in descending order
    	//Hence, we cannot form any higher number using the same digits
            for(i=0; i<n; i++) 
            //If found then look for (a[i-1] < min < a[i]) after a[i]
            int min=i;
            for(int j=i+1; j<n; j++){ 
                //if found then copy its index to min
                if (a[j]>a[i-1] && a[j]<a[min]){ 
                    min = j; 
            //swap a[i-1] and a[min]
            char temp = a[i-1]; 
            a[i-1] = a[min]; 
            a[min] = temp; 
            //sort all after min (i.e. after i inclusive) in ascending order
            Arrays.sort(a, i, n); 
            //output the result
            System.out.print("Next greater number: ");


Enter a number: 1465
Next greater number: 1546

As you can see, we were successfully able to find the next largest number using the same digits in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *