I wrote this code and want to see memory location of 2 objects that i create from one class and make instance of one specific variable.
public class StaticFields { int a = 12; int b = 235; public static void main(String[] args) { StaticFields obj = new StaticFields(); int a = obj.a; StaticFields obj2 = new StaticFields(); int c = obj2.a; System.out.println(System.identityHashCode(a)); System.out.println(System.identityHashCode(c)); } } why the "identityHashCode" of "a" and "c" is the same ?
Thanks.
identityHashCode()has nothing to do with memory address. In general, you cannot get the memory address of an object in Java.aandcare both primitiveintvalues, so when you callidentityHashCode()which expects anObject, the compiler will autobox the values toIntegerobjects, and values in range -128 to 127 are cached for performance, so you get the sameIntegerobject every time you call the method with value12.toString()method of a class that does not override it)