Jump to content

Pass-by-Value vs Pass-by-reference (Java)


Recommended Posts

Posted

....

The problem we're facing here is statements like In Java, Objects are passed by reference, and primitives are passed by value. This is half incorrect. Everyone can easily agree that primitives are passed by value; there's no such thing in Java as a pointer/reference to a primitive. However, Objects are not passed by reference. A correct statement would be Object references are passed by value. This may seem like splitting hairs, bit it is far from it. There is a world of difference in meaning. The following examples should help make the distinction.

...

 

Interesting article:

 

http://javadude.com/articles/passbyvalue.htm

  • Like 3
  • 2 weeks later...
Posted (edited)

Java uses quite a few tricks to achieve what other languages have while still being user-friendly, and this is a great example. Although, after reading the article, I was kinda confused.

For anyone having troubles understanding, if objects were pass-by-reference, this would be possible:

void method(String string) {
    string = "second";
}

String string = "first";
method(string);
System.out.println(string); //prints "second"

Rather than passing the actual reference to that object, a new reference is created (the formal parameter), which then references the object.

So saying object references are pass by value is not true, since a reference value is a pointer to the object, and passing the reference value (pointer) is passing by reference. If you wanna get literal with it, object identities are (currently) pass by value.

Another thing that confuses some developers is how generics are a compile time illusion, and all generic types are converted to Object (type erasure) once compiled. This is why you cannot have "void method(List<String>)" and overload it with "void method(List<Integer>)", since both compile to the same after erasure.

Edited by fixthissite
  • Like 1

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...