Is Java "pass-by-reference" or "pass-by-value"?

2,420,746

Solution 1

Java is always pass-by-value. Unfortunately, when we deal with objects we are really dealing with object-handles called references which are passed-by-value as well. This terminology and semantics easily confuse many beginners.

It goes like this:

public static void main(String[] args) {
    Dog aDog = new Dog("Max");
    Dog oldDog = aDog;

    // we pass the object to foo
    foo(aDog);
    // aDog variable is still pointing to the "Max" dog when foo(...) returns
    aDog.getName().equals("Max"); // true
    aDog.getName().equals("Fifi"); // false
    aDog == oldDog; // true
}

public static void foo(Dog d) {
    d.getName().equals("Max"); // true
    // change d inside of foo() to point to a new Dog instance "Fifi"
    d = new Dog("Fifi");
    d.getName().equals("Fifi"); // true
}

In the example above aDog.getName() will still return "Max". The value aDog within main is not changed in the function foo with the Dog "Fifi" as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return "Fifi" after the call to foo.

Likewise:

public static void main(String[] args) {
    Dog aDog = new Dog("Max");
    Dog oldDog = aDog;

    foo(aDog);
    // when foo(...) returns, the name of the dog has been changed to "Fifi"
    aDog.getName().equals("Fifi"); // true
    // but it is still the same dog:
    aDog == oldDog; // true
}

public static void foo(Dog d) {
    d.getName().equals("Max"); // true
    // this changes the name of d to be "Fifi"
    d.setName("Fifi");
}

In the above example, Fifi is the dog's name after call to foo(aDog) because the object's name was set inside of foo(...). Any operations that foo performs on d are such that, for all practical purposes, they are performed on aDog, but it is not possible to change the value of the variable aDog itself.

For more information on pass by reference and pass by value, consult the following SO answer: https://stackoverflow.com/a/430958/6005228. This explains more thoroughly the semantics and history behind the two and also explains why Java and many other modern languages appear to do both in certain cases.

Solution 2

I just noticed you referenced my article.

The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java.

The key to understanding this is that something like

Dog myDog;

is not a Dog; it's actually a pointer to a Dog. The use of the term "reference" in Java is very misleading and is what causes most of the confusion here. What they call "references" act/feel more like what we'd call "pointers" in most other languages.

What that means, is when you have

Dog myDog = new Dog("Rover");
foo(myDog);

you're essentially passing the address of the created Dog object to the foo method.

(I say essentially because Java pointers/references aren't direct addresses, but it's easiest to think of them that way.)

Suppose the Dog object resides at memory address 42. This means we pass 42 to the method.

if the Method were defined as

public void foo(Dog someDog) {
    someDog.setName("Max");     // AAA
    someDog = new Dog("Fifi");  // BBB
    someDog.setName("Rowlf");   // CCC
}

let's look at what's happening.

  • the parameter someDog is set to the value 42
  • at line "AAA"
    • someDog is followed to the Dog it points to (the Dog object at address 42)
    • that Dog (the one at address 42) is asked to change his name to Max
  • at line "BBB"
    • a new Dog is created. Let's say he's at address 74
    • we assign the parameter someDog to 74
  • at line "CCC"
    • someDog is followed to the Dog it points to (the Dog object at address 74)
    • that Dog (the one at address 74) is asked to change his name to Rowlf
  • then, we return

Now let's think about what happens outside the method:

Did myDog change?

There's the key.

Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog (but note that because of line "AAA", its name is now "Max" - still the same Dog; myDog's value has not changed.)

It's perfectly valid to follow an address and change what's at the end of it; that does not change the variable, however.

Java works exactly like C. You can assign a pointer, pass the pointer to a method, follow the pointer in the method and change the data that was pointed to. However, the caller will not see any changes you make to where that pointer points. (In a language with pass-by-reference semantics, the method function can change the pointer and the caller will see that change.)

In C++, Ada, Pascal and other languages that support pass-by-reference, you can actually change the variable that was passed.

If Java had pass-by-reference semantics, the foo method we defined above would have changed where myDog was pointing when it assigned someDog on line BBB.

Think of reference parameters as being aliases for the variable passed in. When that alias is assigned, so is the variable that was passed in.

Solution 3

Java always passes arguments by value, NOT by reference.


Let me explain this through an example:

public class Main {

     public static void main(String[] args) {
          Foo f = new Foo("f");
          changeReference(f); // It won't change the reference!
          modifyReference(f); // It will modify the object that the reference variable "f" refers to!
     }

     public static void changeReference(Foo a) {
          Foo b = new Foo("b");
          a = b;
     }

     public static void modifyReference(Foo c) {
          c.setAttribute("c");
     }

}

I will explain this in steps:

  1. Declaring a reference named f of type Foo and assign it a new object of type Foo with an attribute "f".

    Foo f = new Foo("f");
    

    enter image description here

  2. From the method side, a reference of type Foo with a name a is declared and it's initially assigned null.

    public static void changeReference(Foo a)
    

    enter image description here

  3. As you call the method changeReference, the reference a will be assigned the object which is passed as an argument.

    changeReference(f);
    

    enter image description here

  4. Declaring a reference named b of type Foo and assign it a new object of type Foo with an attribute "b".

    Foo b = new Foo("b");
    

    enter image description here

  5. a = b makes a new assignment to the reference a, not f, of the object whose attribute is "b".

    enter image description here

  6. As you call modifyReference(Foo c) method, a reference c is created and assigned the object with attribute "f".

    enter image description here

  7. c.setAttribute("c"); will change the attribute of the object that reference c points to it, and it's the same object that reference f points to it.

    enter image description here

I hope you understand now how passing objects as arguments works in Java :)

Solution 4

Java is always pass by value, with no exceptions, ever.

So how is it that anyone can be at all confused by this, and believe that Java is pass by reference, or think they have an example of Java acting as pass by reference? The key point is that Java never provides direct access to the values of objects themselves, in any circumstances. The only access to objects is through a reference to that object. Because Java objects are always accessed through a reference, rather than directly, it is common to talk about fields and variables and method arguments as being objects, when pedantically they are only references to objects. The confusion stems from this (strictly speaking, incorrect) change in nomenclature.

So, when calling a method

  • For primitive arguments (int, long, etc.), the pass by value is the actual value of the primitive (for example, 3).
  • For objects, the pass by value is the value of the reference to the object.

So if you have doSomething(foo) and public void doSomething(Foo foo) { .. } the two Foos have copied references that point to the same objects.

Naturally, passing by value a reference to an object looks very much like (and is indistinguishable in practice from) passing an object by reference.

Solution 5

This will give you some insights of how Java really works to the point that in your next discussion about Java passing by reference or passing by value you'll just smile :-)

Step one please erase from your mind that word that starts with 'p' "_ _ _ _ _ _ _", especially if you come from other programming languages. Java and 'p' cannot be written in the same book, forum, or even txt.

Step two remember that when you pass an Object into a method you're passing the Object reference and not the Object itself.

  • Student: Master, does this mean that Java is pass-by-reference?
  • Master: Grasshopper, No.

Now think of what an Object's reference/variable does/is:

  1. A variable holds the bits that tell the JVM how to get to the referenced Object in memory (Heap).
  2. When passing arguments to a method you ARE NOT passing the reference variable, but a copy of the bits in the reference variable. Something like this: 3bad086a. 3bad086a represents a way to get to the passed object.
  3. So you're just passing 3bad086a that it's the value of the reference.
  4. You're passing the value of the reference and not the reference itself (and not the object).
  5. This value is actually COPIED and given to the method.

