#9 most askedVery commonMediumJVM & memory
Stack vs heap, and how garbage collection works
New to JVM & memory? Learn it from scratch firstMemory: The Stack, the Heap & References โ
๐ข Asked in real interviews
No reports yet. Were you asked this? Be the first to say where.Where do variables and objects live in Java memory, and how does the garbage collector decide what to free?
๐ฎ Predict the output
public class Main {
static void grow(int[] arr, int n) {
n = n + 1; // changes the local copy only
arr[0] = 99; // changes the shared object on the heap
}
public static void main(String[] args) {
int n = 1;
int[] arr = {1};
grow(arr, n);
System.out.println(n + " " + arr[0]);
}
}
๐ค Answer it out loud, then check yourself
Say your answer as if the interviewer is listening (30โ90 seconds). Then reveal what a strong answer covers and tick what you said.
Answer out loud first, then compare.
Want to rehearse it?Answer this to the AI interviewer and get a verdict โ