How to devide Integer value

C

column.column

Helo,

I need to divide Integer value by 2. Is it only one method to create
new Integer? Looks cumbersome.

Integer i = new Integer(10);
....
Integer i = New Integer(i.intValue()/2);

Thank You
 
O

Owen Jacobson

Helo,

I need to divide Integer value by 2. Is it only one method to create
new Integer? Looks cumbersome.

Integer i = new Integer(10);
...
Integer i = New Integer(i.intValue()/2);

Thank You

Yes, like the documentation says, Integer (and all the primitive
wrapper classes) objects are immutable. However, if you're using Java
5 or later, you don't need to write out the unpacking to an int and
creation of new Integers yourself: the language will automatically
unbox and box primitives into their respective wrappers.

You could write the above as

Integer i = 10;
Integer j = i / 2;

and let Java worry about the rest. Alternately, you could use int
instead of Integer.

-o
 
R

RedGrittyBrick

Owen said:
Yes, like the documentation says, Integer (and all the primitive
wrapper classes) objects are immutable. However, if you're using Java
5 or later, you don't need to write out the unpacking to an int and
creation of new Integers yourself: the language will automatically
unbox and box primitives into their respective wrappers.

You could write the above as

Integer i = 10;
Integer j = i / 2;

and let Java worry about the rest. Alternately, you could use int
instead of Integer.

You can also write the OP's expression as
Integer i = 10;
i = i / 2;
Which the OP should find is not as "cumbersome".
 
A

Arne Vajhøj

I need to divide Integer value by 2. Is it only one method to create
new Integer? Looks cumbersome.

Integer i = new Integer(10);
...
/*Integer*/ i = New Integer(i.intValue()/2);

My guess is that you should use:

int i = 10;
i = i / 2;

and wrap in Integer when you need it.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top