In the following (please don't try to compile/execute this...):

1. Person person;
2. person = new Person("Tom");
3. changeName(person);
4.
5. //I didn't use Person person below as an argument to be nice
6. static void changeName(Person anotherReferenceToTheSamePersonObject) {
7.     anotherReferenceToTheSamePersonObject.setName("Jerry");
8. }

What happens?

  • The variable person is created in line #1 and it's null at the beginning.
  • A new Person Object is created in line #2, stored in memory, and the variable person is given the reference to the Person object. That is, its address. Let's say 3bad086a.
  • The variable person holding the address of the Object is passed to the function in line #3.
  • In line #4 you can listen to the sound of silence
  • Check the comment on line #5
  • A method local variable -anotherReferenceToTheSamePersonObject- is created and then comes the magic in line #6:
    • The variable/reference person is copied bit-by-bit and passed to anotherReferenceToTheSamePersonObject inside the function.
    • No new instances of Person are created.
    • Both "person" and "anotherReferenceToTheSamePersonObject" hold the same value of 3bad086a.
    • Don't try this but person==anotherReferenceToTheSamePersonObject would be true.
    • Both variables have IDENTICAL COPIES of the reference and they both refer to the same Person Object, the SAME Object on the Heap and NOT A COPY.

A picture is worth a thousand words:

Pass by Value

Note that the anotherReferenceToTheSamePersonObject arrows is directed towards the Object and not towards the variable person!

If you didn't get it then just trust me and remember that it's better to say that Java is pass by value. Well, pass by reference value. Oh well, even better is pass-by-copy-of-the-variable-value! ;)

Now feel free to hate me but note that given this there is no difference between passing primitive data types and Objects when talking about method arguments.

You always pass a copy of the bits of the value of the reference!

  • If it's a primitive data type these bits will contain the value of the primitive data type itself.
  • If it's an Object the bits will contain the value of the address that tells the JVM how to get to the Object.

Java is pass-by-value because inside a method you can modify the referenced Object as much as you want but no matter how hard you try you'll never be able to modify the passed variable that will keep referencing (not p _ _ _ _ _ _ _) the same Object no matter what!


The changeName function above will never be able to modify the actual content (the bit values) of the passed reference. In other word changeName cannot make Person person refer to another Object.


Of course you can cut it short and just say that Java is pass-by-value!

Share:
2,420,746
user4315
Author by

user4315

Updated on May 10, 2022

