Jagmal Jagmal - 1 month ago 6
Java Question

How to multiply 10 to an "Integer" object in Java?

How do I multiply 10 to an

Integer
object and get back the
Integer
object?

I am looking for the neatest way of doing this.

I would probably do it this way:
Get int from
Integer
object, multiply it with the other int and create another Integer object with this int value.

Code will be something like ...

integerObj = new Integer(integerObj.intValue() * 10);


But, I saw a code where the author is doing it this way: Get the
String
from the
Integer
object, concatenate "0" at the end and then get
Integer
object back by using
Integer.parseInt


The code is something like this:

String s = integerObj + "0";
integerObj = Integer.parseInt(s);


Is there any merit in doing it either way?

And what would be the most efficient/neatest way in general and in this case?

Answer Source

With Java 5's autoboxing, you can simply do:

Integer a = new Integer(2); // or even just Integer a = 2;
a *= 10;
System.out.println(a);