1

Possible Duplicate:
How are Integer arrays stored internally, in the JVM?

In C#, when you are creating a new array which is a reference type so it puts a pointer onto Stack and object itself in Heap. If you create this array with simple primitive types such as int, double, etc. what it does is to put the values exactly where they are placed in Heap instead of a pointer which points at another heap address where the content of it stored.

So can someone please explain how this happens in Java? Java use Integer (a reference type) in arrays all the time or treats value types as C# does?

int[] hello = new int[5];
hello[0] = 2; // C# put this value directly in same slot and doesn't 
//create a wrapping object.

I know a thing which is called Wrapping Types in Java which C# doesn't have. C# has auto-boxing but Int32 lets say not an reference type, but ValueType where as Integer is an object as opposed to int. You can either box a value using Object o = 5; or if struct does have a parent class, you can use it too to wrap it up in heap (boxing).

Community
  • 1
  • 1
Tarik
  • 79,711
  • 83
  • 236
  • 349

3 Answers3

3

Java is much the same as you describe.

int[] hello = new int[5]; // reference hello is on stack, the object is on the heap.
hello[0] = 2; // Java puts this value directly in same slot and doesn't 
              // create a wrapping object.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

Java primitive arrays are stored in the heap as arrays of primitives, not of Integers etc. I do not believe that the actual implementation of how they are stored is specified, so a boolean[] may very well be implemented by an int[] in memory

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
1

In Java, the Array is considered as an Object whether it holds primitive variables or object type, in java Array has one and only one instance variable called length.

int[] arr = new int[5];

arr here is an object reference array variable, which is stored on the STACK if its used Inside the method(ie as local variable), But if its used as an instance variable, then its stored inside the object on the Heap.

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
  • Thanks for the answer Kumar but it doesn't seem we're talking about the same things. I knew those but what I was wondering how Java stored primitive types in Heap using Arrays. Well, I got my answers within previous answers. – Tarik May 30 '12 at 19:23