Sunday, March 16, 2008

How many i 1+1 in Java? ;-)

Last time we spoke about immutability of String in Java, today lets talk about adding Integers ;-)

Lets check how many is 1+1 in Java...

For first try we will use this code:
public class Integers { 
public static void main(String[] args) throws Exception{
Integer i1 = 1;
Integer i2 = 1;
System.out.println(i1+"+"+i2+"="+(Integer)(i1+i2));
}
}

After compile and run we will see on the screen:

1+1=2

It was easy :-)

But to our next try we will add some additional code....

import java.lang.reflect.Field;
public class Integers {
public static void main(String[] args) throws Exception {
Integer i1 = 1;
Integer i2 = 1;
System.out.println(i1+"+"+i2+"="+(Integer)(i1+i2));
fixIntegers();
System.out.println(i1+"+"+i2+"="+(Integer)(i1+i2));

}

static void fixIntegers() throws Exception {
Class integerClass = Integer.class;
Field value = integerClass.getDeclaredField("value");
value.setAccessible(true);
value.setInt(Integer.valueOf(2), 3);
}

}


And now strange things happens....

After we compile and run we can see....

1+1=2
1+1=3

How it's possible? ;-)

Here short explanation ;-)
Method fixIntegers() changes value of int stored as "int representation" in some Integer... This some Integer is rather important ;-) In Sun Java was decided that conversion of some numbers [actually from -128 to 127] is rather often, so why to make this conversion so often? More reasonable will be to keep somewhere array of those Integers and when it will be needed use one of those objects. Method fixIntegers() first gets Integer object for int value of 2, and using reflections it changes value from 2 to 3 :-)
Next "magic" things are in line where we made second addition, we adds 1 to 1, and of course we got as a result 2, but we also wants to convert it to Integer, instead conversion we have here usage of value from "pool", we take this object :-) But because we wants to print String representation of this value method toString() of our object is called... and toString() looks to private variable value and finds in this place... 3 :-)
And it's whole secret ;-)

Similar postsbeta
Abuse of Booleans ;-)
The Secret Life of String ;-)
How to get negative number from size() in LinkedList in Java? ;-)
How to create valid file name?
Recursion is evil ;-)

No comments:

Post a Comment