Reverse Digits of Integer in Java

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


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

Sample Output



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.

Posted by at on

Tags: java.lang,