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

user4315 Source

I always thought Java was pass-by-reference; however I've seen a couple of blog posts (For example, this blog) that claim it's not. I don't think I understand the distinction they're making.

What is the explanation?

javamethodsparameter-passingpass-by-referencepass-by-value

Answers

answered 9 years ago SCdF #1

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.

answered 9 years ago ScArcher2 #2

Java passes references by value.

So you can't change the reference that gets passed in.

answered 9 years ago Hank Gay #3

Basically, reassigning Object parameters doesn't affect the argument, e.g.,

private void foo(Object bar) {
    bar = null;
}

public static void main(String[] args) {
    String baz = "Hah!";
    foo(baz);
    System.out.println(baz);
}

will print out "Hah!" instead of NULL. The reason this works is because bar is a copy of the value of baz, which is just a reference to "Hah!". If it were the actual reference itself, then foo would have redefined baz to null.

answered 9 years ago John Channing #4

Java passes references to objects by value.

answered 9 years ago erlando #5

Java is always pass-by-value. Unfortunately, they decided to call the location of an object a "reference". When we pass the value of an object, we are passing the reference to it. This is confusing to beginners.

It goes like this:

public static void main( String[] args ) {
    Dog aDog = new Dog("Max");
    // 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, java passes by value
    aDog.getName().equals("Fifi"); // false 
}

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 this example 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");
    foo(aDog);
    // when foo(...) returns, the name of the dog has been changed to "Fifi"
    aDog.getName().equals("Fifi"); // 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 itself (except when d is changed to point to a different Dog instance like d = new Dog("Boxer")).

answered 9 years ago Paul de Vrieze #6

To make a long story short, Java objects have some very peculiar properties.

In general, Java has primitive types (int, bool, char, double, etc) that are passed directly by value. Then Java has objects (everything that derives from java.lang.Object). Objects are actually always handled through a reference (a reference being a pointer that you can't touch). That means that in effect, objects are passed by reference, as the references are normally not interesting. It does however mean that you cannot change which object is pointed to as the reference itself is passed by value.

Does this sound strange and confusing? Let's consider how C implements pass by reference and pass by value. In C, the default convention is pass by value. void foo(int x) passes an int by value. void foo(int *x) is a function that does not want an int a, but a pointer to an int: foo(&a). One would use this with the & operator to pass a variable address.

Take this to C++, and we have references. References are basically (in this context) syntactic sugar that hide the pointer part of the equation: void foo(int &x) is called by foo(a), where the compiler itself knows that it is a reference and the address of the non-reference a should be passed. In Java, all variables referring to objects are actually of reference type, in effect forcing call by reference for most intends and purposes without the fine grained control (and complexity) afforded by, for example, C++.

answered 9 years ago shsteimer #7

The distinction, or perhaps just the way I remember as I used to be under the same impression as the original poster is this: Java is always pass by value. All objects( in Java, anything except for primitives) in Java are references. These references are passed by value.

answered 9 years ago pek #8

As many people mentioned it before, Java is always pass-by-value

Here is another example that will help you understand the difference (the classic swap example):

public class Test {
  public static void main(String[] args) {
    Integer a = new Integer(2);
    Integer b = new Integer(3);
    System.out.println("Before: a = " + a + ", b = " + b);
    swap(a,b);
    System.out.println("After: a = " + a + ", b = " + b);
  }

  public static swap(Integer iA, Integer iB) {
    Integer tmp = iA;
    iA = iB;
    iB = tmp;
  }
}

Prints:

Before: a = 2, b = 3
After: a = 2, b = 3

This happens because iA and iB are new local reference variables that have the same value of the passed references (they point to a and b respectively). So, trying to change the references of iA or iB will only change in the local scope and not outside of this method.

answered 9 years ago SWD #9

I always think of it as "pass by copy". It is a copy of the value be it primitive or reference. If it is a primitive it is a copy of the bits that are the value and if it is an Object it is a copy of the reference.

public class PassByCopy{
    public static void changeName(Dog d){
        d.name = "Fido";
    }
    public static void main(String[] args){
        Dog d = new Dog("Maxx");
        System.out.println("name= "+ d.name);
        changeName(d);
        System.out.println("name= "+ d.name);
    }
}
class Dog{
    public String name;
    public Dog(String s){
        this.name = s;
    }
}

output of java PassByCopy:

name= Maxx
name= Fido

Primitive wrapper classes and Strings are immutable so any example using those types will not work the same as other types/objects.

answered 9 years ago sven #10

I have created a thread devoted to these kind of questions for any programming languages here.

Java is also mentioned. Here is the short summary:

  • Java passes it parameters by value
  • "by value" is the only way in java to pass a parameter to a method
  • using methods from the object given as parameter will alter the object as the references point to the original objects. (if that method itself alters some values)

answered 9 years ago Scott Stanchfield #11

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.

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 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, you cannot change where that pointer points.

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.

answered 9 years ago Eclipse #12

Just to show the contrast, compare the following C++ and Java snippets:

In C++: Note: Bad code - memory leaks! But it demonstrates the point.

void cppMethod(int val, int &ref, Dog obj, Dog &objRef, Dog *objPtr, Dog *&objPtrRef)
{
    val = 7; // Modifies the copy
    ref = 7; // Modifies the original variable
    obj.SetName("obj"); // Modifies the copy of Dog passed
    objRef.SetName("objRef"); // Modifies the original Dog passed
    objPtr->SetName("objPtr"); // Modifies the original Dog pointed to 
                               // by the copy of the pointer passed.
    objPtr = new Dog("newObjPtr");  // Modifies the copy of the pointer, 
                                   // leaving the original object alone.
    objPtrRef->SetName("objRefPtr"); // Modifies the original Dog pointed to 
                                    // by the original pointer passed. 
    objPtrRef = new Dog("newObjPtrRef"); // Modifies the original pointer passed
}

int main()
{
    int a = 0;
    int b = 0;
    Dog d0 = Dog("d0");
    Dog d1 = Dog("d1");
    Dog *d2 = new Dog("d2");
    Dog *d3 = new Dog("d3");
    cppMethod(a, b, d0, d1, d2, d3);
    // a is still set to 0
    // b is now set to 7
    // d0 still have name "d0"
    // d1 now has name "objRef"
    // d2 now has name "objPtr"
    // d3 now has name "newObjPtrRef"
}

In Java,

public static void javaMethod(int val, Dog objPtr)
{
   val = 7; // Modifies the copy
   objPtr.SetName("objPtr") // Modifies the original Dog pointed to 
                            // by the copy of the pointer passed.
   objPtr = new Dog("newObjPtr");  // Modifies the copy of the pointer, 
                                  // leaving the original object alone.
}

public static void main()
{
    int a = 0;
    Dog d0 = new Dog("d0");
    javaMethod(a, d0);
    // a is still set to 0
    // d0 now has name "objPtr"
}

Java only has the two types of passing: by value for built-in types, and by value of the pointer for object types.

answered 9 years ago Harald Schilly #13

It's a bit hard to understand, but Java always copies the value - the point is, normally the value is a reference. Therefore you end up with the same object without thinking about it...

answered 9 years ago JacquesB #14

The crux of the matter is that the word reference in the expression "pass by reference" means something completely different from the usual meaning of the word reference in Java.

Usually in Java reference means a a reference to an object. But the technical terms pass by reference/value from programming language theory is talking about a reference to the memory cell holding the variable, which is something completely different.

answered 9 years ago Jared Oberhaus #15

You can never pass by reference in Java, and one of the ways that is obvious is when you want to return more than one value from a method call. Consider the following bit of code in C++:

void getValues(int& arg1, int& arg2) {
    arg1 = 1;
    arg2 = 2;
}
void caller() {
    int x;
    int y;
    getValues(x, y);
    cout << "Result: " << x << " " << y << endl;
}

Sometimes you want to use the same pattern in Java, but you can't; at least not directly. Instead you could do something like this:

void getValues(int[] arg1, int[] arg2) {
    arg1[0] = 1;
    arg2[0] = 2;
}
void caller() {
    int[] x = new int[1];
    int[] y = new int[1];
    getValues(x, y);
    System.out.println("Result: " + x[0] + " " + y[0]);
}

As was explained in previous answers, in Java you're passing a pointer to the array as a value into getValues. That is enough, because the method then modifies the array element, and by convention you're expecting element 0 to contain the return value. Obviously you can do this in other ways, such as structuring your code so this isn't necessary, or constructing a class that can contain the return value or allow it to be set. But the simple pattern available to you in C++ above is not available in Java.

answered 9 years ago kukudas #16

As far as I know, Java only knows call by value. This means for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects. However I think there are some pitfalls; for example, this will not work:

public static void swap(StringBuffer s1, StringBuffer s2) {
    StringBuffer temp = s1;
    s1 = s2;
    s2 = temp;
}


public static void main(String[] args) {
    StringBuffer s1 = new StringBuffer("Hello");
    StringBuffer s2 = new StringBuffer("World");
    swap(s1, s2);
    System.out.println(s1);
    System.out.println(s2);
}

This will populate Hello World and not World Hello because in the swap function you use copys which have no impact on the references in the main. But if your objects are not immutable you can change it for example:

public static void appendWorld(StringBuffer s1) {
    s1.append(" World");
}

public static void main(String[] args) {
    StringBuffer s = new StringBuffer("Hello");
    appendWorld(s);
    System.out.println(s);
}

This will populate Hello World on the command line. If you change StringBuffer into String it will produce just Hello because String is immutable. For example:

public static void appendWorld(String s){
    s = s+" World";
}

public static void main(String[] args) {
    String s = new String("Hello");
    appendWorld(s);
    System.out.println(s);
}

However you could make a wrapper for String like this which would make it able to use it with Strings:

class StringWrapper {
    public String value;

    public StringWrapper(String value) {
        this.value = value;
    }
}

public static void appendWorld(StringWrapper s){
    s.value = s.value +" World";
}

public static void main(String[] args) {
    StringWrapper s = new StringWrapper("Hello");
    appendWorld(s);
    System.out.println(s.value);
}

edit: i believe this is also the reason to use StringBuffer when it comes to "adding" two Strings because you can modifie the original object which u can't with immutable objects like String is.

answered 8 years ago Rusty Shackleford #17

A few corrections to some posts.

C does NOT support pass by reference. It is ALWAYS pass by value. C++ does support pass by reference, but is not the default and is quite dangerous.

It doesn't matter what the value is in Java: primitive or address(roughly) of object, it is ALWAYS passed by value.

If a Java object "behaves" like it is being passed by reference, that is a property of mutability and has absolutely nothing to do with passing mechanisms.

I am not sure why this is so confusing, perhaps because so many Java "programmers" are not formally trained, and thus do not understand what is really going on in memory?

answered 8 years ago fastcodejava #18

Java copies the reference by value. So if you change it to something else (e.g, using new) the reference does not change outside the method. For native types, it is always pass by value.

answered 8 years ago Vinay Lodha #19

Have a look at this code. This code will not throw NullPointerException... It will print "Vinay"

public class Main {
    public static void main(String[] args) {
        String temp = "Vinay";
        print(temp);
        System.err.println(temp);
    }

    private static void print(String temp) {
        temp = null;
    }
}

If Java is pass by reference then it should have thrown NullPointerException as reference is set to Null.

answered 7 years ago Jörg W Mittag #20

I can't believe that nobody mentioned Barbara Liskov yet. When she designed CLU in 1974, she ran into this same terminology problem, and she invented the term call by sharing (also known as call by object-sharing and call by object) for this specific case of "call by value where the value is a reference".

answered 7 years ago Swifty McSwifterton #21

In my opinion, "pass by value" is a terrible way to singularly describe two similar but different events. I guess they should have asked me first.

With primitives we are passing the actual value of the primitive into the method (or constructor), be it the integer "5", the character "c", or what have you. That actual value then becomes its own local primitive. But with objects, all we are doing is giving the same object an additional reference (a local reference), so that we now have two references pointing to the same object.

I hope this simple explanation helps.

answered 7 years ago Gevorg #22

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!

answered 6 years ago Luigi R. Viggiano #23

Everything is passed by value. Primitives and Object references. But objects can be changed, if their interface allows it.

When you pass an object to a method, you are passing a reference, and the object can be modified by the method implementation.

void bithday(Person p) {
    p.age++;
}

The reference of the object itself, is passed by value: you can reassign the parameter, but the change is not reflected back:

void renameToJon(Person p) { 
    p = new Person("Jon"); // this will not work
}

jack = new Person("Jack");
renameToJon(jack);
sysout(jack); // jack is unchanged

As matter of effect, "p" is reference (pointer to the object) and can't be changed.

Primitive types are passed by value. Object's reference can be considered a primitive type too.

To recap, everything is passed by value.

answered 6 years ago fernandoespinosa #24

It's really quite, quite simple:

For a variable of primitive type (eg. int, boolean, char, etc...), when you use its name for a method argument, you are passing the value contained in it (5, true, or 'c'). This value gets "copied", and the variable retains its value even after the method invocation.

For a variable of reference type (eg. String, Object, etc...), when you use its name for a method argument, you are passing the value contained in it (the reference value that "points" to the object). This reference value gets "copied", and the variable retains its value even after the method invocation. The reference variable keeps "pointing" to the same object.

Either way, you're always passing stuff by value.


Compare this to say C++ where you can have a method to take an int&, or in C# where you could have take a ref int (although, in this case, you also have to use the ref modifier when passing the variable's name to the method.)

answered 5 years ago Eng.Fouad #25

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 to 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 to null.

    public static void changeReference(Foo a)
    

    enter image description here

  3. As you call the method changeReference, the reference a will be assigned to 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 to a new object of type Foo with an attribute "b".

    Foo b = new Foo("b");
    

    enter image description here

  5. a = b is re-assigning the reference a NOT f to the object whose its attribute is "b".

    enter image description here


  6. As you call modifyReference(Foo c) method, a reference c is created and assigned to 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 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 :)

