I am confused with the memory allocation of references in Java when you pass them to the methods in Java. As a Test I did an example as below,
class Store{
public int[] buffer = new int[5];
}
class ConsumeStore{
Store store;
public ConsumeStore(Store store){
this.store = store;
}
public int useStore(){
return store.buffer[0];
}
}
class ProduceStore{
Store store;
public ProduceStore(Store store){
this.store = store;
}
public void putStore(){
store.buffer[0] = 100;
}
}
public class CheckRef {
public static void main(String args[]){
Store store = new Store();
ConsumeStore consStore = new ConsumeStore(store);
ProduceStore prodStore = new ProduceStore(store);
prodStore.putStore();
System.out.println(consStore.useStore());
}
}
Well the output is 100.
Here I am passing the Store reference to ProducerStore. Inside ProducerStore I am assigning it to the class member of it. I am doing the same for ConsumerStore as well.
Could someone explain me how the memory allocation is done for Store referece and how it shared among the ProducerStore and ConsumerStore?
Both your
ProducerStoreandConsumerStorehave a reference to the same objectstore, that you passed to each one.So when you modify
storeinternal state (itsbuffermember), either externally or in any of the Producer/Consumer, all the classes that have reference to it are “updated” because they don’t hold a distinct value, they only hold a reference to the unique valuestore.Something different would happen if you reallocated the object entirely. For example:
In this case, the Consumer and the Producer would have a different store: Consumer would still have a reference to the original store, while Producer would have the new one defined within the Put method.
You can think of it as: everytime you do a
new, a new object is created in memory. Then when you pass it around to classes, everyone only has reference to that unique object.