This is the third solution to find the reverse of an integer value using String (immutable) class. This shows the core logic of storing the characters in reverse direction.
import java.util.Scanner;
public class ReverseOfIntUsingString {
private static final String NULL = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
@SuppressWarnings("resource")
Scanner inpInt= new Scanner(System.in);
//Input an Integer
System.out.println("Enter an Integer=");
int numValue=inpInt.nextInt();
System.out.println("The integer is="+numValue);
// Convert Integer to String
String int2Str=String.valueOf(numValue);
String revVal = "";
// Concatenate each character from source string to destination string
for(int i=int2Str.length()-1;i>=0;i--) {
revVal=revVal+int2Str.charAt(i);
}
// Convert the reversed String to original integer
System.out.println("The integer after reverse is="+Integer.parseInt(revVal));
}
}
Output:
Enter an Integer=
943
The integer is=943
The integer after reverse is=349

Leave a comment