ADS

Reverse Digits Of Integer In Java

An easy example on reversing digits of an integer in Java using convert and do.

Example

 import java.util.*;
class ReverseDigits
{
    public static void main(String args[])
    {
    Scanner s=new Scanner(System.in);
    int i=reverseDigits(s.nextInt());
    System.out.println(i);
    }
   
    public static int reverseDigits(int k)
    {
    String st=k+"";
    StringBuffer sb=new StringBuffer(st).reverse();
    return new Integer(sb.toString()).intValue();
    }
}

Sample Output

 988
889

Explanation


reverseDigits(): This is a method that takes an integer and then convert to string and then reverse it and then return an int.

st=k+""; This is an easy way of converting an int to string. Appending "". Nothing in fact is appended, an open and close of the double quotes just does the thing.

sb=new StringBuffer(st).reverse(); This statement creates a StringBuffer object of the string (which is the given int) and then the reverse method reverses the string.

new Integer(sb.toString()).intValue(): Gives the int value of string. The java.lang.Integer class contains this. The constructor here takes a java.lang.String as parameter.

Subscribe to receive free email updates:

ADS