Reversing the digits of an integer For CS class, I had to reverse the digits of an integer from the input. This is my solution:

System.out.println(new StringBuilder(new Integer(new Scanner(System.in).nextInt()).toString()).reverse().toString());


My main question is this: is this too golfed?

Obviously I could simply add whitespace and comments, but is this level of directness practical?

Also, is there a better way to do this? Perhaps something like the following:


final String string = new Integer(new Scanner(System.in).nextInt()).toString();
for (int i = string.length(); i != -1; System.out.print((i-- != 0) ? string.charAt(i) : "\n"));
In Java, and in Code Review, the preference is for creating both highly readable, and highly efficient code.

It is an almost bizarre fact, that one leads to the other.

your code has one efficiency, and that is space-on-disk.... it is neither readable, nor high-performance.

System.out.println(new StringBuilder(new Integer(new Scanner(System.in).nextInt()).toString()).reverse().toString());



For a start, having to scroll off the page means you have to read with your mouse, not with your eyes.
Secondly, it is very hard to evaluate what parenthesis match when they are all clumped together.


Breaking your code down (which should not be necessary), we have:


int valinput = new Scanner(System.in).nextInt();
String stringinput = new Integer(valinput).toString();
String reversed = new StringBuilder(stringinput).reverse().toString();
System.out.println(reversed);



Now, you need error handling on the Scanner, and it needs to be closed as well. Without that, you have a program that is ugly when a user types in 123.0.

Since you have no error handling, you may as well just junk the lines with the Integer...

And, there is no reason to convert the StringBuilder to a String directly...

Without error handling, you can:

System.out.println(new StringBuilder().append(scanner.nextInt()).reverse());


That is, effectively equivalent to your code, but it has different error-condition characteristics..

Also, it is, suprisingly, quite readable, and fast.

Now, all you need is the try/catch for the scanner, and you are sorted.