Java language have 2 data types .
1.Primitive type.
2. Reference type.
Primitive values do not share state with other primitive values. A variable whose type is a primitive type always holds a primitive value of that same type. The value of a variable of primitive type can be changed only by assignment operations on that variable.
The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
According to your first example
Integer i1 and i2 means two different objects and their memory addresses are different.But they are point same value.That 's why
it print 'different objects'
for comparing object values we use ob1.equals(object ) method which return
true if the comparing two object have same value ,that ' s why it print
'meaningfully equal'
---------------------------------------------------------------------------For your second question i take this from
http://www.theserverside.com/news/thread.tss?thread_id=27129I've seen a lot of posts in this thread about what is happening on ==
It's simple:
When we do
Integer i = 127;
autoboxing turns this into:
Integer i = Integer.valueOf( 127 );
Go look at the implementation of Integer.valueOf(), and you'll find:
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
If the int value is between -128 and 127, it will return a cached Integer value. This way we avoid creating many duplicate Integer objects for those common values. It save's on memory and improves performance.
And, of course, it does mean that Integer i = 127 will always return the same Integer instance.
--------------------------------------------------------------------------
For more on this topic please visit following urls.
http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html#85587http://creativekarma.com/ee.php/weblog/comments/value_types_in_java/http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.htmlHope this helpful.
Best Regards.