Comments

  • user4315
    user4315 about 2 years

    I always thought Java uses pass-by-reference.

    However, I've seen a blog post that claims that Java uses pass-by-value.

    I don't think I understand the distinction they're making.

    What is the explanation?

    • jlau
      jlau almost 4 years
      We would more commonly say that a variable "passed-by-reference" can be mutated. The term appears in textbooks because language theorists needed a way to distinguish how you treat primitive data types (int, bool, byte) from complex and structured objects (array, streams, class) -- that is to say, those of possibly unbounded memory allocation.
    • Tobias
      Tobias over 3 years
      I want to note that you do not have to think about this in most cases. I programmed java for many years until i learned c++. Until this point in time i had no clue what pass-by-reference and pass-by-value are. The intuitive solution always worked for me, which is why java is one of the best languages for beginners. So if you currently are worried, if your function needs a reference or a value, just pass it as it is and you will be fine.
    • The Student
      The Student over 3 years
      Java pass the reference by value.
    • Ozair Kafray
      Ozair Kafray over 3 years
      Putting it very concisely, this confusion arises because in Java all non-primitive data types are handled/accessed by references. However, passing is always be value. So for all non-primitive types reference is passed by its value. All primitive types are also passed by value.
    • Natasha Kurian
      Natasha Kurian over 3 years
    • aderchox
      aderchox about 3 years
      It's the difference between foo.bar(sth) and foo = sth. In the 1st one, the object is being changed using the variable that is pointing to it, and the variable itself that is pointing to the object has not been changed. In the 2nd one however, the variable itself that used to point to the object has changed and is now pointing to another object. If you have a C++ background: A pointer is a variable that holds a memory address, while a reference has the same memory address as the item it references. In Java indeed, a pointer is passed by value, but Javaistas happen to call it a reference!
    • hippietrail
      hippietrail almost 3 years
      What would it mean then for some language to pass a reference not by value? Passing pointers to pointers? Are there languages that do such a thing? Don't languages such as C/C++ also pass references and pointers by value??
    • Sam Ginrich
      Sam Ginrich over 2 years
      As Java is an object oriented language and objects are passed by reference, according long time established semantics "modifications of the object apply to the original", it's not clear, how this "pass-by-value"-nonsense could become that famous.
    • Dalija Prasnikar
      Dalija Prasnikar over 2 years
      @SamGinrich Java is always pass-by-value. If you don't understand this basic concept, which is nowhere near an "nonsense" as you call it, I suggest you read the most upvoted answers here until you understand why.
    • Sam Ginrich
      Sam Ginrich over 2 years
      @Dalija Prasnikar There are very few displays escaping the artificial twist of terms. If you want educate yourself see here: baeldung.com/java-pass-by-value-or-pass-by-reference
    • VeKe
      VeKe about 2 years
      for those who like video explanation youtu.be/fL-nXdKWwOg
  • user207421
    user207421 almost 11 years
    There is no such thing as a 'constant referenece' in Java unless the programmer specifies 'finally'.
  • fatma.ekici
    fatma.ekici over 10 years
    What I meant by constant reference is, there is no way to change the reference itself by saying new MyClass() in a function. If I put it correctly, there object references are passed by value which means a copy of the reference is passed so you can change the data where that reference refers to but you can not change it with new operator and allocate a new object.
  • user207421
    user207421 over 9 years
    So fix your answer. If it was a constant you couldn't reassign it inside the called method, and you can, unless you specify final.
  • mrres1
    mrres1 over 9 years
    You can only define one class per file. This is not including nested and inner classes. Considering this will be something a new programmer will be reading, you should explain this to the user; allowing them to duplicate the code on their machine.
  • MrBackend
    MrBackend about 9 years
    @mrres1 Not entirely correct. You can define only one public top-level class/interface per file. Supporting several classes per file is a remnant from the first Java version, which didn't have nested classes, but it is still supported, though often frowned upon.
  • Kachna
    Kachna about 8 years
    in java we can do: someArray = InitArray(someArray) assuming we have this: static int [] InitArray( int[] arr){ ... return ...}
  • bvdb
    bvdb about 8 years
    You are correct. That's a possible alternative for a simple pass-by-reference. But pass-by-reference can do more powerful things. e.g. it could assign multiple values: e.g. int[] array1; int[] array2; InnitArrays(out array1, out array2); assuming that you create a method static void InitArray(out int[] a1, out int[] a2){...}
  • user207421
    user207421 almost 8 years
    Java has not redefined those terms. Nobody has. It has merely avoided the C term 'pointer'.
  • matt
    matt almost 8 years
    Is there an issue in your c++ version where your risking a segfault when Foo(99) goes out of scope but you reference it in your main method?
  • Ravi Sanwal
    Ravi Sanwal almost 8 years
    Indeed. Ah comes from using java for 10 years. But the idea still holds. And I fixed it now.
  • matt
    matt almost 8 years
    I think the previous was better because it would compile. I was just curious about the behavior, sorry about that.
  • Cdaragorn
    Cdaragorn over 7 years
    Those terms existed long before Java or C. Pointer was only ever a method for implementing one of them. If you accept Java's definition for them, then they become meaningless because by that definition, every language ever created is only Pass by Value.
  • Mox
    Mox over 7 years
    This actually doesn't explain anything in regards to potential by ref/by val property of Java.
  • Loduwijk
    Loduwijk almost 7 years
    You might want to clarify your last sentence. My first reaction to "passing the values only and not pointers..." is that your Java implementation probably does exactly that, passes a pointer. The fact that you cannot dereference that pointer seems irrelevant.
  • Loduwijk
    Loduwijk almost 7 years
    This answer only helps for those coming from C++ background who are willing to define "reference" the way you have, according to C++'s definition. That is not always the case.
  • user207421
    user207421 over 6 years
    'Pass its inner value' is meaningless.
  • Khaled.K
    Khaled.K over 6 years
    @EJP thanks for the note, excuse my bad English from 2013, I've edited the whole thing, if you see a better wording, you may suggest or edit
  • Admin
    Admin over 6 years
    i would like to add one thing.if you have changed the name of cat instead of creating a new one, it will reflect in the memory even after the method returns
  • Gray
    Gray over 6 years
    This is very misleading. You certainly can change the value of an argument from within a method.
  • Dennis
    Dennis over 5 years
    I'm not sure it's technically correct to mention that copies are made for primitive types. Primitive types are immutable which is why they cannot be modified inside a method they are passed to. The difference is negligible for things like numbers, but there is an important difference for potentially large strings.
  • Torben
    Torben over 5 years
    This answer is completely incorrect and only creates confusion. Java is a pure pass-by-value language. What confuses you is that the value can be a pointer to an object. Pass-by-reference means one would be able to change the identity of an object at the caller's side. E.g. assigning a new object to a method parameter would also affect the pointer that was passed in the code that called the method.
  • nasch
    nasch over 5 years
    @Dennis Strings are not primitives, they're objects.
  • Sanjeev
    Sanjeev over 5 years
    It's not about what's "In your book." "Pass by reference" and "Pass by value" are industry standard terms which have very specific definitions. By those definitions Java is "Pass by value" without exceptions.
  • AutomatedMike
    AutomatedMike about 5 years
    Describing java as "pass-by-value" is highly misleading. For non-primitive types Java uses "pass by value of the reference". "Pass by value" implies the value is copied when passed to a method. It is not, the reference is copied.
  • AndrewF
    AndrewF over 4 years
    "Passing an object" is not a valid operation in Java. You pass a reference to an object. Doing so is not called "passing by reference". It is called "passing by value". The reference passed is a value, which is copied to a new place on the stack for the method to use, just like any primitive value.
  • Sanjeev
    Sanjeev about 4 years
    Object references (i.e. pointers) are passed by value and primitives are also passed by value. Meaning everything is always passed by value. I think the operative term here is Pass-by-value.
  • Mr.Robot
    Mr.Robot about 4 years
    I think Java Language Architect, who is leading Project Amber and Project Valhalla is a credible source to claim that it is not pass by value.
  • Sanjeev
    Sanjeev about 4 years
    First, I don't think he's more credible than James Gosling, the creator of Java who clearly state in his book, "THE Java Programming Language", that Java is indeed Pass-by-value (Chapter 2, section 2.6.5). Second, although Goetz says it's neither PBV or PBR, he then goes on to say that references are PASSED BY VALUE, thereby contradicting himself. If you know Java, you also know that primitives are also PASSED BY VALUE. Since everything in Java is passed by value, Java is a PASS BY VALUE language.
  • Sanjeev
    Sanjeev about 4 years
    Other sources who are way more credible than Goetz are Aho, Lam, Sethi, and Ullman who are well known for their book "Compilers: Principles, Techniques, and Tools", the standard college text book for compiler construction. The 2nd eddition section 1.6.6 of this book also states that Java is Pass-by-value.
  • Stephen C
    Stephen C about 4 years
    And the most relevant reference of all is the Java Language Specification which states "The effect of this is to assign the argument values to corresponding freshly created parameter variables of the method". (15.12.4.5). Note that it is avoiding the terminological confusion by not saying "pass by ..." at all. (FWIW, I disagree with the Goetz's characterization of "pass by value" and "pass references by value" as being semantically different. And I agree that he is contradicting himself.)
  • Talijanac
    Talijanac almost 4 years
    This is just wrong. What Java calls "reference" C++ calls "pointer". What C++ calls "reference" does not exist in Java. C++ reference is pointer like type but with global scope. When you change a C++ reference all occurrences of that references are changed, both in called function but also in a calling function. Java can't do that. Java is strictly pass by value, and changes to java references are strictly local. Java called function can't change reference value of calling function. You can emulate C++ reference by using wrapper objects like AtomicReference.
  • Dude156
    Dude156 over 3 years
    Such an awesome answer that even a fool like myself was able to understand. I would add also amend that "pass by value" literally means that the literal value in the stack is passed.
  • Paul de Vrieze
    Paul de Vrieze over 3 years
    C++ references have nothing to do with scopes. In implementation they are like pointers that are not allowed to have null values. The main difference beyond that is that syntactically they behave as aliases of the referenced data. In Java references work almost the same way, but have special rules that allow for: comparison with null and other reference values (using the == operator). C++ is also pass by value, although that value could be a pointer/reference to the reference.
  • Talijanac
    Talijanac over 3 years
    Changes to C++ references made by called method are also visible by calling method. That doesn't exist in Java and it is not a pointer like behaviour. In Java and C changes to pointer values are local only. I don't know how to properly call to this kind behaviour but it is somewhat similar to "outer scope" of some scripting languages.
  • Talijanac
    Talijanac over 3 years
    For example of proper pass-by-reference see swap program here: geeksforgeeks.org/references-in-c It is not possible to write swap method in Java with same side-effects. There is "quality" (a behaviour of language operators) to C++ references which does not exists in Java references or C pointers.
  • dbrewster
    dbrewster over 3 years
    so what happens to "Fifi" in the 1st example? Does it cease to exist, was it never created, or does it exist in the heap but without a reference variable in the stack?
  • TMOTTM
    TMOTTM over 3 years
    What do you mean by the last sentence but it is not possible to change the value of the variable aDog itself.?
  • user36800
    user36800 over 3 years
    To me, saying that an object's reference is passed by value is the same as saying that the object is passed by reference. I'm a Java novice, but I presume that (in contrast) primitive data is pass by value.
  • Brian Goetz
    Brian Goetz over 3 years
    JVMS 2.2 makes this pretty clear: There are ... two kinds of values that can be stored in variables, passed as arguments, returned by methods, and operated upon: primitive values and reference values." Object references are values. Everything is passed by value.
  • Mohith7548
    Mohith7548 over 3 years
    Running this program should help anyone understand this concept. pastebin.com/VEc8NQcX
  • Chrispher
    Chrispher over 3 years
    In this example you've not copied the Student object, so I think saying "passing a copy of the value also changes the real value of the object" is misleading. The thing that you are copying, and passing-by-value, is the reference to the object. The object stays living on the heap, and there's just one of them. That's why when you use the new reference to mutate the object, you're mutating it for everyone else that has a reference to the object. There's only one object. When the argument of the function is a primitive type, not a reference to an object, it is also copied.
  • AFP_555
    AFP_555 over 3 years
    This is the only answer that made sense so far. The objects are not passed as pure values because they aren't copied like in the C++ pass-by-value way.
  • Solubris
    Solubris over 3 years
    This shows that java is not pass by value as it doesn't copy the whole object onto the stack like C++ does, as shown in the example above - ..., Dog obj,...
  • Solubris
    Solubris over 3 years
    C++ has true pass by value where it copies all the fields of the object onto the stack. Java doesn't do this so its not pass by value..
  • mekanik
    mekanik over 3 years
    No, Java passes references by value. That's why when you overwrite objPtr in the java example, the original Dog object doesn't change. But if modify the object being pointed to by objPtr, it does.
  • dan carter
    dan carter over 3 years
    Java always passes arguments by value, but what you are passing by value is a reference to an object, not a copy of the object. Simple eh?
  • user21820
    user21820 over 3 years
    @user36800: You're wrong. Did you work through the example with Fifi and look carefully through the results? Check that indeed foo(aDog); did not change aDog despite foo overwriting the value of d, showing that indeed all inputs to a function are passed by value.
  • user36800
    user36800 over 3 years
    @user21820: Yes, I did work through the examples and they both made sense to me. I made two statements in my previous comment. If you can specify which one you disagree with, I can try to better understand your last comment. Thanks.
  • user21820
    user21820 over 3 years
    @user36800: Well, both statements are wrong. To pass an object by reference would mean that if the function modifies the variable then it modifies the object itself. That is not what happens in Java; objects cannot be passed by reference, but instead one can only pass references as inputs to a function, and when a function performs d = new Dog("Fifi"); it overwrites the input variable d, which stores a reference but is not 'the object passed by reference'. Contrast with &d in the function signature in C, which would be pass-by-reference. [cont]
  • user21820
    user21820 over 3 years
    That was for your first statement. Your second statement is also wrong because everything is passed by value in Java. There is absolutely no difference between object references and primitive data types, except that the operations you are allowed to perform on them differ.
  • user36800
    user36800 over 3 years
    Ah, I see. Thanks for clarifying that. I was just thinking in a gross manner, i.e., equating passing by reference as not creating a new object because pointers are used behinds the scenes, and the pointers are automatically dereferenced when the variable is used. It would be so much clearer if pointers were explicitly used. However, the maxim that all Java objects are handled by reference helps.
  • ghilesZ
    ghilesZ over 3 years
    @dbrewster i'm sorry but ... "Fifi" is not among us anymore
  • georgiana_e
    georgiana_e about 3 years
  • ebresie
    ebresie about 3 years
    Minor clarification question on the above example, so when creating new Dog at BBB at address 72, does this imply upon return the created Dog at 72 and it’s value is lost and reverts back to 42?
  • Ravikumar R
    Ravikumar R about 3 years
  • Scott Stanchfield
    Scott Stanchfield about 3 years
    @ebresie Mostly yes (I'll clarify the "mostly" in a moment). The only pointer to the new dog at 74 (I assume you meant 74 rather than 72) is the parameter to the foo function. When foo returns, all of its parameters are popped off the stack, so nothing is left pointing to 72 and it can be garbage collected. I say "mostly" as there is no "revert" happening; the pointer myDog in the caller was pointing to 42 all along and never changed, no matter what happened in the function, hence, no "revert".
  • David Schwartz
    David Schwartz about 3 years
    In both languages, "pass by value" means passing the value of the object if it's an object. In no case does it mean passing the address of the value. There is no difference in terminology. There is no case where we call something pass by value and changing the value in the function called changes the value in the caller. If you call a function like this foo(bar) in java, the value of bar never changes -- if bar is a reference to an object, its value is the identity of the object it references and no matter what the function does, it still references the same object in the caller.
  • v010dya
    v010dya about 3 years
    To understand this, one needs to understand that unlike in many languages in Java an array is an Object itself.
  • v010dya
    v010dya about 3 years
    One of the most complete answers is bumped to the bottom. Your #3 describes the situation in Java the best.
  • Joachim Sauer
    Joachim Sauer about 3 years
    I agree with David Schwartz: there is actually no difference in terminology. The big difference between Java and C++ is that in Java a "value" can never be a whole object. It's always either a reference or a primitive value. You simply can't pass a whole object in Java at all.
  • siegi
    siegi about 3 years
    Note: The safely in "now we can edit internalObject safely" depends on the implementation of the clone() method (i.e. "deep" or "shallow") and how far down the object tree your edits have an impact. For this simple example it is correct though.
  • redd77
    redd77 about 3 years
    So what is the difference between an "object reference" and the "value of an Object reference" then .
  • NiharGht
    NiharGht almost 3 years
    "However, you cannot change where that pointer points." -> Shouldnt it be "However, you cannot change where that pointer points in some other method."
  • Sanjeev
    Sanjeev almost 3 years
    @redd77 when you pass the "value" you are not passing the actual variable, only the value it contains. Meaning you're making a copy of the values and passing in the copy. An object reference (i.e. a pointer) is a variable containing the physical address of the memory which contains the object. The values of an object reference is a copy of that address. Languages which support pass by reference allow you to pass the actual variable and not just a copy so that changing it in the function (like setting it to null) also changes it for the caller.
  • Scott Stanchfield
    Scott Stanchfield almost 3 years
    @NiharGht Good point - I've clarified it (please comment again if it's still not clear)
  • Admin
    Admin almost 3 years
    @redd77 Only difference is that assigning to a "value of Object reference" does not touch the object. In that way it's like a C/C++ pointer.
  • Jonathan
    Jonathan almost 3 years
    Java does not act exactly like C. If you pass a pointer to a function in C and modify where that pointer points to, the effect of reassigning that pointer is seen at the call sight, not just within the scope of the call. Seeking this behavior out of the languages is the purpose of the const keyword. Please stop saying java is just like C, because it's in many many fundamental ways entirely NOT c (or c++) and all you're doing is confusing people that do know C (or C++) and are trying to get a working overview of java. See: courses.washington.edu/css342/zander/css332/passby.html
  • Scott Stanchfield
    Scott Stanchfield almost 3 years
    @Jonathan That link is C++, not C. C does not work that way. C is strictly pass by value, just like Java. If you pass a pointer to something, the pointer is the value that you can follow. You cannot change the pointer but can follow it and change the value it points to. If you re-point it, the caller does not see the change. In C++, you can pass a reference to something (seen in that page you reference as int&), which is similar to an alias; if you change it in a function/method it does actually change the object/primitive/pointer passed as an argument.
  • Excessstone
    Excessstone almost 3 years
    I tried this: <br /> File file = new File("C:/"); changeFile(file); System.out.println(file.getAbsolutePath()); } public static void changeFile(File f) { f = new File("D:/"); }`
  • Jonathan
    Jonathan almost 3 years
    @ScottStanchfield Does C have pointers? Java does not! Give this to your favorite c compiler and test the output. C has reference semantics, Java does not. You can't swap values from within a function in java and have it reflected at the call site. pastebin.com/U9QBFrwL
  • Scott Stanchfield
    Scott Stanchfield almost 3 years
    @Jonathan That's similar to this in java: pastebin.com/1tZsVVRw. The * is creating a pointer to the argument (which itself could be a pointer), which is similar to creating a "bucket" to hold the value - Java doesn't allow the C syntax and pointers to be created to manipulate existing data, but that doesn't mean Java doesn't have pointers (note that C still doesn't have reference semantics either...). Pascal, for example, uses ^ in a similar way to C's * - just because languages have different syntaxes does not mean they don't have the same concepts (such as pointers).
  • Jonathan
    Jonathan almost 3 years
    @ScottStanchfield C indeed has reference semantics, it's achieved using pointers, exactly like what I put in the Pastebin. So what does the address-of operator do in C? HMM? C has reference semantics. It always HAS had reference semantics. I'm sure you've got linguistics and semantics confused here. I'm not talking about the grammar, it can be a *, a ^, or a type&, the meaning is (mostly) all the same, the caviates being the rules of each langauges typesystem, which AGAIN, is another reason that JAVA IS NOT LIKE C
  • Scott Stanchfield
    Scott Stanchfield almost 3 years
    @Jonathan No. C only has pass-by-value (in your example you're passing the value of a pointer - see stackoverflow.com/questions/2229498/passing-by-reference-in-‌​c for a good discussion, esp the answer by Ely). Pass-by-reference has a very specific meaning in compiler parlance. FYI - I'm a compiler guy and was on the ANSI C++ 98 committee... C++ has reference semantics; C does not. The difference is whether the actual argument can be modified. When you pass in &i the actual argument value is the address of i, not a reference to i.
  • Scott Stanchfield
    Scott Stanchfield almost 3 years
    @Jonathan (Submitted too early and cannot edit) Inside the method you're not changing that address; you're following that address and changing the data residing there.
  • Jonathan
    Jonathan almost 3 years
    @ScottStanchfield You obviously don't understand pointers and references. The only difference between a pointer and a reference is that a pointer's type can be cast away. A reference IS a pointer with type safety. A pointer is simply a variable that holds the address of something else. Guess what a reference is? A variable that holds the address of something else. A reference isn't an instance of that something else. A reference is basically syntactic sugar for pointers with type safety. If a language has pointers, it has reference semantics.
  • Scott Stanchfield
    Scott Stanchfield almost 3 years
    @Jonathan You're confusing 'reference' as a type with 'pass-by-reference'. There's a huge difference between "pass by a value by reference" (reference semantics) and "pass a pointer/reference by value" (value semantics). It's all about how you define the FORMAL parameters of a function/method, not the ACTUAL parameters. If the language gives you syntax to automatically de-reference values in the FORMAL parameters (the function/method signature), it has reference semantics. Creating a pointer to something in the ACTUAL arguments (the call site) is still only passing a value.
  • Scott Stanchfield
    Scott Stanchfield almost 3 years
    @Jonathan C and Java are strictly pass-by-value. You can SIMULATE pass-by-reference in them by doing something both inside the function/method AND at the call site (for example, in C, using & at the call site and * inside the function/method, or in Java, wrapping the value at the call site and working inside the wrapper inside the function/method), but that's still pass-by-value. Pass-by-reference is a specific compiler term for logically aliasing a variable passed into a function by ONLY specifying this behavior in the FORMAL parameters, not at the call site.
  • Magne
    Magne over 2 years
    Maybe "pass-by-sharing" is even more precise and disambiguated? en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing Since it incorporates the reason why people resort to calling it "pass-by-reference" in the first place: the danger that functions are able to mutate objects passed in. They don't want to say "pass-by-value" as it implies copying and thus safety from mutating what's passed in.
  • Scott Stanchfield
    Scott Stanchfield over 2 years
    @Magne I've never understood why Liskov felt it necessary to coin "call by sharing"; it's just passing the address/reference by value and following it in the function, and causes confusion. Some people didn't want to use the perfectly-correct word "pointer" (even though they used it in "NullPointerException" in Java...) There's nothing about the definition of "pointer" that says it must be implemented directly as a memory address (though it's easiest to think of it that way) - it's just indirect access to data. You don't pass the object in Java; you pass a pointer to an object.
  • Magne
    Magne over 2 years
    I think it is because people are not "pointer-oriented", but "value/object-oriented". The pointer is invisible to them. As you said "The mistake they make is in the definition of Dog d; itself. When you write that definition, you are defining a pointer to a Dog object, not a Dog object itself.". Maybe because many languages make it invisible (like Java here), but it's common to humans to "mistake the map for the territory" in real life as well; in effect treating the symbol as the referent). "Call by sharing" takes this cognitive artifact into account, so the intention is clearer, to most.
  • Scott Stanchfield
    Scott Stanchfield over 2 years
    @Magne Pointers are a key concept in programming; trying to word one's way around them is a sure way to cause more confusion, not less.
  • Magne
    Magne over 2 years
    I can see how that might be the case, when coming to Java from a lower level language where you do have to deal with pointers. But coming from a higher level language, or from no previous language, it’s the other way around. Esp. if working in a language where you don’t directly deal with pointers.
  • Sam Ginrich
    Sam Ginrich over 2 years
    Not half the answer.
  • the_prole
    the_prole over 2 years
    @Sanjeev that finally made sense. Pass by reference or by pointer means to pass the reference itself, and not a copy of it. Passing a reference in a pass by value only language, is not pass by reference, it is pass by value.
  • Joop Eggen
    Joop Eggen over 2 years
    The operative implication: f(x) (passing a variable) will never assign to x itself. There is no such thing as a variable address (alias) passed. A solid language design decision.
  • Michael
    Michael over 2 years
    It's still pass-by-value even if the value itself is a reference. The argument is copied and reassigning it doesn't affect anything outside the called function - this is the key difference between pass-by-value/reference.
  • Sanjeev
    Sanjeev over 2 years
    @the_prole Yes, but just to be clear, the word "Reference" has a different meaning than as used by Java. Therefore pass by reference does not mean pass by pointer (although under-the-hood, pointers could be used to handle PBR, but not necessarily). It just so happens that java uses the same word for pointers. Please see my post for details ==>> stackoverflow.com/questions/40480/…
  • Sam Ginrich
    Sam Ginrich over 2 years
    We agree, that references and objects are two pairs of shoes
  • Dale Stanbrough
    Dale Stanbrough over 2 years
    "In C++, Ada, Pascal and other languages that support pass-by-reference, you can actually change the variable that was passed." Ada doesn't really depend on the actual passing mechanism (for most things) as it has parameter passing modes which have specific semantics. The modes are "in" (read only), "in out" (initial value passed in, modifiable) and "out" (initial value not necessarily passed in, can be updated). For scalars the mechanism for "in out" is copy in/copy out which is much more cache friendly than C's pass by reference.
  • Scott Stanchfield
    Scott Stanchfield over 2 years
    @DaleStanbrough Didn't know about the cache-friendliness there for scalars; cool. Not sure what you mean by "Ada doesn't really depend on the actual passing mechanism (for most things) as it has parameter passing modes which have specific semantics." I was thinking about "in"/"out"/"in out" when I mentioned Ada (with "out" specifying update of a passed variable). Been a while since I've programmed in Ada, though, so I may be fuzzy on some of the ways terminology is used by the language nowadays
  • Dale Stanbrough
    Dale Stanbrough over 2 years
    "It doesn't depend" mainly meant that when designing in Ada you think about the modes (information direction flow) rather than the mechanism - which is such a great way to design subprograms. Ada takes care of the rest.
  • h0r53
    h0r53 over 2 years
    This seems like the correct answer to me. Why are people so caught up on the technicalities of pass-by-object-reference versus pass-by-reference? If you pass a non-primitive variable to a function, modifications to that variable within the function affect the variable outside of the function. That is pretty much the same behavior as pass-by-reference. "It's still pass-by-value even if the value itself is a reference" - umm, okay, but if the value is a reference then you are passing a reference. Terminology aside, passing objects as arguments can affect the object outside of the function.
  • h0r53
    h0r53 over 2 years
    "Since we said the value of t was 0x100234, both t and f will have the same value and hence they will point to the same object." - That doesn't sound right. Creating a copy of an object should not mean the copy and the original both point to the same object. This smells like pass-by-reference, or minimally, pass-by-object-reference
  • Sam Ginrich
    Sam Ginrich over 2 years
    "Object not by Reference", really?
  • Sam Ginrich
    Sam Ginrich over 2 years
    :) another term, feeding the confusion around the Java Island, just because it's politically incorrect to say "An Object is passed by reference, according to what we find on the stack".
  • Sam Ginrich
    Sam Ginrich over 2 years
    Yes, a object reference is technically a handle, not yet the address, and so even a step further from "by value".
  • Sam Ginrich
    Sam Ginrich over 2 years
  • Sam Ginrich
    Sam Ginrich over 2 years
    No, idea how to unwind that knot: You pass a object reference and say the object is passed by value. :(
  • Sam Ginrich
    Sam Ginrich over 2 years
    What, if "passing by reference" meant, that you can modify the passed object inside the called method, affecting the object existing outside the method?
  • Sam Ginrich
    Sam Ginrich over 2 years
    And to where is Java passed?
  • Sam Ginrich
    Sam Ginrich over 2 years
    Objects are passed by reference. :)
  • Sam Ginrich
    Sam Ginrich over 2 years
    user207421 certainly discussed terms have existed 50 before Java and we never heard something equivalent stupid like "passing a pointer by value", even if entire Java community thinks, it was the gold standard of terminology.
  • Sam Ginrich
    Sam Ginrich over 2 years
    Thought, Java is a programming language ;)
  • Sam Ginrich
    Sam Ginrich over 2 years
    "What is the outcome?" - Guess a memory leak
  • Sam Ginrich
    Sam Ginrich over 2 years
    Sure, the confusion comes from the fact, that outside the Java community there is other semantics and verbose "Java is not God"
  • Sam Ginrich
    Sam Ginrich over 2 years
    Every time you pas an object, it is passed by reference, cause that is what you find on the stack: a Reference
  • Sam Ginrich
    Sam Ginrich over 2 years
    The object can be modified because it is passed by it's reference ;)
  • Priyanka
    Priyanka over 2 years
    Hi what is the return type of swap method.?
  • Sam Ginrich
    Sam Ginrich over 2 years
    Not relevant for the semantics: Guess, all Java implementations use two levels of indirection, i.e. a reference is a kind of handle, not yet the object address, which may change by garbage collection.
  • jmarkmurphy
    jmarkmurphy over 2 years
    @akki2346 because when you pass an object, you are not making a copy of the whole object and passing that, you are passing the value of the reference. There can be multiple references to the same object in Java. When you pass an object to a function, one of those references to the object is on the stack.
  • jmarkmurphy
    jmarkmurphy over 2 years
    @SamGinrich I don't know why you insist on going back to C++ to understand Java. They are not the same. Ok, do this. Create for me a swap function defined like this swap(String str1, String str2). It should swap the two objects str1 and str2. This will be a simple exercise if Java uses pass by reference semantics for objects.
  • Mehdi Monzavi
    Mehdi Monzavi over 2 years
    so cute, and the best answer
  • Sam Ginrich
    Sam Ginrich over 2 years
    Guess, you are the first human being, who ever managed to "pass an object by value" in Java, tend to call you the "Neil Armstrong of Java", henceforth ;)
  • pek
    pek over 2 years
    @Priyanka Ha! So many years later and you are the first to catch that! It's void.
  • jmarkmurphy
    jmarkmurphy over 2 years
    No it's not. Pass by reference/pass by value is all about what is put onto the call stack. In Java, it is the VALUE of the reference, and the receiver understands it as the VALUE of the reference to the object. If we were using pass by reference semantics, things that are represented by a reference would have the address of the reference rather than the value of the reference put on the stack. The receiver would then understand this and dereference the the parameter, and would then operate on the passed object itself, not a copy of it. Did you make that swap function yet?
  • Johnes
    Johnes over 2 years
    Not a useful explanation.
  • Admin
    Admin over 2 years
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
  • Sam Ginrich
    Sam Ginrich over 2 years
    Option 3: You think of a reference to a replicated object? Think the mess is, that many responses refuse to consider objects, at all and that modes of passing entities were used long before Java.
  • Alexander Kalinowski
    Alexander Kalinowski over 2 years
    With #3, I am thinking of what Java is doing. In Java, when your method gets passed an instance Foo foo and you assign foo = new FancyFooSubclass();, these changes do not propagate outside. After your method returns, foo still points to the original Foo object. This is not necessarily the case with, say, C++ pointers passed to a method. Which is why the original question poses a false dichotomy. And answers with hundreds of upvotes (!) do not clear up that misunderstanding, exacerbating the confusing state of things for Junior Developers.
  • Sam Ginrich
    Sam Ginrich over 2 years
    Assigning parameter reference in Java is same semantic as assigning a parameter pointer in C (excluding C++-pointer reference, "T*&" for some type T). Certainly agree with you, majority not necessarily meets reason. Dichotomy exists after grammar. Under the question is a comment with reasonable link, getting the things straight -> baeldung.com/java-pass-by-value-or-pass-by-reference For further entertainment you can follow my last response to the thread :)
  • Alexander Kalinowski
    Alexander Kalinowski over 2 years
    My problem is this: What's a Junior Developer to think who reads this thread and then reads, for example, in "More Effective C#" by Bill Wagner that in Java all parameters are passed by reference? It's going to make the confusion complete. The false dichotomy regarding the treatment of parameters follows an actual dichotomy regarding the type of parameters: value (aka copies of the original data) or reference (aka the memory address of the original data). Making the switch from types to treatment (CbV doesn't change the original, CbR does) is awful because treatment is not a binary choice.
  • Sam Ginrich
    Sam Ginrich over 2 years
    Well, don't agree with Bill Wagner, as primitive types as int, char, float are passed by value; there is actually an instance of that type on the stack. It's unacceptable for the public audience to have these loud statements uncommented, nor that the author would deliver an "errata". Wagner is not an exception, and it's not just a problem for Jr. Devleopers: The spirit of time in that manner nurses a lot of junk -science, - journalism and -politics and produces lots of people totally locked towards other views.
  • Sam Ginrich
    Sam Ginrich over 2 years
    ... Think you did it the traceable way: Defining terms, list cases and conclude on that basis. So, someone coming to a different result should find the cause in different terms or scope. The problem are people not following such protocol and still claiming correctness. Summary: In scope of ´primitive values and objects´ the modes of call become immediately clear.
  • Alexander Kalinowski
    Alexander Kalinowski over 2 years
    For transparency's sake, full Wagner quote: "The distinction between value types and reference types was added to .NET and C# because of common problems that occurred in C++ and Java. In C++, all parameters and return values were passed by value. [...] The Java language responded by more or less removing value types from the language. All user-defined types are reference types. In the Java language, all parameters and return values are passed by reference."
  • Alexander Kalinowski
    Alexander Kalinowski over 2 years
    Personally, I don't have a skin in the game. I have a weak preference for calling passing value types as CbV and reference types as CbR. The interpretation of Java developers. otoh, is detached from the actual words used in CbV and CbR. But ultimately which expressions we use is not as important as having enough expressions to express ourselves. Passing parameters certainly has more divergent properties than can be expressed in two terms: docs.microsoft.com/en-us/dotnet/visual-basic/programming-gui‌​de/…
  • Amir
    Amir over 2 years
    So every thing in the world is passed by value. for example in C we always passed by value even if we create a function by input pointer.
  • Amir
    Amir over 2 years
    i say it is wrong. in C void func(int *i); is a call by reference function. call by value means you can not change the value of original input. it this case you can implement func some thing like void func(int *i){int j = 5; i = &j;}. so if you say java is call by value you have to say every thing is call by value. cuz always new value copied to stack.
  • Scott Stanchfield
    Scott Stanchfield over 2 years
    @Amir Writing func(int *i) means you're passing a pointer value as the parameter (and would have to call it with func(&x). Note that the caller needs to do something special. That's still pass-by-value. Pass-by reference allows the function to state it can change the parameter value without the caller doing anything extra. C++ allows func(int &i) and you can call it directly with an int x variable like func(x). Pass-by-reference is a special construct in the language, and can be simulated in some value-only languages, but it's not true pass-by-reference. (You can't do either of these in Java)
  • Amir
    Amir over 2 years
    but tutorialspoint.com/cprogramming/… said it is call by reference. it is better clearly define what is call by reference and what is call by value. So it seems C and Assembly don't have call by reference.
  • Scott Stanchfield
    Scott Stanchfield over 2 years
    @Amir They're incorrect. C only supports value parameters. See stackoverflow.com/questions/2229498/passing-by-reference-in-‌​c for some good explanations, particularly the comment about "Illusion of pass-by-reference".
  • Scott Stanchfield
    Scott Stanchfield over 2 years
    @Amir The difference is that "pass by value" is just passing the result of the evaluated expression used as an argument in the function call. "Pass by reference" can be thought of the parameter being an alias for the variable passed in as an argument.
  • bwass31
    bwass31 over 2 years
    So basically we're passing the address and we reference that address in our method for example in c int test(int *a) { int b = *(a); return b;) ?
  • Sam Ginrich
    Sam Ginrich over 2 years
    Precisely, the war starts, when you want to say "an object is passed by reference"
  • Sam Ginrich
    Sam Ginrich over 2 years
    Half of the rent: "everything" is "objects" in your post.
  • Sam Ginrich
    Sam Ginrich over 2 years
    "The Java programming language does not pass objects by reference; it passes object references by value." I think this statement as a whole is wrong. Assume, you want to pass an object to a method ...
  • Sam Ginrich
    Sam Ginrich over 2 years
    So, when I want to pass an object to some method, I'm doomed, because an object is "not a value" :(
  • Sam Ginrich
    Sam Ginrich over 2 years
    Grammar: Is "pass-by-value" an object of a sentence?
  • Sam Ginrich
    Sam Ginrich over 2 years
    Finally, it comes down to that fact, that the term "value" was re-declared for Java, so a reference of an object is called value, instead of the object itself and on the same didactic level the use case "passing an object to a method" was declared politically incorrect. So one faces an artificial narrow language, that feeds the dogma.
  • Sanjeev
    Sanjeev over 2 years
    @SamGinrich, in this case you are passing a reference to that object. The object exists somewhere in memory. The reference (otherwise known as a pointer) is like a primitive (like a long) which holds the memory address of the object. What's passed into the method is actually a copy of the reference. Since you're passing a COPY of the reference, this is pass by value (i.e. you're passing the reference by value). If you were to set the copy to null inside the method, it would have no affect on the original. If this was pass by reference setting the copy to null would also set the original to nul
  • Sanjeev
    Sanjeev over 2 years
    @SamGinrich Have a look at my code example and the two diagrams I posted.
  • Sam Ginrich
    Sam Ginrich over 2 years
    Totally agree with your presentation. I doubt that Ken Arnold et al. are qualified to rename long time established concepts, where "passing an object reference" had been equivalent to "passing an object by reference", as you obviously work on shared objects and references for this purpose are invariant, in analogy to pointers. That's how I learned it at university. Now, in the use case "passing an object to some method" focusing on the technical aspect of the reference appears as artificial narrowing, not catching up on: "Does the called method work on the original object or a copy?"
  • Sanjeev
    Sanjeev over 2 years
    @SamGinrich If you look at the definition of pass-by-value, that's exactly what it boils down to - PBV = passing a copy. And if you look at the Java language definition, that's exactly what Java does. I've included excerpts from both "The dragon book" and the Java language specification (Edit 4). Also, Arnold and Gosling are both highly regarded computer scientists and the creators of Java. They are actually NOT renaming established concepts. If you look at the excerpts form their book (Edit 2), they are saying exactly the same as my post and it's consistent with established Computer Science.
  • Sanjeev
    Sanjeev over 2 years
    @h0r53 Why are people so caught up? Consistent definitions are import for effective communication. What C does, IS ALSO PASS BY VALUE. It's just the java calls its pointers "References". And that's where the confusion comes from. It's a different use of the word reference than in "pass-by-reference". Under the hood a "reference" in java is just a pointer, meaning it's a primitive which holds an address to the object in memory. Yes, you change the object in memory, but not the reference itself. So if you assign a different object or set it to null, the reference outside the function wont change
  • Sanjeev
    Sanjeev over 2 years
    @h0r53, I can see from your posts (which are great, btw) that you know C and C++. C does not offer Pass by Reference, but C++ actually does by way of allowing "reference parameters". When you declare a function with a header like , void foo(TreeClass& maple), the ampersand makes this a reference parameter (can't do that in C). Now, if you set maple to null inside the function, the change will also be reflected outside the method. Please see my post for details stackoverflow.com/questions/40480/…
  • Sam Ginrich
    Sam Ginrich over 2 years
    @Sanjeev For that matter, in C++ we have equivalence of parameters of type T& and T const* for some type variable T, which differs in the syntactic dereferentiation level, not in the use cases or requirements for associated objects in calling or called context. Also there is no need to twist these and everyone is able to understand this, if he is willing.
  • Sam Ginrich
    Sam Ginrich about 2 years
    @Amir think you are wrong on C. tutorialspoint.com/cprogramming/…
  • Sam Ginrich
    Sam Ginrich about 2 years
    Sure, and I explained, why I'm qualified to reject all of these, according to established Computer Science. And I well understand, that Java wants to have its island, probably driven by testosterone. ;) Terms were well defined and understood before Java, when there was no "look at the definition of some Java-Guru". tutorialspoint.com/cprogramming/…
  • Sanjeev
    Sanjeev about 2 years
    @SamGinrich These definitions existed BEFORE Java. They are not the definitions of "some Java-Guru". The "Dragon Book" existed BEFORE Java. Computer Science existed BEFORE Java. The link you posted completely missed the point of a swap test. In order for it to be valid you would need to swap the actual pointers, not what they point to. It's silly the take the word of some random guy who wrote a tutorial on the internet over people like Sethi, Ullman, Lam, and Aho. Also, Gosling is no just a "Guru". He's the creator of Java. I'm sure he's more qualified than anyone to comment on Java.
  • Sanjeev
    Sanjeev about 2 years
    @SamGinrich I don't doubt your qualification. But I have sourced six famous computer scientists with PhDs who are widely published to make my point. And not just any computer scientists. Gosling created Java. Sethi, Ullman, Lam, and Aho are the gods of compilers. They wrote the most widely used text book on compilers. You should look at the list of publications, accomplishments, and awards for these people. In response to that you have to give me something better than a nameless guy with a laptop who writes tutorials for a website.
  • Sam Ginrich
    Sam Ginrich about 2 years
    Think a Guru is someone who creates own rules. Now claiming these rules to be world formula, while the rest of the computer science community does not agree, leads to discussions like the one we have. What have you achieved, if for every statement of mine you refer precisely to the same people, which have called out for their arbitrary change of terms.
  • Sanjeev
    Sanjeev about 2 years
    @SamGinrich Here is the definition of Guru according to Merriam-Webster : merriam-webster.com/dictionary/guru. The assertion, "the rest of the computer science community does not agree", can you site any sources for this? As for, "the same people", if I really tried, I could get you more sources, but I'd have to go digging through text books. Can you at least supply one decent source? Until then here is IBMs documentation on C and C++ which show how of the two only C++ an accomplish this : ibm.com/docs/en/zos/2.4.0?topic=calls-pass-by-reference-c-on‌​ly. . .
  • Sanjeev
    Sanjeev about 2 years
    @SamGinrich . . . also here is a really good article by Scott Stanchfield of on why Java is pass-by-value only. It does a better job than me. javadude.com/articles/passbyvalue.htm
  • h0r53
    h0r53 about 2 years
    @Sanjeev I see your point and the subtle differences in reference v. object-reference are more clear to me. I was admittedly a bit frustrated when writing the prior response because it seemed like the issue was being unnecessarily convoluted with terminology. I just wanted a quick answer - "If I pass an object to a function, and change that object within the function, is it reflected in the caller?" My background causes me to think of everything in terms of pointers, so when I think of pass-by-reference or pass-by-object-reference, I think of pass-by-pointer, which isn't technically correct.
  • Sam Ginrich
    Sam Ginrich about 2 years
    Oops, think I totally agreed with your answer above, though not with citing definitions, which are neither from you nor from me.
  • Sanjeev
    Sanjeev about 2 years
    @SamGinrich, you're right about citing definitions.
  • Sam Ginrich
    Sam Ginrich about 2 years
    :) As stated above I reject them. The original semantics of "passing-by-reference" is that an instance is shared among caller and called method. Whoever came later to define for himself something else, cannot allocate computer science as a whole.
  • Sanjeev
    Sanjeev about 2 years
    @SamGinrich again, nobody has changed the definition. I worked hard to compile all the information in this post, which shows exactly that. If you think someone is trying to changed the definition, please share some evidence of that.
  • Sam Ginrich
    Sam Ginrich about 2 years
    As stated above, the main post above is an island, even if it's a huge one. I'm still wondering, how someone with IQ>=85% can put out a sentence of shape "Java is <a parameter passing mode>".
  • Sam Ginrich
    Sam Ginrich about 2 years
    Indirect evidence, that other definitions exist is here stackoverflow.com/questions/2229498/passing-by-reference-in-‌​c
  • Sam Ginrich
    Sam Ginrich about 2 years
    @Paul de Vrieze "are not allowed to have null values" - think, in C dialects, exactly when p is a pointer, then *p is a reference; this is valid, even if p is null. Concerning assignment, references in Java behave like pointers and meet the "call-by-reference" semantics of C.
  • Sam Ginrich
    Sam Ginrich about 2 years
    What about "Java is a programming language"? What about "Designers of Java built their own terminology, that does not exist outside"?
  • Sanjeev
    Sanjeev about 2 years
    A) that is not evidence of "Established Computer Science" disagreeing with Gosling, it's someone asking a question on stack overflow. B) Thats an example of a pointer being passed by value, not pass-by-reference. C) my post explains this. Have you read it carefully?
  • Sam Ginrich
    Sam Ginrich about 2 years
  • Sanjeev
    Sanjeev about 2 years
    @SamGinrich VB ALLOWS pass-by-reference. Java and C do not!! Am I just wasting my time?
  • Sam Ginrich
    Sam Ginrich about 2 years
    If you say so and loud enough, Established Computer Science will comply. The expectation of a unique terminology on your base - yes, a waste of time!
  • Sanjeev
    Sanjeev about 2 years
    @SamGinrich please read the Microsfoft documentation which you yourself posted. Microsoft does not disagree with Gosling. You haven't posted anything that shows this. And please stop speaking for "Established Computer Science". Majority of the people around the world who design languages and write compilers studied from The Dragon Book. THAT is established computer science. Not me, not you.
  • Sanjeev
    Sanjeev about 2 years
    @SamGinrich here is my reply to the post you posted stackoverflow.com/a/71270573/1028560
  • Sanjeev
    Sanjeev about 2 years
    @SamGinrich saw your post here stackoverflow.com/a/70586240/1028560. I think I know the source of the confusion. I think you have a misunderstanding of what pass-by-value is. Please have a look at this link blog.penjee.com/passing-by-value-vs-by-reference-java-graphi‌​cal. This does a great job of explaining the difference and shows why Java is Pass-By-Value.
  • Sam Ginrich
    Sam Ginrich about 2 years
    I won't. You do not belong to the generation, that grew up with these things and you don't listen anyway, violating the golden rule. stackoverflow.com/a/2229516/9437799
  • Sam Ginrich
    Sam Ginrich about 2 years
    Raises the question, whether Java is an Object Oriented of Reference Oriented language, rather than ´a mechanism for passing arguments´. en.wikipedia.org/wiki/Java_(programming_language)#Principles
  • Sam Ginrich
    Sam Ginrich about 2 years
    "Consistent definitions are import for effective communication." Indeed, Java wanted to be an object-oriented language, until it came to ´passing objects´, then it died from inconsistency. Suddenly references were values and objects did not exists, at all. Living with a lie and forcing everyone not to reference Niklaus Wirth, who got the terms straight.
  • Sam Ginrich
    Sam Ginrich about 2 years
    Java defined itself like this. In history of computer science, the concepts and modi of passing data to functions existed long before Kernighan & Ritchie invented the confusion of pointers and values. For Java one can state, that the own dogmatism of being OBJECT ORIENTED is broke, when in context of calls suddenly a reference is a value, rather than the object instance.
  • alife
    alife about 2 years
    I object to the ire in this answer. Also, referring to it as "Call by value" is something I've never seen outside of Wikipedia ("Pass by value" is the only term I've ever seen used for this passing technique in 40 years). Besides, it's not the call that is by value, it's the parameter passing that is by value, "call by value" would seem (semantically) a misnomer.
  • alife
    alife about 2 years
    The term "by" is the culprit in this. "Passing a reference" and "Passing by reference" are distinct. Java is pass by value. If you need to pass a reference, you pass it by value.
  • alife
    alife about 2 years
    @SamGinrich, That cited page is incorrect. And once again, the confusion is in contrasting "Passing by reference" with "Passing a reference by value". We are going to see a few such confusions, but C similarly follows the PBV rule. If you need a pointer (reference) sent to function, you send it by value. These terms have meanings in computer science. Colloquially we used define PBV by failing "the swap(a,b) test".
  • alife
    alife about 2 years
    @SamGinrich, I seem to have put you on the defensive. This will send us down the wrong path, and I'll not discuss things with someone who assumes I need to get an overview of terms. I've overlooked the prior engagements of yours regarding this topic, and they seem emotionally charged. I'll not contrast your CS degree with mine, and these principals are far from "because I said so." So I consider this over.
  • Sam Ginrich
    Sam Ginrich about 2 years
    @alife The problem is, that you consider your setup as the only existing one, and this is an error.
  • Dalija Prasnikar
    Dalija Prasnikar about 2 years
    This answer completely misses the point of the question and doesn't explain how Java passes parameters.
  • platypusguy
    platypusguy almost 2 years
    You wrote: "In java everything is reference" This is not correct. Only objects are references. Primitives are not. This is what @SamGinrich meant by his comment.
  • Muhammad Zahab Ahmad Khan
    Muhammad Zahab Ahmad Khan almost 2 years
    What a beautiful and concised explaination.
  • azis.mrazish
    azis.mrazish almost 2 years
    From this perspective pass-by-reference does never exist in universe, since reference is actually always a value of pointer
  • JobHunter69
    JobHunter69 almost 2 years
    So basiclly it's passed by pointer?