2

I was thinking about Java and memory managment, there is something I'm not sure about.

Lets say we are using wrapper class Integer to represent int type as an object

we create two objects

Integer x = 1; Integer y = 1:

My question is, does Java create two identical objects at two different memory locations and reference them with x and y. or it creates only one object and use both references to point to that one object?

Also, is there a way to find out where objects are stored in memory in Java?

ssayyed
  • 766
  • 1
  • 8
  • 13
  • In your case, you are creating two different objetcs, to two different memory positions with the same value, that it is stored twice. – RamonBoza Nov 05 '13 at 11:33
  • Even i think you check if(x == y) if it returns true then those two variable x, y refers to same object :). == always check memory reference not object state, so easily you can figure out. – Jayasagar Nov 05 '13 at 11:35

3 Answers3

3

JVM implements cache for small Integer objects. And you do not need to get address of java object.

Community
  • 1
  • 1
2

Regarding to Integer - it has it's own cache which does not create any new instances for range -128..127

So in your case it will be referencing the same object.

Integer.class

     public static Integer valueOf(int i) {
         final int offset = 128;
         if (i >= -128 && i <= 127) { // must cache
             return IntegerCache.cache[i + offset];
         }
         return new Integer(i);
     }
Igor Konoplyanko
  • 9,176
  • 6
  • 57
  • 100
0

Compilers usually look for optimizations like that and apply Copy on Write http://en.wikipedia.org/wiki/Copy-on-write

You can check with strings because two strings defined like

String x = "test";
String y = "test":

are comparable like this

if (x == y) 

Which any other time would need .equals to compare.

for example

public class test
{
  public static void main(String[] args){
    String x = "test";
    String y = "test";
    if (x == y){
      System.out.print("Same object");
    }
  }
}

then running

$ java test 
Same object
exussum
  • 18,275
  • 8
  • 32
  • 65