0

a code snippet

    Scanner sc=new Scanner(System.in);
    System.out.println("enter size of array");
    int size=sc.nextInt();
    int[] arr=new int[size];//Is the array arr allocated on heap?

Is there something called dynamic memory allocation for arrays?

skm
  • 25
  • 4
  • *dynamic memory allocation for arrays* `Array` or `ArrayList` ? – Ravi Aug 26 '17 at 07:51
  • https://stackoverflow.com/questions/14837185/how-can-we-dynamically-allocate-and-grow-an-array – Naman Aug 26 '17 at 07:51
  • 6
    It's the heap. Whenever you see the word `new`, something goes on the heap. – Dawood ibn Kareem Aug 26 '17 at 07:51
  • Not sure what you mean by "dynamic". The array cannot change its size after it has been created, but you can create new arrays (and choose their size) at runtime at will. – Thilo Aug 26 '17 at 07:57
  • 2
    And all object allocations (including arrays) use the heap. See https://stackoverflow.com/questions/10953806/java-array-using-stack-space – Thilo Aug 26 '17 at 07:59
  • If You are thinking in C way (fast 'allocation' and 'deallocation' on stack) - Java allocation & garbage collector is highly optimised for short living objects – Jacek Cz Aug 26 '17 at 08:03

2 Answers2

1
int[] arr=new int[size];//Is the array arr allocated on heap?

Note that there is no "array arr".

There is an array - which is necessarily on the heap, because arrays are objects, and all Java objects reside on the heap - and there is a reference to that, arr, which resides on the stack, because it's a local variable.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

Java objects reside in an area called the heap. Newly contructed objects are first allocated in an area of heap called eden.

The stack contains references to Objects and values of primitive types for the scope of current method:

  • When we are creating primitive local variable it’s created and stored in the stack memory.
  • When we are creating an Object, it’s created in Heap memory and stack memory contains the reference for it.

When we are creating an array of primitive type, it's created in Heap memory and stack memory contains the reference for it.

Krzysztof Cichocki
  • 6,294
  • 1
  • 16
  • 32