So, I am trying to figure out how the value inside data changes accordingly. I have written comments to what i have understood. can anyone please explain how values stored in heap and stack memory for this problem.
public class CBV
{
static int data = 10;
public static void main(String []args)
{
// data is a local variable
//int data = 10;
System.out.println("Before data: "+data);
changeData(data);
System.out.println("After data: "+data);
}
public static void changeData(int data)
{
// data is changed and its scope is within this method
// so the original value is not changed
// In java, garbage collection is automatically handled
data = data + 500;
// so here data is garbage collected
}
}
Only objects go on the heap. And (aside from autoboxing) Objects are created using the
newoperator.So in your example, the class object for CBV (including its static data field) goes on the heap (but will never be garbage collected since it isn't dynamically loaded). In changeData,
datais on the stack