Quantcast
Channel: User Karthik T - Stack Overflow
Viewing all articles
Browse latest Browse all 42

Answer by Karthik T for Pass array by reference in Java

$
0
0

This might be an unpopular way of thinking about it, but being from a C/C++ side myself, it made it easier for me.

In Java, objects are reference types. Meaning that the actual object is on the heap somewhere, and what you actually use is just a reference to that object. Thus it is simpler to think of it in terms of C pointers (as an analogy).

Classname object;

would behave similar to the below in C/C++

Classname *object;

Similarly, in the case of functions, they behave as if the parameters of the function are passed as pointers. Similar to how you would simulate pass-by-reference in C:

void Function(Classname object)

It is more like the below C version

void Function(Classname *object)

And as long as you don’t change the value of the pointer itself (in java by reallocating the variable with a new instance) you can use it to access and modify the original instance.

And to wrap it all up, all types other than the primitive types (int, double,boolean, etc.) are reference types (even types like Integer, Double, Boolean, and arrays).

So as others have explained already, you don’t need to add the & for it to behave as you would expect (except certain caveats like reassignment with a new instance).


Viewing all articles
Browse latest Browse all 42

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>