One of friend Subhash Chand asked me foll. question:
Question:
-------------
Integer a = new Integer(10);
Integer b = new Integer(10);
boolean test =a < b || a == b || a > b;
If you found any valuable reason then please tell me?
Answer :
------------
The value of boolean test comes out to be false. we might have
expected it to be true.
Reason:
------------
For all operations other than equality (==) an intValue is computed on
Integer object which results in int value 10.
But with equality just keep in mind foll. concepts:
1. Integers are Immutable while int values are mutable
2. Integers maintain a pool just as Strings have.
3. The Integer pool is from -128 to 127 only.
4. The Integers created with new keyword are not created in pool.
With above 4 concepts we can say that (a==b) in the question results
false and so a<b || a==b || a>b results false.
Just try these also:
public static void main(String[] args) throws InterruptedException {
Integer i1 = 100;
Integer i2 = 100;
// Comparison of integers from the pool - returns true.
compareInts(i1, i2);
Integer i3 = 130;
Integer i4 = 130;
// Same comparison, but from outside the pool
// (not in the range -128 to 127)
// resulting in false.
compareInts(i3, i4);
Integer i5 = new Integer(100);
Integer i6 = new Integer(100);
// Comparison of Integers created using the 'new' keyword
// results in new instances and '==' comparison leads to false.
compareInts(i5, i6);
}
private static void compareInts(Integer i1, Integer i2){
System.out.println("Comparing Integers " +
i1 + "," + i2 + " results in: " + (i1 == i2) );
}
More information on:
http://www.devx.com/tips/Tip/42276?trk=DXRSS_JAVA
Please comment if you can add something?