Java pass by value and memory and CPU usage

Based on background C, I have a very simple question: does a larger data type, such as a String array, skip a value, invokes something like a copy constructor in java.

Thus, this code will create a duplicate list in memory by copying the list in list2. Thus, the use of dual memory and processor.

String[] getList() { String[] list = new String... ... return list; } String [] list2 = getList(); 

Is my assumption correct? If so, is there an alternative, for example, passing pointers in C.

PS: if we allow the garbage collector to clean up additional memory, then this will be another set of processor use memory cleaning cycles that should not have been created in the first place.

+4
source share
2 answers

No, this will not double the memory and CPU usage. In Java, all non-primitive types are stored as links, and these links are passed by value.

So, in your example, the getList method getList build an array on the heap and return a reference to this array. No copy of the array; just a reference copy.

+6
source

No, the contents of the array will not be copied. Instead, a link will be passed pointing to the array on the heap.

There are no pointers in Java; it has links. In Java, references pointing to objects on the heap are passed as arguments and returned by methods. Arrays are objects in Java, so they are also processed this way.

+6
source

Source: https://habr.com/ru/post/1482683/


All Articles