answered 5 years ago George Paolo Flores #26

No, it's not pass by reference.

Java is pass by value according to the Java Language Specification:

When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared type, before execution of the body of the method or constructor. The Identifier that appears in the DeclaratorId may be used as a simple name in the body of the method or constructor to refer to the formal parameter.

answered 5 years ago fatma.ekici #27

Java is pass by constant reference where a copy of the reference is passed which means that it is basically a pass by value. You might change the contents of the reference if the class is mutable but you cannot change the reference itself. In other words the address can not be changed since it is passed by value but the content that is pointed by the address can be changed. In case of immutable classes, the content of the reference cannot be changed either.

answered 5 years ago Khaled.K #28

Java is always pass-by-value, the parameters are copies of what the variables passed, all Objects are defined using a reference, and reference is a variable that stores a memory address of where the object is in memory.

Check the comments to understand what happens in execution; follow numbers as they show the flow of execution ..

class Example
{
    public static void test (Cat ref)
    {
        // 3 - <ref> is a copy of the reference <a>
        // both currently reference Grumpy
        System.out.println(ref.getName());

        // 4 - now <ref> references a new <Cat> object named "Nyan"
        ref = new Cat("Nyan");

        // 5 - this should print "Nyan"
        System.out.println( ref.getName() );
    }

    public static void main (String [] args)
    {
        // 1 - a is a <Cat> reference that references a Cat object in memory with name "Grumpy"
        Cat a = new Cat("Grumpy");

        // 2 - call to function test which takes a <Cat> reference
        test (a);

        // 6 - function call ends, and <ref> life-time ends
        // "Nyan" object has no references and the Garbage
        // Collector will remove it from memory when invoked

        // 7 - this should print "Grumpy"
        System.out.println(a.getName());
    }
}

answered 5 years ago JasonG #29

In an attempt to add even more to this, I thought I'd include the SCJP Study Guide section on the topic. This is from the guide that is made to pass the Sun/Oracle test on the behaviour of Java so it's a good source to use for this discussion.

Passing Variables into Methods (Objective 7.3)

7.3 Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.

Methods can be declared to take primitives and/or object references. You need to know how (or if) the caller's variable can be affected by the called method. The difference between object reference and primitive variables, when passed into methods, is huge and important. To understand this section, you'll need to be comfortable with the assignments section covered in the first part of this chapter.

Passing Object Reference Variables

When you pass an object variable into a method, you must keep in mind that you're passing the object reference, and not the actual object itself. Remember that a reference variable holds bits that represent (to the underlying VM) a way to get to a specific object in memory (on the heap). More importantly, you must remember that you aren't even passing the actual reference variable, but rather a copy of the reference variable. A copy of a variable means you get a copy of the bits in that variable, so when you pass a reference variable, you're passing a copy of the bits representing how to get to a specific object. In other words, both the caller and the called method will now have identical copies of the reference, and thus both will refer to the same exact (not a copy) object on the heap.

For this example, we'll use the Dimension class from the java.awt package:

1. import java.awt.Dimension;
2. class ReferenceTest {
3.     public static void main (String [] args) {
4.         Dimension d = new Dimension(5,10);
5.         ReferenceTest rt = new ReferenceTest();
6.         System.out.println("Before modify() d.height = " + d.height);
7.         rt.modify(d);
8.         System.out.println("After modify() d.height = "
9.     }
10.
11.
12.
13.   }
14. }

When we run this class, we can see that the modify() method was indeed able to modify the original (and only) Dimension object created on line 4.

C:\Java Projects\Reference>java ReferenceTest
Before modify() d.height = 10
dim = 11
After modify() d.height = 11

Notice when the Dimension object on line 4 is passed to the modify() method, any changes to the object that occur inside the method are being made to the object whose reference was passed. In the preceding example, reference variables d and dim both point to the same object.

Does Java Use Pass-By-Value Semantics?

If Java passes objects by passing the reference variable instead, does that mean Java uses pass-by-reference for objects? Not exactly, although you'll often hear and read that it does. Java is actually pass-by-value for all variables running within a single VM. Pass-by-value means pass-by-variable-value. And that means, pass-by-copy-of- the-variable! (There's that word copy again!)

It makes no difference if you're passing primitive or reference variables, you are always passing a copy of the bits in the variable. So for a primitive variable, you're passing a copy of the bits representing the value. For example, if you pass an int variable with the value of 3, you're passing a copy of the bits representing 3. The called method then gets its own copy of the value, to do with it what it likes.

And if you're passing an object reference variable, you're passing a copy of the bits representing the reference to an object. The called method then gets its own copy of the reference variable, to do with it what it likes. But because two identical reference variables refer to the exact same object, if the called method modifies the object (by invoking setter methods, for example), the caller will see that the object the caller's original variable refers to has also been changed. In the next section, we'll look at how the picture changes when we're talking about primitives.

The bottom line on pass-by-value: the called method can't change the caller's variable, although for object reference variables, the called method can change the object the variable referred to. What's the difference between changing the variable and changing the object? For object references, it means the called method can't reassign the caller's original reference variable and make it refer to a different object, or null. For example, in the following code fragment,

        void bar() {
           Foo f = new Foo();
           doStuff(f);
        }
        void doStuff(Foo g) {
           g.setName("Boo");
           g = new Foo();
        }

reassigning g does not reassign f! At the end of the bar() method, two Foo objects have been created, one referenced by the local variable f and one referenced by the local (argument) variable g. Because the doStuff() method has a copy of the reference variable, it has a way to get to the original Foo object, for instance to call the setName() method. But, the doStuff() method does not have a way to get to the f reference variable. So doStuff() can change values within the object f refers to, but doStuff() can't change the actual contents (bit pattern) of f. In other words, doStuff() can change the state of the object that f refers to, but it can't make f refer to a different object!

Passing Primitive Variables

Let's look at what happens when a primitive variable is passed to a method:

class ReferenceTest {
    public static void main (String [] args) {
      int a = 1;
      ReferenceTest rt = new ReferenceTest();
      System.out.println("Before modify() a = " + a);
      rt.modify(a);
      System.out.println("After modify() a = " + a);
    }
    void modify(int number) {
      number = number + 1;
      System.out.println("number = " + number);
    }
}

In this simple program, the variable a is passed to a method called modify(), which increments the variable by 1. The resulting output looks like this:

  Before modify() a = 1
  number = 2
  After modify() a = 1

Notice that a did not change after it was passed to the method. Remember, it was a copy of a that was passed to the method. When a primitive variable is passed to a method, it is passed by value, which means pass-by-copy-of-the-bits-in-the-variable.

answered 5 years ago Gaurav #30

Java has only pass by value. A very simple example to validate this.

public void test() {
    MyClass obj = null;
    init(obj);
    //After calling init method, obj still points to null
    //this is because obj is passed as value and not as reference.
}
private void init(MyClass objVar) {
    objVar = new MyClass();
}

answered 5 years ago bvdb #31

Shortest answer :)

  • Java has pass-by-value (and pass-reference-by-value.)
  • C# also has pass-by-reference

