Search code examples
javavariablescompareprimitive

Compare memory locations of two primitives


Is there any way which I can compare memory locations of two ints in java?

int x = 25;
int y = 25;

I want to check and prove whether the both variables are referring the same value or they are created twice.

x == y

above line compares the literal values that's not what I want. Any idea?


Solution

  • While this won’t be possible to do with code, you can look at the bytecode generated by your snippet.

    0: bipush        25
    2: istore_1
    3: bipush        25
    5: istore_2
    6: return
    

    Seeing that bipush is called twice, it would appear that two stack allocations are made. An optimization could very well be made later on, though.