Compare memory locations of two primitives

Roshana Pitigala :

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?

Logan :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=85905&siteId=1