I am getting a bit confused regarding few points regarding Java memory management.
Understood what is the difference between Stacks and Heap and I went to see a proper example on what is those memories when we execute some code.
I took for example this few lines
public static void main(String[] args)
{
int a = 5;
calculate(a);
System.out.println(a); //will print 5 not 50
}
private static void calculatee(int a)
{
a = a * 10;
}
I understood what is happening in the stack and in the heap. The variable is not getting returned and there is no reference to the Heap in this case.
while in this example:
public static void maina(String[] args)
{
Customer customer = new Customer("John");
setAName(customer);
System.out.println(customer.getName()); // this will return Philip
}
private static void setAName(Customer c)
{
c.setName("Philip");
}
I can see the state of the object changed this time!
Stacks are not shared thought threads, but heap is shared! Which make sense to me that the object customer has changed its value from Jhon to Philip when I am printing it! Great! all make sense!
However, I was expecting that if I will do this
public static void main(String[] args)
{
Integer i = new Integer(5);
calculate(i);
System.out.println(i); // printing 5 and not 50
}
private static void calculate(Integer i)
{
i = i * 10;
}
I would get 50 and not 5!
In this case Integer is an object and I am assuming it is created in the heap!
Funny thing is that if I will wrap the Integer inside Customer I will get 50 instead of 5.
Why is this happening? Isn't the Integer type getting created in the Heap?