In C# this is accomplished with the "out" and "ref" keywords.

Pass By Reference: The variable is passed in such a way that a reassignment inside the method is reflected even outside the method.

Here follows an example of passing-by-reference (C#). This feature does not exist in java.

class Example
{
    static void InitArray(out int[] arr)
    {
        arr = new int[5] { 1, 2, 3, 4, 5 };
    }

    static void Main()
    {
        int[] someArray;
        InitArray(out someArray);

        // This is true !
        boolean isTrue = (someArray[0] == 1);
    }
}

See also: MSDN library (C#): passing arrays by ref and out

See also: MSDN library (C#): passing by by value and by reference

answered 4 years ago James Drinkard #32

The bottom line on pass-by-value: the called method can't change the caller's variable, although for object reference variables, the called method can change the object the variable referred to. What's the difference between changing the variable and changing the object? For object references, it means the called method can't reassign the caller's original reference variable and make it refer to a different object, or null.

I took this code and explanation from a book on Java Certification and made some minor changes.
I think it's a good illustration to the pass by value of an object. In the code below, reassigning g does not reassign f! At the end of the bar() method, two Foo objects have been created, one referenced by the local variable f and one referenced by the local (argument) variable g.

Because the doStuff() method has a copy of the reference variable, it has a way to get to the original Foo object, for instance to call the setName() method. But, the doStuff() method does not have a way to get to the f reference variable. So doStuff() can change values within the object f refers to, but doStuff() can't change the actual contents (bit pattern) of f. In other words, doStuff() can change the state of the object that f refers to, but it can't make f refer to a different object!

package test.abc;

public class TestObject {

    /**
     * @param args
     */
    public static void main(String[] args) {
        bar();
    }

    static void bar() {
        Foo f = new Foo();
        System.out.println("Object reference for f: " + f);
        f.setName("James");
        doStuff(f);
        System.out.println(f.getName());
        //Can change the state of an object variable in f, but can't change the object reference for f.
        //You still have 2 foo objects.
        System.out.println("Object reference for f: " + f);
        }

    static void doStuff(Foo g) {
            g.setName("Boo");
            g = new Foo();
            System.out.println("Object reference for g: " + g);
        }
}


package test.abc;

public class Foo {
    public String name = "";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Note that the object reference has not changed in the console output below:

Console output:

Object reference for f: [email protected]

Object reference for g: [email protected]

Boo Object reference for f: [email protected]

answered 4 years ago cutmancometh #33

I feel like arguing about "pass-by-reference vs pass-by-value" is not super-helpful.

If you say, "Java is pass-by-whatever (reference/value)", in either case, you're not provide a complete answer. Here's some additional information that will hopefully aid in understanding what's happening in memory.

Crash course on stack/heap before we get to the Java implementation: Values go on and off the stack in a nice orderly fashion, like a stack of plates at a cafeteria. Memory in the heap (also known as dynamic memory) is haphazard and disorganized. The JVM just finds space wherever it can, and frees it up as the variables that use it are no longer needed.

Okay. First off, local primitives go on the stack. So this code:

int x = 3;
float y = 101.1f;
boolean amIAwesome = true;

results in this:

primitives on the stack

When you declare and instantiate an object. The actual object goes on the heap. What goes on the stack? The address of the object on the heap. C++ programmers would call this a pointer, but some Java developers are against the word "pointer". Whatever. Just know that the address of the object goes on the stack.

Like so:

int problems = 99;
String name = "Jay-Z";

a b*7ch aint one!

An array is an object, so it goes on the heap as well. And what about the objects in the array? They get their own heap space, and the address of each object goes inside the array.

JButton[] marxBros = new JButton[3];
marxBros[0] = new JButton("Groucho");
marxBros[1] = new JButton("Zeppo");
marxBros[2] = new JButton("Harpo");

marx brothers

So, what gets passed in when you call a method? If you pass in an object, what you're actually passing in is the address of the object. Some might say the "value" of the address, and some say it's just a reference to the object. This is the genesis of the holy war between "reference" and "value" proponents. What you call it isn't as important as that you understand that what's getting passed in is the address to the object.

private static void shout(String name){
    System.out.println("There goes " + name + "!");
}

public static void main(String[] args){
    String hisName = "John J. Jingleheimerschmitz";
    String myName = hisName;
    shout(myName);
}

One String gets created and space for it is allocated in the heap, and the address to the string is stored on the stack and given the identifier hisName, since the address of the second String is the same as the first, no new String is created and no new heap space is allocated, but a new identifier is created on the stack. Then we call shout(): a new stack frame is created and a new identifier, name is created and assigned the address of the already-existing String.

la da di da da da da

So, value, reference? You say "potato".

answered 4 years ago user1931858 #34

Java passes parameters by value, but for object variables, the values are essentially references to objects. Since arrays are objects the following example code shows the difference.

public static void dummyIncrease(int[] x, int y)
{
    x[0]++;
    y++;
}
public static void main(String[] args)
{
    int[] arr = {3, 4, 5};
    int b = 1;
    dummyIncrease(arr, b);
    // arr[0] is 4, but b is still 1
}

main()
  arr +---+       +---+---+---+
      | # | ----> | 3 | 4 | 5 |
      +---+       +---+---+---+
  b   +---+             ^
      | 1 |             | 
      +---+             |
                        |
dummyIncrease()         |
  x   +---+             |
      | # | ------------+
      +---+      
  y   +---+ 
      | 1 | 
      +---+ 

answered 4 years ago Ganesh #35

Java is always pass by values NOT pass by reference

first of we understand what is pass by value and pass by reference

pass by value means you are making a copy in memory of the actual parameter's value that is passed in, a copy of the contents of the actual parameter

pass by reference (also called pass by address), a copy of the address of the actual parameter is stored

Some time it gives illusion pass by reference.lets see how it works by example

public class Passbyvalue {
    public static void main(String[] args) {
        test t=new test();
        t.name="initialvalue";
        new Passbyvalue().changeValue(t);
        System.out.println(t.name);
    }

    public void changeValue(test f){
        f.name="changevalue";
    }
}

class test{
    String name;
}

Output of this program is

changevalue

lets understand step by step

test t=new test();

as we all know it will create object in heap and return return reference value back to t. suppose for example value of t is 0x100234(its JVM internal value as we don't about it i have just consider it for example)

enter image description here

new Passbyvalue().changeValue(t);

when passing reference t to function it will not directly pass actual reference value of object test but it will create copy of t and then it pass to function ( as it pass by value it passes copy of variable not actual reference of it) . As we consider value of t will be0x100234 . so in this way both t and f will have same value and hence they will point to same object

enter image description here

so if you change any thing in function using reference f it will modify existing contain of object that why we were getting output "changevalue" which is updated in function

to understand this more clearly consider following example

public class Passbyvalue {
    public static void main(String[] args) {
        test t=new test();
        t.name="initialvalue";
        new Passbyvalue().changerefence(t);
        System.out.println(t.name);
    }

    public void changerefence(test f){
        f=null;
    }
}

class test{
    String name;
}

will it give null pointer no because it passes only copy of reference .In case of by reference it could have given nullpointer exception

enter image description here

Hopefully this will help

answered 4 years ago Bhushan #36

The Java programming language passes arguments only by value, that is, you cannot change the argument value in the calling method from within the called method.


However, when an object instance is passed as an argument to a method, the value of the argument is not the object itself but a reference to the object. You can change the contents of the object in the called method but not the object reference.


To many people, this looks like pass-by-reference, and behaviorally, it has much in common with pass-by-reference. However, there are two reasons this is inaccurate.

  • Firstly, the ability to change the thing passed into a method only applies to objects, not primitive values.

  • Second, the actual value associated with a variable of object type is the reference to the object, and not the object itself. This is an important distinction in other ways, and if clearly understood, is entirely supporting of the point that the Java programming language passes arguments by value.


The following code example illustrates this point:
1 public class PassTest {
2
3   // Methods to change the current values
4   public static void changeInt(int value) {
5     value = 55;
6  }
7   public static void changeObjectRef(MyDate ref) {
8     ref = new MyDate(1, 1, 2000);
9  }
10   public static void changeObjectAttr(MyDate ref) {
11     ref.setDay(4);
12   }
13
14 public static void main(String args[]) {
15     MyDate date;
16     int val;
17
18     // Assign the int
19     val = 11;
20     // Try to change it
21     changeInt(val);
22     // What is the current value?
23     System.out.println("Int value is: " + val);
24
25 // Assign the date
26     date = new MyDate(22, 7, 1964);
27     // Try to change it
28     changeObjectRef(date);
29     // What is the current value?
30 System.out.println("MyDate: " + date);
31
32 // Now change the day attribute
33     // through the object reference
34     changeObjectAttr(date);
35     // What is the current value?
36 System.out.println("MyDate: " + date);
37   }
38 }

This code outputs the following:
java PassTest
Int value is: 11
MyDate: 22-7-1964
MyDate: 4-7-1964
The MyDate object is not changed by the changeObjectRef method;
however, the changeObjectAttr method changes the day attribute of the
MyDate object.

answered 4 years ago Srle #37

In java everything is reference, so when you have something like: Point pnt1 = new Point(0,0); Java does following:

  1. Creates new Point object
  2. Creates new Point reference and initialize that reference to point (refer to) on previously created Point object.
  3. From here, through Point object life, you will access to that object through pnt1 reference. So we can say that in Java you manipulate object through its reference.

enter image description here

Java doesn't pass method arguments by reference; it passes them by value. I will use example from this site:

public static void tricky(Point arg1, Point arg2) {
  arg1.x = 100;
  arg1.y = 100;
  Point temp = arg1;
  arg1 = arg2;
  arg2 = temp;
}
public static void main(String [] args) {
  Point pnt1 = new Point(0,0);
  Point pnt2 = new Point(0,0);
  System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y); 
  System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
  System.out.println(" ");
  tricky(pnt1,pnt2);
  System.out.println("X1: " + pnt1.x + " Y1:" + pnt1.y); 
  System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);  
}

Flow of the program:

Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);

Creating two different Point object with two different reference associated. enter image description here

System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y); 
System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
System.out.println(" ");

As expected output will be:

X1: 0     Y1: 0
X2: 0     Y2: 0

On this line 'pass-by-value' goes into the play...

tricky(pnt1,pnt2);           public void tricky(Point arg1, Point arg2);

References pnt1 and pnt2 are passed by value to the tricky method, which means that now yours references pnt1 and pnt2 have their copies named arg1 and arg2.So pnt1 and arg1 points to the same object. (Same for the pnt2 and arg2) enter image description here

In the tricky method:

 arg1.x = 100;
 arg1.y = 100;

enter image description here

Next in the tricky method

Point temp = arg1;
arg1 = arg2;
arg2 = temp;

Here, you first create new temp Point reference which will point on same place like arg1 reference. Then you move reference arg1 to point to the same place like arg2 reference. Finally arg2 will point to the same place like temp.

enter image description here

From here scope of tricky method is gone and you don't have access any more to the references: arg1, arg2, temp. But important note is that everything you do with these references when they are 'in life' will permanently affect object on which they are point to.

So after executing method tricky, when you return to main, you have this situation: enter image description here

So now, completely execution of program will be:

X1: 0         Y1: 0
X2: 0         Y2: 0
X1: 100       Y1: 100
X2: 0         Y2: 0

answered 4 years ago Aniket Thakur #38

Java passes references to objects by value.

So if any modification is done to the Object to which the reference argument points it will be reflected back on the original object.

But if the reference argument point to another Object still the original reference will point to original Object.

answered 4 years ago karatedog #39

A reference is always a value when represented, no matter what language you use.

Getting an outside of the box view, let's look at Assembly or some low level memory management. At the CPU level a reference to anything immediately becomes a value if it gets written to memory or to one of the CPU registers. (That is why pointer is a good definition. It is a value, which has a purpose at the same time).

Data in memory has a Location and at that location there is a value (byte,word, whatever). In Assembly we have a convenient solution to give a Name to certain Location (aka variable), but when compiling the code, the assembler simply replaces Name with the designated location just like your browser replaces domain names with IP addresses.

Down to the core it is technically impossible to pass a reference to anything in any language without representing it (when it immediately becomes a value).

Lets say we have a variable Foo, its Location is at the 47th byte in memory and its Value is 5. We have another variable Ref2Foo which is at 223rd byte in memory, and its value will be 47. This Ref2Foo might be a technical variable, not explicitly created by the program. If you just look at 5 and 47 without any other information, you will see just two Values. If you use them as references then to reach to 5 we have to travel:

(Name)[Location] -> [Value at the Location]
---------------------
(Ref2Foo)[223]  -> 47
(Foo)[47]       -> 5

This is how jump-tables work.

If we want to call a method/function/procedure with Foo's value, there are a few possible way to pass the variable to the method, depending on the language and its several method invocation modes:

  1. 5 gets copied to one of the CPU registers (ie. EAX).
  2. 5 gets PUSHd to the stack.
  3. 47 gets copied to one of the CPU registers
  4. 47 PUSHd to the stack.
  5. 223 gets copied to one of the CPU registers.
  6. 223 gets PUSHd to the stack.

In every cases above a value - a copy of an existing value - has been created, it is now upto the receiving method to handle it. When you write "Foo" inside the method, it is either read out from EAX, or automatically dereferenced, or double dereferenced, the process depends on how the language works and/or what the type of Foo dictates. This is hidden from the developer until she circumvents the dereferencing process. So a reference is a value when represented, because a reference is a value that has to be processed (at language level).

Now we have passed Foo to the method:

  • in case 1. and 2. if you change Foo (Foo = 9) it only affects local scope as you have a copy of the Value. From inside the method we cannot even determine where in memory the original Foo was located.
  • in case 3. and 4. if you use default language constructs and change Foo (Foo = 11), it could change Foo globally (depends on the language, ie. Java or like Pascal's procedure findMin(x, y, z: integer;var m: integer);). However if the language allows you to circumvent the dereference process, you can change 47, say to 49. At that point Foo seems to have been changed if you read it, because you have changed the local pointer to it. And if you were to modify this Foo inside the method (Foo = 12) you will probably FUBAR the execution of the program (aka. segfault) because you will write to a different memory than expected, you can even modify an area that is destined to hold executable program and writing to it will modify running code (Foo is now not at 47). BUT Foo's value of 47 did not change globally, only the one inside the method, because 47 was also a copy to the method.
  • in case 5. and 6. if you modify 223 inside the method it creates the same mayhem as in 3. or 4. (a pointer, pointing to a now bad value, that is again used as a pointer) but this is still a local problem, as 223 was copied. However if you are able to dereference Ref2Foo (that is 223), reach to and modify the pointed value 47, say, to 49, it will affect Foo globally, because in this case the methods got a copy of 223 but the referenced 47 exists only once, and changing that to 49 will lead every Ref2Foo double-dereferencing to a wrong value.

Nitpicking on insignificant details, even languages that do pass-by-reference will pass values to functions, but those functions know that they have to use it for dereferencing purposes. This pass-the-reference-as-value is just hidden from the programmer because it is practically useless and the terminology is only pass-by-reference.

Strict pass-by-value is also useless, it would mean that a 100 Mbyte array should have to be copied every time we call a method with the array as argument, therefore Java cannot be stricly pass-by-value. Every language would pass a reference to this huge array (as a value) and either employs copy-on-write mechanism if that array can be changed locally inside the method or allows the method (as Java does) to modify the array globally (from the caller's view) and a few languages allows to modify the Value of the reference itself.

So in short and in Java's own terminology, Java is pass-by-value where value can be: either a real value or a value that is a representation of a reference.

answered 4 years ago ron #40

Mr @Scott Stanchfield wrote an excellent answer. Here is the class that would you to verify exactly what he meant:

public class Dog {

    String dog ;
    static int x_static;
    int y_not_static;

    public String getName()
    {
        return this.dog;
    }

    public Dog(String dog)
    {
        this.dog = dog;
    }

    public void setName(String name)
    {
        this.dog = name;
    }

    public static void foo(Dog someDog)
    {
        x_static = 1;
        // y_not_static = 2;  // not possible !!
        someDog.setName("Max");     // AAA
        someDog = new Dog("Fifi");  // BBB
        someDog.setName("Rowlf");   // CCC
    }

    public static void main(String args[])
    {
        Dog myDog = new Dog("Rover");
        foo(myDog);
        System.out.println(myDog.getName());
    }
}

So, we pass from main() a dog called Rover, then we assign a new address to the pointer that we passed, but at the end, the name of the dog is not Rover, and not Fifi, and certainly not Rowlf, but Max.

answered 4 years ago Sotirios Delimanolis #41

I thought I'd contribute this answer to add more details from the Specifications.

First, What's the difference between passing by reference vs. passing by value?

Passing by reference means the called functions' parameter will be the same as the callers' passed argument (not the value, but the identity - the variable itself).

Pass by value means the called functions' parameter will be a copy of the callers' passed argument.

Or from wikipedia, on the subject of pass-by-reference

In call-by-reference evaluation (also referred to as pass-by-reference), a function receives an implicit reference to a variable used as argument, rather than a copy of its value. This typically means that the function can modify (i.e. assign to) the variable used as argument—something that will be seen by its caller.

And on the subject of pass-by-value

In call-by-value, the argument expression is evaluated, and the resulting value is bound to the corresponding variable in the function [...]. If the function or procedure is able to assign values to its parameters, only its local copy is assigned [...].

Second, we need to know what Java uses in its method invocations. The Java Language Specification states

When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared type, before execution of the body of the method or constructor.

So it assigns (or binds) the value of the argument to the corresponding parameter variable.

What is the value of the argument?

Let's consider reference types, the Java Virtual Machine Specification states

There are three kinds of reference types: class types, array types, and interface types. Their values are references to dynamically created class instances, arrays, or class instances or arrays that implement interfaces, respectively.

The Java Language Specification also states

The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.

The value of an argument (of some reference type) is a pointer to an object. Note that a variable, an invocation of a method with a reference type return type, and an instance creation expression (new ...) all resolve to a reference type value.

So

public void method (String param) {}
...
String var = new String("ref");
method(var);
method(var.toString());
method(new String("ref"));

all bind the value of a reference to a String instance to the method's newly created parameter, param. This is exactly what the definition of pass-by-value describes. As such, Java is pass-by-value.

The fact that you can follow the reference to invoke a method or access a field of the referenced object is completely irrelevant to the conversation. The definition of pass-by-reference was

This typically means that the function can modify (i.e. assign to) the variable used as argument—something that will be seen by its caller.

In Java, modifying the variable means reassigning it. In Java, if you reassigned the variable within the method, it would go unnoticed to the caller. Modifying the object referenced by the variable is a different concept entirely.


Primitive values are also defined in the Java Virtual Machine Specification, here. The value of the type is the corresponding integral or floating point value, encoded appropriately (8, 16, 32, 64, etc. bits).

answered 4 years ago Dustin Deus #42

Understand it in 2 Steps:

You can't change the reference to the object itself but you can work with this passed parameter as a reference to the object.

If you want to change the value behind the reference you will only declare a new variable on the stack with the same name 'd'. Look at the references with the sign @ and you will find out that the reference has been changed.

public static void foo(Dog d) {
  d.Name = "belly";
  System.out.println(d); //Reference: [email protected]

  d = new Dog("wuffwuff");
  System.out.println(d); //[email protected]
}
public static void main(String[] args) throws Exception{
  Dog lisa = new Dog("Lisa");
  foo(lisa);
  System.out.println(lisa.Name); //belly
}

answered 3 years ago Michał Żbikowski #43

Throughout all the answers we see that Java pass-by-value or rather as @Gevorg wrote: "pass-by-copy-of-the-variable-value" and this is the idea that we should have in mind all the time.

I am focusing on examples that helped me understand the idea and it is rather addendum to previous answers.

From [1] In Java you always are passing arguments by copy; that is you're always creating a new instance of the value inside the function. But there are certain behaviors that can make you think you're passing by reference.

  • Passing by copy: When a variable is passed to a method/function, a copy is made (sometimes we hear that when you pass primitives, you're making copies).

  • Passing by reference: When a variable is passed to a method/function, the code in the method/function operates on the original variable (You're still passing by copy, but references to values inside the complex object are parts of both versions of the variable, both the original and the version inside the function. The complex objects themselves are being copied, but the internal references are being retained)

Examples of Passing by copy/ by value

Example from [ref 1]

void incrementValue(int inFunction){
  inFunction ++;
  System.out.println("In function: " + inFunction);
}

int original = 10;
System.out.print("Original before: " + original);
incrementValue(original);
System.out.println("Original after: " + original);

We see in the console:
 > Original before: 10
 > In Function: 11
 > Original after: 10 (NO CHANGE)

Example from [ref 2]

shows nicely the mechanism watch max 5 min

(Passing by reference) pass-by-copy-of-the-variable-value

Example from [ref 1] (remember that an array is an object)

void incrementValu(int[] inFuncion){
  inFunction[0]++;
  System.out.println("In Function: " + inFunction[0]);
}

int[] arOriginal = {10, 20, 30};
System.out.println("Original before: " + arOriginal[0]);
incrementValue(arOriginal[]);
System.out.println("Original before: " + arOriginal[0]);

We see in the console:
  >Original before: 10
  >In Function: 11
  >Original before: 11 (CHANGE)

The complex objects themselves are being copied, but the internal references are being retained.

Example from[ref 3]

package com.pritesh.programs;

class Rectangle {
  int length;
  int width;

  Rectangle(int l, int b) {
    length = l;
    width = b;
  }

  void area(Rectangle r1) {
    int areaOfRectangle = r1.length * r1.width;
    System.out.println("Area of Rectangle : " 
                            + areaOfRectangle);
  }
}

class RectangleDemo {
  public static void main(String args[]) {
    Rectangle r1 = new Rectangle(10, 20);
    r1.area(r1);
  }
}

The area of the rectangle is 200 and the length=10 and width=20

Last thing I would like to share was this moment of the lecture: Memory Allocation which I found very helpful in understanding the Java passing by value or rather “pass-by-copy-of-the-variable-value” as @Gevorg has written.

  1. REF 1 Lynda.com
  2. REF 2 Professor Mehran Sahami
  3. REF 3 c4learn

answered 3 years ago drew7721 #44

There is a workaround in Java for the reference. Let me explain by this example:

public class Yo {
public static void foo(int x){
    System.out.println(x); //out 2
    x = x+2;
    System.out.println(x); // out 4
}
public static void foo(int[] x){
    System.out.println(x[0]); //1
    x[0] = x[0]+2;
    System.out.println(x[0]); //3
}
public static void main(String[] args) {
    int t = 2;
    foo(t);
    System.out.println(t); // out 2 (t did not change in foo)

    int[] tab = new int[]{1};
    foo(tab);
    System.out.println(tab[0]); // out 3 (tab[0] did change in foo)
}}

I hope this helps!

answered 3 years ago Ramprasad #45

Simple program

import java.io.*;
class Aclass
{
    public int a;
}
public class test
{
    public static void foo_obj(Aclass obj)
    {
        obj.a=5;
    }
    public static void foo_int(int a)
    {
        a=3;
    }
    public static void main(String args[])
    {
        //test passing an object
        Aclass ob = new Aclass();
        ob.a=0;
        foo_obj(ob);
        System.out.println(ob.a);//prints 5

        //test passing an integer
        int i=0;
        foo_int(i);
        System.out.println(i);//prints 0
    }
}

From a C/C++ programmer's point of view, java uses pass by value, so for primitive data types (int, char etc) changes in the function does not reflect in the calling function. But when you pass an object and in the function you change its data members or call member functions which can change the state of the object, the calling function will get the changes.

answered 3 years ago João Oliveira #46

Java passes everything by value!!

//create an object by passing in a name and age:

PersonClass variable1 = new PersonClass("Mary", 32);

PersonClass variable2;

//Both variable2 and variable1 now reference the same object

variable2 = variable1; 


PersonClass variable3 = new PersonClass("Andre", 45);

// variable1 now points to variable3

variable1 = variable3;

//WHAT IS OUTPUT BY THIS?

System.out.println(variable2);
System.out.println(variable1);

Mary 32
Andre 45

if you could understand this example we r done. otherwise, please visit this webPage for detailed explanation:

webPage

answered 3 years ago Christian #47

Java passes parameters by VALUE, and by value ONLY.

To cut long story short:

For those coming from C#: THERE IS NO "out" parameter.

For those coming from PASCAL: THERE IS NO "var" parameter.

It means you can't change the reference from the object itself, but you can always change the object's properties.

A workaround is to use StringBuilder parameter instead String. And you can always use arrays!

answered 3 years ago spiderman #48

Let me try to explain my understanding with the help of four examples. Java is pass-by-value, and not pass-by-reference

/**

Pass By Value

In Java, all parameters are passed by value, i.e. assigning a method argument is not visible to the caller.

*/

Example 1:

public class PassByValueString {
    public static void main(String[] args) {
        new PassByValueString().caller();
    }

    public void caller() {
        String value = "Nikhil";
        boolean valueflag = false;
        String output = method(value, valueflag);
        /*
         * 'output' is insignificant in this example. we are more interested in
         * 'value' and 'valueflag'
         */
        System.out.println("output : " + output);
        System.out.println("value : " + value);
        System.out.println("valueflag : " + valueflag);

    }

    public String method(String value, boolean valueflag) {
        value = "Anand";
        valueflag = true;
        return "output";
    }
}

Result

output : output
value : Nikhil
valueflag : false

Example 2:

/** * * Pass By Value * */

public class PassByValueNewString {
    public static void main(String[] args) {
        new PassByValueNewString().caller();
    }

    public void caller() {
        String value = new String("Nikhil");
        boolean valueflag = false;
        String output = method(value, valueflag);
        /*
         * 'output' is insignificant in this example. we are more interested in
         * 'value' and 'valueflag'
         */
        System.out.println("output : " + output);
        System.out.println("value : " + value);
        System.out.println("valueflag : " + valueflag);

    }

    public String method(String value, boolean valueflag) {
        value = "Anand";
        valueflag = true;
        return "output";
    }
}

Result

output : output
value : Nikhil
valueflag : false

Example 3:

/** This 'Pass By Value has a feeling of 'Pass By Reference'

Some people say primitive types and 'String' are 'pass by value' and objects are 'pass by reference'.

But from this example, we can understand that it is infact pass by value only, keeping in mind that here we are passing the reference as the value. ie: reference is passed by value. That's why are able to change and still it holds true after the local scope. But we cannot change the actual reference outside the original scope. what that means is demonstrated by next example of PassByValueObjectCase2.

*/

public class PassByValueObjectCase1 {

    private class Student {
        int id;
        String name;
        public Student() {
        }
        public Student(int id, String name) {
            super();
            this.id = id;
            this.name = name;
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        @Override
        public String toString() {
            return "Student [id=" + id + ", name=" + name + "]";
        }
    }

    public static void main(String[] args) {
        new PassByValueObjectCase1().caller();
    }

    public void caller() {
        Student student = new Student(10, "Nikhil");
        String output = method(student);
        /*
         * 'output' is insignificant in this example. we are more interested in
         * 'student'
         */
        System.out.println("output : " + output);
        System.out.println("student : " + student);
    }

    public String method(Student student) {
        student.setName("Anand");
        return "output";
    }
}

Result

output : output
student : Student [id=10, name=Anand]

Example 4:

/**

In addition to what was mentioned in Example3 (PassByValueObjectCase1.java), we cannot change the actual reference outside the original scope."

Note: I am not pasting the code for private class Student. The class definition for Student is same as Example3.

*/

public class PassByValueObjectCase2 {

    public static void main(String[] args) {
        new PassByValueObjectCase2().caller();
    }

    public void caller() {
        // student has the actual reference to a Student object created
        // can we change this actual reference outside the local scope? Let's see
        Student student = new Student(10, "Nikhil");
        String output = method(student);
        /*
         * 'output' is insignificant in this example. we are more interested in
         * 'student'
         */
        System.out.println("output : " + output);
        System.out.println("student : " + student); // Will it print Nikhil or Anand?
    }

    public String method(Student student) {
        student = new Student(20, "Anand");
        return "output";
    }

}

Result

output : output
student : Student [id=10, name=Nikhil]

answered 2 years ago kaushalpranav #49

ACCORDING TO C++ TERMINOLOGY :

  1. Primitive Types and their wrappers - Pass by Value
  2. Other Complex Datatypes - Pass by Reference

(Although Java is completely Pass by Value, in the second case it passes the reference to the object and in this case the value of the object if changed is reflected in the main function and so I called it Pass by Reference according to C++ Terminology.) If you are hailing from C++, then Java is pass by value for Primitive types and their Wrapper Classes like int, Integer, bool, Boolean i.e., if you pass a value of these data types, there will be no change in the original function. For all other kinds of datatypes java just passes them and if any change is made, the change can be seen in the original function(It can be called pass by reference according to c++ terminology)

answered 2 years ago Placinta Alexandru #50

Java always uses call by value. That means the method gets copy of all parameter values.

Consider next 3 situations:

1) Trying to change primitive variable

public static void increment(int x) { x++; }

int a = 3;
increment(a);

x will copy value of a and will increment x, a remains the same

2) Trying to change primitive field of an object

public static void increment(Person p) { p.age++; }

Person pers = new Person(20); // age = 20
increment(pers);

p will copy reference value of pers and will increment age field, variables are referencing to the same object so age is changed

3) Trying to change reference value of reference variables

public static void swap(Person p1, Person p2) {
    Person temp = p1;
    p1 = p2;
    p2 = temp;
}

Person pers1 = new Person(10);
Person pers2 = new Person(20);
swap(pers1, pers2);

after calling swap p1, p2 copy reference values from pers1 and pers2, are swapping with values, so pers1 and pers2 remain the same

So. you can change only fields of objects in method passing copy of reference value to this object.

answered 2 years ago Gee Bee #51

So many long answers. Let me give a simple one:

  • Java always passes everything by value
  • that means also references are passed by value

In short, you can not modify value of any parameter passed, but you can call methods or change attributes of an object reference passed.

answered 2 years ago OverCoder #52

I made this little diagram that shows how the data gets created and passed

Diagram of how data is created and passed

Note: Primitive values are passed as a value, the first reference to to that value is the method's argument

That means:

  • You can change the value of myObject inside the function
  • But you can't change what myObject references to, inside the function, because point is not myObject
  • Remember, both point and myObject are references, different references, however, those references point at the same new Point(0,0)

answered 2 years ago Cdaragorn #53

A lot of the confusion surrounding this issue comes from the fact that Java has attempted to redefine what "Pass by value" and "Pass by reference" mean. It's important to understand that these are Industry Terms, and cannot be correctly understood outside of that context. They are meant to help you as you code and are valuable to understand, so let's first go over what they mean.

A good description of both can be found here.

Pass By Value The value the function received is a copy of the object the caller is using. It is entirely unique to the function and anything you do to that object will only be seen within the function.

Pass By Reference The value the function received is a reference to the object the caller is using. Anything the function does to the object that value refers to will be seen by the caller and it will be working with those changes from that point on.

As is clear from those definitions, the fact that the reference is passed by value is irrelevant. If we were to accept that definition, then these terms become meaningless and all languages everywhere are only Pass By Value.

No matter how you pass the reference in, it can only ever be passed by value. That isn't the point. The point is that you passed a reference to your own object to the function, not a copy of it. The fact that you can throw away the reference you received is irrelevant. Again, if we accepted that definition, these terms become meaningless and everyone is always passing by value.

And no, C++'s special "pass by reference" syntax is not the exclusive definition of pass by reference. It is purely a convenience syntax meant to make it so that you don't need to use pointer syntax after passing the pointer in. It is still passing a pointer, the compiler is just hiding that fact from you. It also still passes that pointer BY VALUE, the compiler is just hiding that from you.

So, with this understanding, we can look at Java and see that it actually has both. All Java primitive types are always pass by value because you receive a copy of the caller's object and cannot modify their copy. All Java reference types are always pass by reference because you receive a reference to the caller's object and can directly modify their object.

The fact that you cannot modify the caller's reference has nothing to do with pass by reference and is true in every language that supports pass by reference.

answered 2 years ago Logos #54

Thinking that way is just making things sound more and more complicated. Just simply thinks that the new keyword creates a whole new object thus, when you pass an object from a variable to another variable without the keyword new, you pass the same object.

Assume the operator = means the word "is" in English :

Pokemon a = new Pokemon(); // Pokemon a is a new Pokemon
Pokemon b = a; //Pokemon b is pokemon a

So, if you made any changes towards b, affects a, since b is a or you can think b as an alias for a.

Let's see what happen when we change the operands into primitive variables like int, float, etc. :

int x = 1; // x is 1
int y = x; // y is 1
y = 5 // y is 5

x is an alias for 1, whenever I say "x", it means 1. So, changes towards y will not affect x...

Another analogy :

Suppose that Tommy Spade, Dennis Heart and Jackie Diamond are friends. Tommy calls Jackie "Jack" and Dennis call Jackie "Dia". Let's think Jack and Dia are variables. No matter what, Jackie and Dia is the same entity (object). When Tommy hit Jack's face, Dennis can see the bruise in Dia's face too of course, since Jack and Dia is the same [person].

Primitive values are just primitive. It has no component, just a value, so the above analogy doesn't work on this type of data.

One of the main concept of OOP is abstraction. You don't need to know the details of how a device work to use it, you only need to know how to use it, not how it works. Unless you want to be a researcher, it is fine. Hope my answer helps.

answered 2 years ago Ravi Sanwal #55

There is a very simple way to understand this. Lets's take C++ pass by reference.

#include <iostream>
using namespace std;

class Foo {
    private:
        int x;
    public:
        Foo(int val) {x = val;}
        void foo()
        {
            cout<<x<<endl;
        }
};

void bar(Foo& ref)
{
    ref.foo();
    ref = *(new Foo(99));
    ref.foo();
}

int main()
{
   Foo f = Foo(1);
   f.foo();
   bar(f);
   f.foo();

   return 0;
}

What is the outcome?

1
1
99
99

So, after bar() assigned a new value to a "reference" passed in, it actually changed the one which was passed in from main itself, explaining the last f.foo() call from main printing 99.

Now, lets see what java says.

public class Ref {

    private static class Foo {
        private int x;

        private Foo(int x) {
            this.x = x;
        }

        private void foo() {
            System.out.println(x);
        }
    }

    private static void bar(Foo f) {
        f.foo();
        f = new Foo(99);
        f.foo();
    }

    public static void main(String[] args) {
        Foo f = new Foo(1);
        System.out.println(f.x);
        bar(f);
        System.out.println(f.x);
    }

}

It says:

1
1
99
1

Voilà, the reference of Foo in main that was passed to bar, is still unchanged!

This example clearly shows that java is not the same as C++ when we say "pass by reference". Essentially, java is passing "references" as "values" to functions, meaning java is pass by value.

answered 2 years ago user1767316 #56

In Java only references are passed and are passed by value:

Java arguments are all passed by value (the reference is copied when used by the method) :

In the case of primitive types, Java behaviour is simple: The value is copied in another instance of the primitive type.

In case of Objects, this is the same: Object variables are pointers (buckets) holding only Object’s address that was created using the "new" keyword, and are copied like primitive types.

The behaviour can appear different from primitive types: Because the copied object-variable contains the same address (to the same Object) Object's content/members might still be modified within a method and later access outside, giving the illusion that the (containing) Object itself was passed by reference.

"String" Objects appear to be a perfect counter-example to the urban legend saying that "Objects are passed by reference":

In effect, within a method you will never be able, to update the value of a String passed as argument:

A String Object, holds characters by an array declared final that can't be modified. Only the address of the Object might be replaced by another using "new". Using "new" to update the variable, will not let the Object be accessed from outside, since the variable was initially passed by value and copied.

answered 1 year ago Ahmed Abouhegaza #57

public static void main(String args[]) {

    Point p1 = new Point(1, 1); //This is pointing to a location in memory let's say that the reference is x1=5
    Point p2 = new Point(2, 2); //This is pointing to a location in memory let's say that the reference is x2=6

    // Next we need to pass something to the function, what is it and how we pass it? 
    // There are two references x1,x2 are going to be passed by value
    // Meaning that if x1=5, x2=6 as we mentioned, we are passing 5,6. We are not passing x1,x2
    // That's a big difference. If we are passing x1 and x2, we can change values there inside the trickMe method.
    // but we are passing only two numbers which are 5 and 6.
    trickMe(p1, p2);

    System.out.println(p1); // outputs java.awt.Point[x=1,y=1]
    System.out.println(p2); // outputs java.awt.Point[x=2,y=2]
}

//  Here we received two values which are 5,6.
// This method will create another two references which are x3,x4 for objects arg3,arg4
// arg3 and arg4 are actually same exact objects as p1,p2 with the same memory location. 
// BUT we use x1,x2 to access p1,p2
// AND we use x3,x4 to access arg3,arg4
// x3 is corresponding to x1 and each one of them equal 5. Each one of them means that they are not the same obviously, but have equal values.
// x4 is corresponding to x2 and each one of them equal 6.
// Beautiful, now if we replace x3 with x4,, does this replace  x1 with x2?
// NO THEY ARE TOTALLY INDEPENDENT. x3 and x4 are inside the trickMe Method. they have no acces to x1,x2 at all.
// So, no matter what I did to x3,x4 inside the trickMe method, x1 and x2 in the main method will not change at all.
// They will remain x1=5 and x2=6
public static void trickMe(Point arg3, Point arg4) {
    // Now we have a reference to arg3 which is x3 and it is equal to 5 and a reference to arg4 which is x4 and equal to 6, right?
    // Great! When we say arg3=arg4, we means that make the reference of arg3 which is x3 equals to the reference of arg4 which is x4.
    // Meaning, from this point,, we will make x3=6 instead of 5 and of course x4 is still 6 as it was.
    // We didn't touch niether x1 nor x2, we also can't thouch them inside trickMe method.
    // We only have access to x3 and x4.
    // That's why swapping methods always fail in java if we just put the equal sign "=" to swap.
    // We really have two memory locations which represents two, but with 4 different refernces.
    // Two are in the main method, and another two are in this method
    arg3 = arg4;
}

answered 1 year ago Vivek Kumar #58

Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.

Take the badSwap() method for example:

    public void badSwap(int var1, int
 var2{ int temp = var1; var1 = var2; var2 =
 temp; }

When badSwap() returns, the variables passed as arguments will still hold their original values. The method will also fail if we change the arguments type from int to Object, since Java passes object references by value as well. Now, here is where it gets tricky:

public void tricky(Point arg1, Point   arg2)
{ arg1.x = 100; arg1.y = 100; Point temp = arg1; arg1 = arg2; arg2 = temp; }
public static void main(String [] args) { 

 Point pnt1 = new Point(0,0); Point pnt2
 = new Point(0,0); System.out.println("X:
 " + pnt1.x + " Y: " +pnt1.y);

     System.out.println("X: " + pnt2.x + " Y:
 " +pnt2.y); System.out.println(" ");

     tricky(pnt1,pnt2);
 System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);

     System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); }

If we execute this main() method, we see the following output:

X: 0 Y: 0 X: 0 Y: 0 X: 100 Y: 100 X: 0 Y: 0

The method successfully alters the value ofpnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In themain() method, pnt1 and pnt2 are nothing more than object references. When you passpnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references. Figure 1 below shows two references pointing to the same object after Java passes an object to a method.

Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail. As Figure 2 illustrates, the method references swap, but not the original references. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies.

answered 1 year ago khakishoiab #59

A simple test to check whether a language supports pass-by-reference is simply writing a traditional swap. Can you write a traditional swap(a,b) method/function in Java?

A traditional swap method or function takes two arguments and swaps them such that variables passed into the function are changed outside the function. Its basic structure looks like

(Non-Java) Basic swap function structure

swap(Type arg1, Type arg2) {
    Type temp = arg1;
    arg1 = arg2;
    arg2 = temp;
}

If you can write such a method/function in your language such that calling

Type var1 = ...;
Type var2 = ...;
swap(var1,var2);

actually switches the values of the variables var1 and var2, the language supports pass-by-reference. But Java does not allow such a thing as it supports passing the values only and not pointers or references.

answered 1 year ago mcolak #60

public class Main {

    public static void main(String[] args) {
        Person person = new Person();
        person.setName("Murat");
        System.out.println(person);
        passby(person);
        System.out.println(person);

    }

    public static void passby(Person a){
        //a= new Person(); //if you open this line you will see that reference value change so main reference not change
        a.setName("Kemal");
        System.out.println(a);
    }

    private static class Person {
        String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return getName();
        }
    }
}

answered 1 year ago shiva kumar #61

class Codechef
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        Person p = new Person();
        p.age = 30;
        System.out.println(p.age); //30
        ss(p); //40
        System.out.println(p.age); //40
        yy(p); //20
        System.out.println(p.age); //40
    }
    static void  ss(Person p) {
// Change the value in object then it gets retained.
        p.age = 40;
        System.out.println(p.age);
    }

    static void  yy(Person p) {
// Change the object itself it don't retain. So its pass by value
        p = new Person();
        p.age = 20;
        System.out.println(p.age);
    }
}


class Person {
    int age = 10;   
}

O/p

30 40 40 20 40

So its always the pass by value but if the object instance variables are changed they get retained. If the Object itself is changed then java creates a new object so its not retained.

answered 1 year ago snr #62

The major cornerstone knowledge must be the quoted one,

When an object reference is passed to a method, the reference itself is passed by use of call-by-value. However, since the value being passed refers to an object, the copy of that value will still refer to the same object referred to by its corresponding argument.

Java: A Beginner's Guide, Sixth Edition, Herbert Schildt

answered 1 year ago Taleev Aalam #63

It seems everything is call by value in java as i have tried to understand by the following program

Class-S

class S{
String name="alam";
public void setName(String n){
this.name=n; 
}}

Class-Sample

    public class Sample{
    public static void main(String args[]){
    S s=new S();
    S t=new S();
    System.out.println(s.name);
    System.out.println(t.name);
    t.setName("taleev");
    System.out.println(t.name);
    System.out.println(s.name);
    s.setName("Harry");
    System.out.println(t.name);
    System.out.println(s.name);
    }}

Output

alam

alam

taleev

alam

taleev

harry

As we have define class S with instance variable name with value taleev so for all the objects that we initialize from it will have the name variable with value of taleev but if we change the name's value of any objects then it is changing the name of only that copy of the class(Object) not for every class so after that also when we do System.out.println(s.name) it is printing taleev only we can not change the name's value that we have defined originally, and the value that we are changing is the object's value not the instance variable value so once we have define instance variable we are unable to change it

So i think that is how it shows that java deals with values only not with the references

The memory allocation for the primitive variables can be understood by this

answered 1 year ago Rahul Kumar #64

Java, for sure, without a doubt, is "pass by value". Also, since Java is (mostly) object-oriented and objects work with references, it's easy to get confused and think of it to be "pass by reference"

Pass by value means you pass the value to the method and if the method changes the passed value, the real entity doesn't change. Pass by reference, on the other hand, means a reference is passed to the method, and if the method changes it, the passed object also changes.

In Java, usually when we pass an object to a method, we basically pass the reference of the object as-a-value because that's how Java works; it works with references and addresses as far as Object in the heap goes.

But to test if it is really pass by value or pass by reference, you can use a primitive type and references:

@Test
public void sampleTest(){
    int i = 5;
    incrementBy100(i);
    System.out.println("passed ==> "+ i);
    Integer j = new Integer(5);
    incrementBy100(j);
    System.out.println("passed ==> "+ j);
}
/**
 * @param i
 */
private void incrementBy100(int i) {
    i += 100;
    System.out.println("incremented = "+ i);
}

The output is:

incremented = 105
passed ==> 5
incremented = 105
passed ==> 5

So in both cases, whatever happens inside the method doesn't change the real Object, because the value of that object was passed, and not a reference to the object itself.

But when you pass a custom object to a method, and the method and changes it, it will change the real object too, because even when you passed the object, you passed it's reference as a value to the method. Let's try another example:

@Test
public void sampleTest2(){
    Person person = new Person(24, "John");
    System.out.println(person);
    alterPerson(person);
    System.out.println(person);
}

/**
 * @param person
 */
private void alterPerson(Person person) {
    person.setAge(45);
    Person altered = person;
    altered.setName("Tom");
}

private static class Person{
    private int age;
    private String name; 

    public Person(int age, String name) {
        this.age=age;
        this.name =name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Person [age=");
        builder.append(age);
        builder.append(", name=");
        builder.append(name);
        builder.append("]");
        return builder.toString();
    }

}

In this case, the output is:

Person [age=24, name=John]
Person [age=45, name=Tom]

answered 1 year ago Raja #65

I tried to simplify the examples above, keeping only the essense of the problem. Let me present this as a story that is easy to remember and apply correctly. The story goes like this: You have a pet dog, Jimmy, whose tail is 12 inches long. You leave it with a vet for a few weeks while you are travelling abroad.

The vet doesn't like the long tail of Jimmy, so he wants to cut it by half. But being a good vet, he knows that he has no right to mutilate other people's dogs. So he first makes a clone of the dog (with the new key word) and cuts the tail of the clone. When the dog finally returns to you, it has the original 12 inch tail in tact. Happy ending !

The next time you travel, you take the dog, unwittingly, to a wicked vet. He is also a hater of long tails, so he cuts it down to a miserable 2 inches. But he does this to your dear Jimmy, not a clone of it. When you return, you are shocked to see Jimmy pathetically wagging a 2 inch stub.

Moral of the story: When you pass on your pet, you are giving away whole and unfettered custody of the pet to the vet. He is free to play any kind of havoc with it. Passing by value, by reference, by pointer are all just technical wrangling. Unless the vet clones it first, he ends up mutilating the original dog.

public class Doggie {

    public static void main(String...args) {
        System.out.println("At the owner's home:");
        Dog d = new Dog(12);
        d.wag();
        goodVet(d);
        System.out.println("With the owner again:)");
        d.wag();
        badVet(d);
        System.out.println("With the owner again(:");
        d.wag();
    }

    public static void goodVet (Dog dog) {
        System.out.println("At the good vet:");
        dog.wag();
        dog = new Dog(12); // create a clone
        dog.cutTail(6);    // cut the clone's tail
        dog.wag();
    }

    public static void badVet (Dog dog) {
        System.out.println("At the bad vet:");
        dog.wag();
        dog.cutTail(2);   // cut the original dog's tail
        dog.wag();
    }    
}

class Dog {

    int tailLength;

    public Dog(int originalLength) {
        this.tailLength = originalLength;
    }

    public void cutTail (int newLength) {
        this.tailLength = newLength;
    }

    public void wag()  {
        System.out.println("Wagging my " +tailLength +" inch tail");
    }
}

Output:
At the owner's home:
Wagging my 12 inch tail
At the good vet:
Wagging my 12 inch tail
Wagging my 6 inch tail
With the owner again:)
Wagging my 12 inch tail
At the bad vet:
Wagging my 12 inch tail
Wagging my 2 inch tail
With the owner again(:
Wagging my 2 inch tail

answered 11 months ago Basheer AL-MOMANI #66

Unlike some other languages, Java does not allow you to choose pass-by-value or pass-by-reference

all arguments are passed by value.

A method call can pass two types of valuesto a method

  • copies of primitive values (e.g., values of type int and double)
  • copies of references to objects.

Objects themselves cannot be passed to methods. When a method modifies a primitive-type parameter, changes to the parameter have no effect on the original argument value in the calling method.

This is also true for reference-type parameters. If you modify a reference-type parameter so that it refers to another object, only the parameter refers to the new object—the reference stored in the caller’s variable still refers to the original object.

References: Java™ How To Program (Early Objects), Tenth Edition

answered 10 months ago Himanshu arora #67

Java is a call by value.

How it works.

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

  • If it's a primitive data type these bits contain the value of the primitive data type itself, That's why if we change the value of header inside the method then it does not reflect the changes outside.

  • If it's an object data type like Foo foo=new Foo() then in this case copy of the address of the object passes like file shortcut , suppose we have a text file abc.txt at C:\desktop and suppose we make shortcut of the same file and put this inside C:\desktop\abc-shortcut so when you access the file from C:\desktop\abc.txt and write 'Stack Overflow' and close the file and again you open the file from shortcut then you write ' is the largest online community for programmers to learn' then total file change will be 'Stack Overflow is the largest online community for programmers to learn' which means it doesn't matter from where you open the file , each time we were accessing the same file , here we can assume Foo as a file and suppose foo stored at 123hd7h(original address like C:\desktop\abc.txt ) address and 234jdid(copied address like C:\desktop\abc-shortcut which actually contains the original address of the file inside) .. So for better understanding make shortcut file and feel...

answered 6 months ago Sup #68

Java is pass by value.

There are already great answers on this thread. Somehow, I was never clear on pass by value/reference with respect to primitive data types and with respect to objects. Therefore, I tested it out for my satisfaction and clarity with the following piece of code; might help somebody seeking similar clarity:

class Test    {

public static void main (String[] args) throws java.lang.Exception
{
    // Primitive type
    System.out.println("Primitve:");
    int a = 5;
    primitiveFunc(a);
    System.out.println("Three: " + a);    //5

    //Object
    System.out.println("Object:");
    DummyObject dummyObject = new DummyObject();
    System.out.println("One: " + dummyObject.getObj());    //555
    objectFunc(dummyObject);
    System.out.println("Four: " + dummyObject.getObj());    //666 (555 if line in method uncommented.)

}

private static void primitiveFunc(int b)    {
    System.out.println("One: " + b);    //5
    b = 10;
    System.out.println("Two:" + b);    //10
}

private static void objectFunc(DummyObject b)   {
    System.out.println("Two: " + b.getObj());    //555
    //b = new DummyObject();
    b.setObj(666);
    System.out.println("Three:" + b.getObj());    //666
}

}

class DummyObject   {
    private int obj = 555;
    public int getObj() { return obj; }
    public void setObj(int num) { obj = num; }
}

If the line b = new DummyObject() is uncommented, the modifications made thereafter are made on a new object, a new instantiation. Hence, it is not reflected in the place where the method is called from. However, otherwise, the change is reflected as the modifications are only made on a "reference" of the object, i.e - b points to the same dummyObject.

Illustrations in one of the answers in this thread (https://stackoverflow.com/a/12429953/4233180) can help gain a deeper understanding.

answered 5 months ago Raj S. Rusia #69

One of the biggest confusion in Java programming language is whether Java is Pass by Value or Pass by Reference.

First of all, we should understand what is meant by pass by value or pass by reference.

Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that’s why it’s called pass by value.

Pass by Reference: An alias or reference to the actual parameter is passed to the method, that’s why it’s called pass by reference.

Let’s say we have a class Balloon like below.

public class Balloon {

    private String color;

    public Balloon(){}

    public Balloon(String c){
        this.color=c;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

And we have a simple program with a generic method to swap two objects, the class looks like below.

public class Test {

    public static void main(String[] args) {

        Balloon red = new Balloon("Red"); //memory reference 50
        Balloon blue = new Balloon("Blue"); //memory reference 100

        swap(red, blue);
        System.out.println("red color="+red.getColor());
        System.out.println("blue color="+blue.getColor());

        foo(blue);
        System.out.println("blue color="+blue.getColor());

    }

    private static void foo(Balloon balloon) { //baloon=100
        balloon.setColor("Red"); //baloon=100
        balloon = new Balloon("Green"); //baloon=200
        balloon.setColor("Blue"); //baloon = 200
    }

    //Generic swap method
    public static void swap(Object o1, Object o2){
        Object temp = o1;
        o1=o2;
        o2=temp;
    }
}

When we execute the above program, we get following output.

red color=Red
blue color=Blue
blue color=Red

If you look at the first two lines of the output, it’s clear that swap method didn’t work. This is because Java is passed by value, this swap() method test can be used with any programming language to check whether it’s pass by value or pass by reference.

Let’s analyze the program execution step by step.

Balloon red = new Balloon("Red");
Balloon blue = new Balloon("Blue");

When we use the new operator to create an instance of a class, the instance is created and the variable contains the reference location of the memory where the object is saved. For our example, let’s assume that “red” is pointing to 50 and “blue” is pointing to 100 and these are the memory location of both Balloon objects.

Now when we are calling swap() method, two new variables o1 and o2 are created pointing to 50 and 100 respectively.

So below code snippet explains what happened in the swap() method execution.

public static void swap(Object o1, Object o2){ //o1=50, o2=100
    Object temp = o1; //temp=50, o1=50, o2=100
    o1=o2; //temp=50, o1=100, o2=100
    o2=temp; //temp=50, o1=100, o2=50
} //method terminated

Notice that we are changing values of o1 and o2 but they are copies of “red” and “blue” reference locations, so actually, there is no change in the values of “red” and “blue” and hence the output.

If you have understood this far, you can easily understand the cause of confusion. Since the variables are just the reference to the objects, we get confused that we are passing the reference so Java is passed by reference. However, we are passing a copy of the reference and hence it’s pass by value. I hope it clears all the doubts now.

Now let’s analyze foo() method execution.

private static void foo(Balloon balloon) { //baloon=100
    balloon.setColor("Red"); //baloon=100
    balloon = new Balloon("Green"); //baloon=200
    balloon.setColor("Blue"); //baloon = 200
}

The first line is the important one when we call a method the method is called on the Object at the reference location. At this point, the balloon is pointing to 100 and hence it’s color is changed to Red.

In the next line, balloon reference is changed to 200 and any further methods executed are happening on the object at memory location 200 and not having any effect on the object at memory location 100. This explains the third line of our program output printing blue color=Red.

I hope above explanation clear all the doubts, just remember that variables are references or pointers and its copy is passed to the methods, so Java is always passed by value. It would be more clear when you will learn about Heap and Stack memory and where different objects and references are stored.

answered 5 months ago Hussein Terek #70

In java, arguments are always passed by value regardless of the original variable type. Each time a method is invoked, the following happens:

  • A copy for each argument is created in the stack memory and the copy version is passed to the method.
  • If the original variable type is primitive, then simply, a copy of the variable is created inside the stack memory and then passed to the method.
  • If the original type is not primitive, then a new reference is created inside the stack memory which points to the actual object data and the new reference is then passed to the method, (at this stage, 2 references are pointing to the same object data).

Inside the method, you can modify the data of the referenced object but you can't modify the reference itself.

This tutorial explains well why java is always pass by value.

answered 4 months ago NAGHMAAN MOHASEEN #71

Java is strictly passed by value

When I say pass by value it means whenever caller has invoked the callee the arguments(ie: the data to be passed to the other function) is copied and placed in the formal parameters (callee's local variables for receiving the input). Java makes data communications from one function to other function only in a pass by value environment.

An important point would be to know that even C language is strictly passed by value only:
ie: Data is copied from caller to the callee and more ever the operation performed by the callee are on the same memory location and what we pass them is the address of that location that we obtain from (&) operator and the identifier used in the formal parameters are declared to be a pointer variable (*) using which we can get inside the memory location for accessing the data in it.

Hence here the formal parameter is nothing but mere aliases for that location. And any modifications done on that location is visible where ever that scope of the variable (that identifies that location) is alive.

In Java, there is no concept of pointers (ie: there is nothing called a pointer variable), although we can think of reference variable as a pointer technically in java we call it as a handle. The reason why we call the pointer to an address as a handle in java is because a pointer variable is capable of performing not just single dereferencing but multiple dereferencing for example: int *p; in P means p points to an integer and int **p; in C means p is pointer to a pointer to an integer we dont have this facility in Java, so its absolutely correct and technically legitimate to say it as an handle, also there are rules for pointer arithmetic in C. Which allows performing arithmetic operation on pointers with constraints on it.

In C we call such mechanism of passing address and receiving them with pointer variables as pass by reference since we are passing their addresses and receiving them as pointer variable in formal parameter but at the compiler level that address is copied into pointer variable (since data here is address even then its data ) hence we can be 100% sure that C is Strictly passed by value (as we are passing data only)

(and if we pass the data directly in C we call that as pass by value.)

In java when we do the same we do it with the handles; since they are not called pointer variables like in (as discussed above) even though we are passing the references we cannot say its pass by reference since we are not collecting that with a pointer variable in Java.

Hence Java strictly use pass by value mechanism

answered 3 months ago Learner #72

Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.

answered 2 months ago Premraj #73

  • passed by reference : caller and callee use same variable for parameter.

  • passed by value : caller and callee have two independent variables with same value.

  • Java uses pass by value
    • When passing primitive data, it copies the value of primitive data type.
    • When passing object, it copies the address of object and passes to callee method variable.

Example using primitive data type:

public class PassByValuePrimitive {
    public static void main(String[] args) {
        int i=5;
        System.out.println(i);  //prints 5
        change(i);
        System.out.println(i);  //prints 5
    }


    private static void change(int i) {
        System.out.println(i);  //prints 5
        i=10;
        System.out.println(i); //prints 10

    }
}

Example using object:

public class PassByValueObject {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("prem");
        list.add("raj");
        new PassByValueObject().change(list);
        System.out.println(list); // prints [prem, raj, ram]

    }


    private  void change(List list) {
        System.out.println(list.get(0)); // prem
        list.add("ram");
        list=null;
        System.out.println(list.add("bheem")); //gets NullPointerException
    }
}

answered 2 weeks ago Felypp Oliveira #74

This is the best way to answer the question imo...

First, we must understand that, in Java, the parameter passing behavior...

public void foo()
{
  Object obj = new Object();

  bar(obj);
}

public void bar(Object param)
{
  // some code in bar...
}

is exactly the same as...

public void foo()
{
  Object obj = new Object();

  Object param = obj;

  // some code in bar...
}

not considering stack locations, which aren't relevant in this discussion.

So, in fact, what we're looking for in Java is how variable assigment works, which could be classified, imo, as mutable or immutable assignment (pass-by-reference or pass-by-value, respectivelly), when an assignment does change or does not change a previous assignment.

Having this in mind, we can run some Java code to find the answer by ourselves.

public class Program
{
  public static class MyInteger
  {
    public int value;

    public MyInteger(int number)
    {
      this.value = number;
    }
  }

  public static void main(String[] args)
  {
    MyInteger obj1, obj2, obj3;

    System.out.println("[1] Create some new MyInteger objects...");

    obj1 = new MyInteger(9);
    System.out.println("obj1 = new  -> obj1 value: " + obj1.value);

    obj2 = new MyInteger(8);
    System.out.println("obj2 = new  -> obj2 value: " + obj2.value);

    obj3 = new MyInteger(7);
    System.out.println("obj3 = new  -> obj3 value: " + obj3.value);

    System.out.println("");

    System.out.println("[2] Now lets assign some of them to another object...");

    obj3 = obj2;
    System.out.println("obj3 = obj2 -> obj3 value: " + obj3.value);

    obj2 = obj1;
    System.out.println("obj2 = obj1 -> obj2 value: " + obj2.value);

    System.out.println("");

    System.out.println("[3] So, if obj3 = obj2 and obj2 = obj1, what is the value of obj3?");

    System.out.println("obj3        -> obj3 value: " + obj3.value);

    System.out.println("");

    System.out.println("[4] Lets assign to obj1 value the number 1...");

    obj1.value = 1;
    System.out.println("obj1        -> obj1 value: " + obj1.value);

    System.out.println("");

    System.out.println("[5] So, if obj2 = obj1, what is the value of obj2?");

    System.out.println("obj2        -> obj2 value: " + obj2.value);

    System.out.println("");

    System.out.println("[6] end.");
  }
}

That's the output of my run:

[1] Create some new MyInteger objects...
obj1 = new  -> obj1 value: 9
obj2 = new  -> obj2 value: 8
obj3 = new  -> obj3 value: 7

[2] Now lets assign some of them to another object...
obj3 = obj2 -> obj3 value: 8
obj2 = obj1 -> obj2 value: 9

[3] So, if obj3 = obj2 and obj2 = obj1, what is the value of obj3?
obj3        -> obj3 value: 8

[4] Lets assign to obj1 value the number 1...
obj1        -> obj1 value: 1

[5] So, if obj2 = obj1, what is the value of obj2?
obj2        -> obj2 value: 1

[6] end.

You can see in [3] that assigning to obj2 the variable obj1 doesn't change the previous assignment of obj2 to obj3, so they were immutable assignments (pass-by-value) or copy of variables. But the assignment of a new value to obj1 in [4] just changed the value of obj2 in [5], which looks like a mutable assignment (pass-by-reference), not like a copy. So how could this happen? I think it's the confusing point to most people, but still Java did the variable copy. The point is... in Java, the content of a primitive type variable is different from the content of a complex type variable.

A single instance of a complex type can allocate a good amount of the available memory, so Java would end up all the memory really fast doing content copies through variable assignment... and it would keep the CPU much more busy too. To avoid this, a complex type variable doesn't hold the object instance itself... it holds the memory address where the instance is stored, as the cost of doing address copy is much lower. So, after [2], obj1 and obj2 are two distinct copies of the same memory address that holds the object instance. Thus, updating the object in this address through one variable will change the result you'll get on the other variable just like in [4] and [5], but still these variables are distinct copies through what I call immutable assignment.

Hope it's clear now.

answered 4 days ago Kamil Tomasz Jarmusik #75

To simplify the problem:
addr - address of the memory cell, or reference.

Java pass-by-reference because:

a; // => addrA(valueA);
function (a) {// => newAddrA(addrA(valueA));
    // change "a in function" affects the change of the value "a outside function" 
   // because the newAddrA points to addrA with valueA.
    b; // => addrB(valueB)
    a = b; // => newAddrA(addrB(valueB));
    // change "a in function" does not affect the value of "a outside function" 
   // because now newAddrA points to addrB with valueB.
}

C ++ pass-by-value because:

a; // => addrA(valueA);
function (a) {// => newAddrA(valueCloneA);
    // change "a in function" does not affect the value of "a outside function" 
   // outside the function, because the newAddrA with new value valueCloneA;
    b; // => addrB(valueB);
    a = b; // => newAddrA(addrB(valueB));
}

comments powered by Disqus