In the below example, how many number of objects will be created? And also Explain the logic regarding the same?
class test {
public static void main(String args[]) {
// 1 Integer Object
Integer i=10;
// 1 Integer Object
Integer j=10;
// sum of Integer Object
Integer k=i+j;
}
}
As per my knowledge it will create 2 objects. 1st for Integer i=10 it internally converts to Integer.valueOf(10) and then calls the valueof method of Integer and these internally calls the IntegerCache and gets the object by creation of it and stores in cache. similar for j as already it is cached it points to same object then the k object will be created. So total 2 .
But some are saying that Integer values with in -127 to +128 we will get objects from cache. 1st for Integer i=10 it internally converts to Integer.valueOf(10) and then calls the valueof method of Integer and these internally calls the IntegerCache and gets the object by cache. similar for j from cache. and K value 20 also from cache. So objects will be zero.
So I am not sure whether it is 0 or 2.
If anyone knows please let me know.