+ 4

Help me with arrays in Java

While defining arrays in Java, we use something like * int[] arr=new int [5]; * Here, I have some clarifications to be made. First of all, why are we defining it on the heap?? Why can't it be on the stack? In the tutorial, the array was not deallocated from the heap, is it a mistake, or am I missing something? Why can't the definition of array be like ***int arr[5]***(brackets after the name and allocated on the stack)? Thank you :)

19th Aug 2021, 2:40 AM
Rishi
Rishi - avatar
6 ответов
+ 1
https://www.javatpoint.com/array-in-java Java has its own memory management tool called Garbage Collector (short: GC). There's no need for memory deallocation as the GC takes care of it.
19th Aug 2021, 6:06 AM
Ipang
+ 1
Ipang ooh tnx. Plz answer my other two questions too
19th Aug 2021, 11:03 AM
Rishi
Rishi - avatar
+ 1
Rishi, Which ones though? I see answers in all your questions ...
19th Aug 2021, 11:54 AM
Ipang
+ 1
Ipang 1) Can't we define arrays on the stack? Sometimes I see array definitions like * int[] arr={3,4,5}; * Are these arrays on the stack? 2) My code below is not producing the correct output. Can you find why it's not producing the correct output? https://code.sololearn.com/cDyOHEvoDxse/?ref=app
20th Aug 2021, 2:02 AM
Rishi
Rishi - avatar
+ 1
Ipang ooh, thank you so much! Now I have my doubt cleared. Actually, it turns out that "int[] arr={3,4,5}" is just a short hand for "int[] arr=new int[](3,4,5)". So it's on the heap. Second, there is only pass by value in Java. So that we can't have arrays on the stack. Reason, if we had arrays on the stack, when we pass them to a function, we have to pass it by value which is slower. When the array is on the heap, the array variable(storing the array's location on the heap) is alone stored on the stack. So when we pass it to a function, only the memory address is passed, so it's fast and secure. Hope you got it :)
21st Aug 2021, 1:56 AM
Rishi
Rishi - avatar