-2

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.

9
  • 2
    FYI: The value returned by identityHashCode() has nothing to do with memory address. In general, you cannot get the memory address of an object in Java. Commented Oct 9, 2019 at 11:36
  • 2
    a and c are both primitive int values, so when you call identityHashCode() which expects an Object, the compiler will autobox the values to Integer objects, and values in range -128 to 127 are cached for performance, so you get the same Integer object every time you call the method with value 12. Commented Oct 9, 2019 at 11:39
  • here is another SO-thread on that matter. Including a "workaround" on how to extrapolate the heap-address from an object (the one you see when you use the toString() method of a class that does not override it) Commented Oct 9, 2019 at 11:45
  • @Andreas thank you for the clarification, I removed my comment. Commented Oct 9, 2019 at 11:48
  • 2
    How does the default hashCode() work? Commented Oct 9, 2019 at 11:54

1 Answer 1

-2

Both the integers carry the same value, 12.

Since Integers are cached (for values up to 127 from -128), the hash code value of both objects returned are same.

This is not true for b since its value is greater than 127.

Sign up to request clarification or add additional context in comments.

4 Comments

The value of an int has nothing to do with identityHashCode() of an Object (parameter type of the method).
Try it with obj.b and obj2.b. They have also "the same value", but ...
@Seelenvirtuose - hashcode value of obj.b and obj2.b is not same.
Thanks for answers . now , my problem is int c and int a has the same memory location ? i mean are they point to one location of memory ? or they have different objects in memory cause they are from separate instance ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.