By user4315


2008-09-02 20:14:29 8 Comments

I always thought Java uses pass-by-reference.

However, I've seen a couple of blog posts (for example, this blog) that claim that it isn't (the blog post says that Java uses pass-by-value).

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

What is the explanation?

30 comments

@Ari 2020-07-28 17:46:17

For people who are familiar with python and javascript: passing objects in java is very similar to passing objects those languages, which is known as one of the following:

Call by sharing, call by object-sharing, call by object reference or passing references by value or passing object references.

@Boris Fain 2020-06-07 04:04:55

Java as each programming language passes parameters by value only, in case of objects it's send value of reference, and with primitive it sends value of primitive itself, that people mean when they say it pass by reference,

@Michael 2018-04-03 23:48:10

Unlike some other languages, Java does not allow you to choose between pass-by-value and pass-by-reference—all arguments are passed by value. A method call can pass two types of values to a method—copies of primitive values (e.g., values of int and double) and copies of references to objects.

When a method modifies a primitive-type parameter, changes to the parameter have no effect on the original argument value in the calling method.

When it comes to objects, objects themselves cannot be passed to methods. So we pass the reference(address) of the object. We can manipulate the original object using this reference.

How Java creates and stores objects: When we create an object we store the object’s address in a reference variable. Let's analyze the following statement.

Account account1 = new Account();

“Account account1” is the type and name of the reference variable, “=” is the assignment operator, “new” asks for the required amount of space from the system. The constructor to the right of keyword new which creates the object is called implicitly by the keyword new. Address of the created object(result of right value, which is an expression called "class instance creation expression") is assigned to the left value (which is a reference variable with a name and a type specified) using the assign operator.

Although an object’s reference is passed by value, a method can still interact with the referenced object by calling its public methods using the copy of the object’s reference. Since the reference stored in the parameter is a copy of the reference that was passed as an argument, the parameter in the called method and the argument in the calling method refer to the same object in memory.

Passing references to arrays, instead of the array objects themselves, makes sense for performance reasons. Because everything in Java is passed by value, if array objects were passed, a copy of each element would be passed. For large arrays, this would waste time and consume considerable storage for the copies of the elements.

In the image below you can see we have two reference variables(These are called pointers in C/C++, and I think that term makes it easier to understand this feature.) in the main method. Primitive and reference variables are kept in stack memory(left side in images below). array1 and array2 reference variables "point" (as C/C++ programmers call it) or reference to a and b arrays respectively, which are objects (values these reference variables hold are addresses of objects) in heap memory (right side in images below).

Pass by value example 1

If we pass the value of array1 reference variable as an argument to the reverseArray method, a reference variable is created in the method and that reference variable starts pointing to the same array (a).

public class Test
{
    public static void reverseArray(int[] array1)
    {
        // ...
    }

    public static void main(String[] args)
    {
        int[] array1 = { 1, 10, -7 };
        int[] array2 = { 5, -190, 0 };

        reverseArray(array1);
    }
}

Pass by value example 2

So, if we say

array1[0] = 5;

in reverseArray method, it will make a change in array a.

We have another reference variable in reverseArray method (array2) that points to an array c. If we were to say

array1 = array2;

in reverseArray method, then the reference variable array1 in method reverseArray would stop pointing to array a and start pointing to array c (Dotted line in second image).

If we return value of reference variable array2 as the return value of method reverseArray and assign this value to reference variable array1 in main method, array1 in main will start pointing to array c.

So let's write all the things we have done at once now.

public class Test
{
    public static int[] reverseArray(int[] array1)
    {
        int[] array2 = { -7, 0, -1 };

        array1[0] = 5; // array a becomes 5, 10, -7

        array1 = array2; /* array1 of reverseArray starts
          pointing to c instead of a (not shown in image below) */
        return array2;
    }

    public static void main(String[] args)
    {
        int[] array1 = { 1, 10, -7 };
        int[] array2 = { 5, -190, 0 };

        array1 = reverseArray(array1); /* array1 of 
         main starts pointing to c instead of a */
    }
}

enter image description here

And now that reverseArray method is over, its reference variables(array1 and array2) are gone. Which means we now only have the two reference variables in main method array1 and array2 which point to c and b arrays respectively. No reference variable is pointing to object (array) a. So it is eligible for garbage collection.

You could also assign value of array2 in main to array1. array1 would start pointing to b.

@Sanjeev 2019-01-25 21:37:30

There are already great answers that cover this. I wanted to make a small contribution by sharing a very simple example (which will compile) contrasting the behaviors between Pass-by-reference in c++ and Pass-by-value in Java.

A few points:

  1. The term "reference" is a overloaded with two separate meanings. In Java it simply means a pointer, but in the context of "Pass-by-reference" it means a handle to the original variable which was passed in.
  2. Java is Pass-by-value. Java is a descendent of C (among other languages). Before C, several (but not all) earlier languages like FORTRAN and COBOL supported PBR, but C did not. PBR allowed these other languages to make changes to the passed variables inside sub-routines. In order to accomplish the same thing (i.e. change the values of variables inside functions), C programmers passed pointers to variables into functions. Languages inspired by C, such as Java, borrowed this idea and continue to pass pointer to methods as C did, except that Java calls its pointers References. Again, this is a different use of the word "Reference" than in "Pass-By-Reference".
  3. C++ allows Pass-by-reference by declaring a reference parameter using the "&" character (which happens to be the same character used to indicate "the address of a variable" in both C and C++). For example, if we pass in a pointer by reference, the parameter and the argument are not just pointing to the same object. Rather, they are the same variable. If one gets set to a different address or to null, so does the other.
  4. In the C++ example below I'm passing a pointer to a null terminated string by reference. And in the Java example below I'm passing a Java reference to a String (again, the same as a pointer to a String) by value. Notice the output in the comments.

C++ pass by reference example:

using namespace std;
#include <iostream>

void change (char *&str){   // the '&' makes this a reference parameter
    str = NULL;
}

int main()
{
    char *str = "not Null";
    change(str);
    cout<<"str is " << str;      // ==>str is <null>
}

Java pass "a Java reference" by value example

public class ValueDemo{

    public void change (String str){
        str = null;
    }

     public static void main(String []args){
        ValueDemo vd = new ValueDemo();
        String str = "not null";
        vd.change(str);
        System.out.println("str is " + str);    // ==> str is not null!!
                                                // Note that if "str" was
                                                // passed-by-reference, it
                                                // WOULD BE NULL after the
                                                // call to change().
     }
}

EDIT

Several people have written comments which seem to indicate that either they are not looking at my examples or they don't get the c++ example. Not sure where the disconnect is, but guessing the c++ example is not clear. I'm posting the same example in pascal because I think pass-by-reference looks cleaner in pascal, but I could be wrong. I might just be confusing people more; I hope not.

In pascal, parameters passed-by-reference are called "var parameters". In the procedure setToNil below, please note the keyword 'var' which precedes the parameter 'ptr'. When a pointer is passed to this procedure, it will be passed by reference. Note the behavior: when this procedure sets ptr to nil (that's pascal speak for NULL), it will set the argument to nil--you can't do that in Java.

program passByRefDemo;
type 
   iptr = ^integer;
var
   ptr: iptr;

   procedure setToNil(var ptr : iptr);
   begin
       ptr := nil;
   end;

begin
   new(ptr);
   ptr^ := 10;
   setToNil(ptr);
   if (ptr = nil) then
       writeln('ptr seems to be nil');     { ptr should be nil, so this line will run. }
end.

EDIT 2

Some excerpts from "THE Java Programming Language" by Ken Arnold, James Gosling (the guy who invented Java), and David Holmes, chapter 2, section 2.6.5

All parameters to methods are passed "by value". In other words, values of parameter variables in a method are copies of the invoker specified as arguments.

He goes on to make the same point regarding objects . . .

You should note that when the parameter is an object reference, it is the object reference-not the object itself-that is passed "by value".

And towards the end of the same section he makes a broader statement about java being only pass by value and never pass by reference.

The Java programming language does not pass objects by reference; it passes object references by value. Because two copies of the same reference refer to the same actual object, changes made through one reference variable are visible through the other. There is exactly one parameter passing mode-pass by value-and that helps keep things simple.

This section of the book has a great explanation of parameter passing in Java and of the distinction between pass-by-reference and pass-by-value and it's by the creator of Java. I would encourage anyone to read it, especially if you're still not convinced.

I think the difference between the two models is very subtle and unless you've done programming where you actually used pass-by-reference, it's easy to miss where two models differ.

I hope this settles the debate, but probably won't.

EDIT 3

I might be a little obsessed with this post. Probably because I feel that the makers of Java inadvertently spread misinformation. If instead of using the word "reference" for pointers they had used something else, say dingleberry, there would've been no problem. You could say, "Java passes dingleberries by value and not by reference", and nobody would be confused.

That's the reason only Java developers have issue with this. They look at the word "reference" and think they know exactly what that means, so they don't even bother to consider the opposing argument.

Anyway, I noticed a comment in an older post, which made a balloon analogy which I really liked. So much so that I decided to glue together some clip-art to make a set of cartoons to illustrate the point.

Passing a reference by value--Changes to the reference are not reflected in the caller's scope, but the changes to the object are. This is because the reference is copied, but the both the original and the copy refer to the same object. Passing Object references By Value

Pass by reference--There is no copy of the reference. Single reference is shared by both the caller and the function being called. Any changes to the reference or the Object's data are reflected in the caller's scope. Pass by reference

EDIT 4

I have seen posts on this topic which describe the low level implementation of parameter passing in Java, which I think is great and very helpful because it makes an abstract idea concrete. However, to me the question is more about the behavior described in the language specification than about the technical implementation of the behavior. This is an exerpt from the Java Language Specification, section 8.4.1 :

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.

Which means, java creates a copy of the passed parameters before executing a method. Like most people who studied compilers in college, I used "The Dragon Book" which is THE compilers book. It has a good description of "Call-by-value" and "Call-by-Reference" in Chapter 1. The Call-by-value description matches up with Java Specs exactly.

Back when I studied compilers-in the 90's, I used the first edition of the book from 1986 which pre-dated Java by about 9 or 10 years. However, I just ran across a copy of the 2nd Eddition from 2007 which actually mentions Java! Section 1.6.6 labeled "Parameter Passing Mechanisms" describes parameter passing pretty nicely. Here is an excerpt under the heading "Call-by-value" which mentions Java:

In call-by-value, the actual parameter is evaluated (if it is an expression) or copied (if it is a variable). The value is placed in the location belonging to the corresponding formal parameter of the called procedure. This method is used in C and Java, and is a common option in C++ , as well as in most other languages.

@Saranga kapilarathna 2020-03-13 04:45:16

Please read this.

Many programming languages allow passing parameters by reference or by value. In Java, we can only pass parameters by value. This imposes some limits and also raises questions. For instance, if the parameter value is changed in the method, what happens to the value following method execution? You may also wonder how Java manages object values in the memory heap. This Java Challenger helps you resolve these and other common questions about object references in Java.

For the more:

https://www.javaworld.com/article/3512039/does-java-pass-by-reference-or-pass-by-value.html

@Mr.Robot 2020-02-09 21:30:03

I see that all answers contain the same: pass by value. However, a recent Brian Goetz update on project Valhalla actually answers it differently:

Indeed, it is a common “gotcha” question about whether Java objects are passed by value or by reference, and the answer is “neither”: object references are passed by value.

You can read more here: State of Valhalla. Section 2: Language Model

Edit: Brian Goetz is Java Language Architect, leading such projects as Project Valhalla and Project Amber.

@Sanjeev 2020-02-20 22:24:38

Object references (i.e. pointers) are passed by value and primitives are also passed by value. Meaning everything is always passed by value. I think the operative term here is Pass-by-value.

@Mr.Robot 2020-04-02 16:28:05

I think Java Language Architect, who is leading Project Amber and Project Valhalla is a credible source to claim that it is not pass by value.

@Sanjeev 2020-04-02 18:17:58

First, I don't think he's more credible than James Gosling, the creator of Java who clearly state in his book, "THE Java Programming Language", that Java is indeed Pass-by-value (Chapter 2, section 2.6.5). Second, although Goetz says it's neither PBV or PBR, he then goes on to say that references are PASSED BY VALUE, thereby contradicting himself. If you know Java, you also know that primitives are also PASSED BY VALUE. Since everything in Java is passed by value, Java is a PASS BY VALUE language.

@Sanjeev 2020-04-02 18:49:52

Other sources who are way more credible than Goetz are Aho, Lam, Sethi, and Ullman who are well known for their book "Compilers: Principles, Techniques, and Tools", the standard college text book for compiler construction. The 2nd eddition section 1.6.6 of this book also states that Java is Pass-by-value.

@Stephen C 2020-04-05 11:40:51

And the most relevant reference of all is the Java Language Specification which states "The effect of this is to assign the argument values to corresponding freshly created parameter variables of the method". (15.12.4.5). Note that it is avoiding the terminological confusion by not saying "pass by ..." at all. (FWIW, I disagree with the Goetz's characterization of "pass by value" and "pass references by value" as being semantically different. And I agree that he is contradicting himself.)

@user1767316 2016-07-24 08:29:59

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 good counter-example to the urban legend saying that "Objects are passed by reference":

In effect, using 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.

@mondlos 2020-01-17 17:37:37

TL;DR: It's like passing a pointer in C, so it's pass-by-value and you can change the public and mutable members of the object the caller's variable is pointing to.

Let's define the terms first:

  1. pass-by-value: You can not change the callers variable because only it's value is passed.

  2. pass-by-reference: You can change the callers variable because an alias (l-value reference) to the variable is passed.

Ok, so in Java and Python pointers are essentially called variables. So if you pass a Java/Python variable to a method/function, you are passing a way to find it's location in memory.

You cannot change which object the callers function is referencing/pointing to but you can change the object's value. Java/Python are pass-by-value, but the special semantics of them allow you to change the underlying object anyway by (implicit) dereferencing of the variable/pointer.

@Himanshu arora 2017-04-08 05:51:29

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

@Eng.Fouad 2012-09-14 18:22:55

Java always passes arguments by value, NOT by reference.


Let me explain this through an example:

public class Main {

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

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

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

}

I will explain this in steps:

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

    Foo f = new Foo("f");
    

    enter image description here

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

    public static void changeReference(Foo a)
    

    enter image description here

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

    changeReference(f);
    

    enter image description here

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

    Foo b = new Foo("b");
    

    enter image description here

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

    enter image description here

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

    enter image description here

  7. c.setAttribute("c"); will change the attribute of the object that reference c points to it, and it's 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 :)

@DeC 2019-11-05 03:25:23

A: 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 of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 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.

enter image description here
Figure 1. After being passed to a method, an object will have at least two references

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

@Rose 2019-09-21 08:09:07

I think this simple explanation might help you understand as I wanted to understand this same thing when I was struggling through this.

When you pass a primitive data to a function call it's content is being copied to the function's argument and when you pass an object it's reference is being copied to the function's argument. Speaking of object, you can't change the copied reference-the argument variable is referencing to in the calling function.

Consider this simple example, String is an object in java and when you change the content of a string the reference variable will now point to some new reference as String objects are immutable in java.

String name="Mehrose";  // name referencing to 100

ChangeContenet(String name){
 name="Michael"; // refernce has changed to 1001

} 
System.out.print(name);  //displays Mehrose

Fairly simple because as I mentioned you are not allowed to change the copied reference in the calling function. But the problem is with the array when you pass an array of String/Object. Let us see.

String names[]={"Mehrose","Michael"};

changeContent(String[] names){
  names[0]="Rose";
  names[1]="Janet"

}

System.out.println(Arrays.toString(names)); //displays [Rose,Janet]

As we said that we can't change the copied reference in the function call and we also have seen in the case of a single String object. The reason is names[] variable referencing to let's say 200 and names[0] referencing to 205 and so on. You see we didn't change the names[] reference it still points to the old same reference still after the function call but now names[0] and names[1] reference has been changed. We Still stand on our definition that we can't change the reference variable's reference so we didn't.

The same thing happens when you pass a Student object to a method and you are still able to change the Student name or other attributes, the point is we are not changing the actual Student object rather we are changing the contents of it

You can't do this

Student student1= new Student("Mehrose");

changeContent(Student Obj){
 obj= new Student("Michael") //invalid
 obj.setName("Michael")  //valid

}

@natwar kumar 2019-07-27 03:56:02

public class Test {

    static class Dog {
        String name;

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Dog other = (Dog) obj;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            return true;
        }

        public String getName() {
            return name;
        }

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

        Dog(String sd) {
            this.name = sd;
        }
    }
    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
        Dog aDog = new Dog("Max");

        // we pass the object to foo
        foo(aDog);
        Dog oldDog = aDog;

        System.out.println(" 1: " + aDog.getName().equals("Max")); // false
        System.out.println(" 2 " + aDog.getName().equals("huahua")); // false
        System.out.println(" 3 " + aDog.getName().equals("moron")); // true
        System.out.println(" 4 " + " " + (aDog == oldDog)); // true

        // part2
        Dog aDog1 = new Dog("Max");

        foo(aDog1, 5);
        Dog oldDog1 = aDog;

        System.out.println(" 5 : " + aDog1.getName().equals("huahua")); // true
        System.out.println(" part2 : " + (aDog1 == oldDog1)); // false

        Dog oldDog2 = foo(aDog1, 5, 6);
        System.out.println(" 6 " + (aDog1 == oldDog2)); // true
        System.out.println(" 7 " + (aDog1 == oldDog)); // false
        System.out.println(" 8 " + (aDog == oldDog2)); // false
    }

    /**
     * 
     * @param d
     */
    public static void foo(Dog d) {
        System.out.println(d.getName().equals("Max")); // true

        d.setName("moron");

        d = new Dog("huahua");
        System.out.println(" -:-  " + d.getName().equals("huahua")); // true
    }

    /**
     * 
     * @param d
     * @param a
     */
    public static void foo(Dog d, int a) {
        d.getName().equals("Max"); // true

        d.setName("huahua");
    }

    /**
     * 
     * @param d
     * @param a
     * @param b
     * @return
     */
    public static Dog foo(Dog d, int a, int b) {
        d.getName().equals("Max"); // true
        d.setName("huahua");
        return d;
    }
}

The sample code to demonstrate the impact of changes to the object at different functions .

@grindlewald 2019-08-22 19:47:09

First let's understand Memory allocation in Java: Stack and Heap are part of Memory that JVM allocates for different purposes. The stack memory is pre-allocated to thread, when it is created, therefore, a thread cannot access the Stack of other thread. But Heap is available to all threads in a program.

For a thread, Stack stores all local data, metadata of program, primitive type data and object reference. And, Heap is responsible for storage of actual object.

Book book = new Book("Effective Java");

In the above example, the reference variable is "book" which is stored in stack. The instance created by new operator -> new Book("Effective Java") is stored in Heap. The ref variable "book" has address of the object allocated in Heap. Let's say the address is 1001.

enter image description here

Consider passing a primitive data type i.e. int, float, double etc.

public class PrimitiveTypeExample { 
    public static void main(string[] args) {
       int num = 10;
       System.out.println("Value before calling method: " + num);
       printNum(num);
       System.out.println("Value after calling method: " + num);
    }
    public static void printNum(int num){
       num = num + 10;
       System.out.println("Value inside printNum method: " + num);
    }
}

Output is: Value before calling method: 10 Value inside printNum method: 20 Value after calling method: 10

int num =10; -> this allocates the memory for "int" in Stack of the running thread, because, it is a primitive type. Now when printNum(..) is called, a private stack is created within the same thread. When "num" is passed to this method, a copy of "num" is created in the method stack frame. num = num+10; -> this adds 10 and modifies the the int variable within the method stack frame. Therefore, the original num outside the method stack frame remains unchanged.

Consider, the example of passing the object of a custom class as an argument.

enter image description here

In the above example, ref variable "book" resides in stack of thread executing the program, and the object of class Book is created in Heap space when program executes new Book(). This memory location in Heap is referred by "book". When "book" is passed as method argument, a copy of "book" is created in private stack frame of method within the same stack of thread. Therefore, the copied reference variable points to the same object of class "Book" in the Heap.

enter image description here

The reference variable within method stack frame sets a new value to same object. Therefore, it is reflected when original ref variable "book" gets its value. Note that in case of passing reference variable, if it is initialized again in called method, it then points to new memory location and any operation does not affect the previous object in the Heap.

Therefore, when anything is passed as method argument, it is always the Stack entity - either primitive or reference variable. We never pass something that is stored in Heap. Hence, in Java, we always pass the value in the stack, and it is pass by value.

@Amit Sharma 2019-07-17 05:10:43

Java passes parameters by value, There is no option of passing a reference in Java.

But at the complier binding level layer, It uses reference internally not exposed to the user.

It is essential as it saves a lot of memory and improves speed.

@user10356724 2019-06-18 10:15:03

I disagree that Java is only pass by value. Let us see this code snippet

import java.util.ArrayList;
public class Main {
    public static void getList(ArrayList<String> list){
        list.add("Hello") ;
    }
    public static void main(String[] args) {
        ArrayList<String> list=new ArrayList();
        System.out.println(list);
        getList(list);
        System.out.println(list);
    }
}

The output

[]
[Hello]

if JAVA had been call by value then why would my list be changed after calling the function the function should have changed only a copy of variable and the original list would have remained same

@Minn 2019-06-18 13:51:55

Here you have to understand the difference between a shallow copy and a deep copy. The reference is passed by value, its a shallow copy since the referenced value is not copied. stackoverflow.com/questions/184710/…

@user10356724 2019-06-18 14:03:09

So what i have done is shallow copy . It does not create new objects and hence it is kind of pass by value stackoverflow.com/questions/1175620/…

@Minn 2019-06-18 15:02:20

What you have done emulates pass-by-reference through an indirect reference. This is comparable to passing a pointer by value in C.

@user10356724 2019-06-18 15:05:54

It allll makes sense now

@Sanjeev 2019-06-19 18:35:22

@who If you were passing "list" by-reference to the method getList(), you'd be able to set "list" to null or assign a new object to "list" and the change would be reflected in main(). You're not really passing "list" by reference. You are passing a reference to "list" by value.

@user10356724 2019-06-20 03:42:29

@Sanjeev but i assigned "hello" to the empty list did not i

@Sanjeev 2019-06-20 04:19:38

Yes, but by definition, that's not enough to qualify as pass-by-reference. As @Minn mentioned, that's only emulated pass-by-reference. True pass-by-reference would allow you to change the value of the "reference", not just the object it points to. In fact the object is not in question at all since the "reference" is what's being passed to the function. To quote Gosling (the inventor of Java): "The Java programming language does not pass objects by reference; it passes object references by value." -- James Gosling, THE Java Programming Language, Chapter 2, Section 2.6.5

@user10356724 2019-06-20 06:01:20

@Sanjeev i am only a beginner so thank you for your clarification sir

@Basheer AL-MOMANI 2017-03-30 09:29:06

Unlike some other languages, Java does not allow you to choose between pass-by-value and 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

@moldovean 2019-04-30 14:50:45

Long story short:

  1. Non-primitives: Java passes the Value of the Reference.
  2. Primitives: just value.

The End.

(2) is too easy. Now if you want to think of what (1) implies, imagine you have a class Apple:

class Apple {
    private double weight;
    public Apple(double weight) {
        this.weight = weight;
    }
    // getters and setters ...

}

then when you pass an instance of this class to the main method:

class Main {
    public static void main(String[] args) {
        Apple apple = new Apple(3.14);
        transmogrify(apple);
        System.out.println(apple.getWeight()+ " the goose drank wine...";

    }

    private static void transmogrify(Apple apple) {
        // does something with apple ...
        apple.setWeight(apple.getWeight()+0.55);
    }
}

oh.. but you probably know that, you're interested in what happens when you do something like this:

class Main {
    public static void main(String[] args) {
        Apple apple = new Apple(3.14);
        transmogrify(apple);
        System.out.println("Who ate my: "+apple.getWeight()); // will it still be 3.14? 

    }

    private static void transmogrify(Apple apple) {
        // assign a new apple to the reference passed...
        apple = new Apple(2.71);
    }


}

@asok 2018-05-17 12:41:46

Java is only passed by value. there is no pass by reference, for example, you can see the following example.

package com.asok.cop.example.task;
public class Example {
    int data = 50;

    void change(int data) {
        data = data + 100;// changes will be in the local variable 
        System.out.println("after add " + data);
        }

    public static void main(String args[]) {
        Example op = new Example();
        System.out.println("before change " + op.data);
        op.change(500);
        System.out.println("after change " + op.data);
    }
}

Output:

before change 50
after add 600
after change 50

as Michael says in the comments:

objects are still passed by value even though operations on them behave like pass-by-reference. Consider void changePerson(Person person){ person = new Person(); } the callers reference to the person object will remain unchanged. Objects themselves are passed by value but their members can be affected by changes. To be true pass-by-reference, we would have to be able to reassign the argument to a new object and have the change be reflected in the caller.

@AutomatedMike 2019-05-03 12:18:06

Describing java as "pass-by-value" is highly misleading. For non-primitive types Java uses "pass by value of the reference". "Pass by value" implies the value is copied when passed to a method. It is not, the reference is copied.

@Stephane 2019-04-24 13:37:28

This above article is confusing.

It assumes making a copy of the reference and passing it to the method is a pass by value, because a copy is passed. That is not what I and many understand.

Is the language passing by value or by reference ? Why do we ask this question ?

The whole issue occurs when calling a method. Such a method is defined with parameters and is called with arguments.

Making the distinction between parameter and argument is helpful. The parameter is the name of the received thing specified when defining the method. The argument is the name of the sent thing specified when calling the method.

Any content stored in memory has an address so as to be accessed. This content address is called a reference. With the reference it is possible to access the content. If the reference is given to a tier then this tier can access and update the referenced content. If the reference is given to a method, then this method can also access and update this referenced content.

What happens when "passing" an argument into a method parameter ? A copy of the argument is made and given to the method parameter.

What do we understand when we say "pass by value" and "pass by reference" ? When using the word "value" we understand the actual content being stored, say someone's name. When using the word "reference" we understand a memory address pointing to a "value".

So, when we say "pass by value" we understand that the argument we pass into the method parameter is some content. And when we say "pass by reference" we understand that the argument we pass into the method parameter is a memory address pointing to some content.

If what is passed is some content, then a copy of this content is being made and given to the method. Since the content given is a copy, there is no risk of altering the original content.

If, on the other hand, what is passed is a reference to some content, then a copy of this reference is being made and given to the method, with the referenced content itself not being a copy of the original content, but being the original content, only its reference having been copied.

In Java, I understand that a primitive type is passed as content, that is, is passed by value, and an object is passed as a reference to some content, that is, is passed by reference.

That a copy of the reference is made before being given to the method parameter, does not make this reference a value.

The swap test is not a decisive indicator.

If an object outside a method can be altered from within the method when passing it to the method, then the passing is by reference.

The Java documentation and lots of articles are at best confusing on this, and at worst, wrong.

My two cents.

@Rodrigo Rodrigues 2019-10-09 04:56:45

Wrong. Try to use a language that actually passes arguments by reference, like Fortran, and you will see the difference.

@OverCoder 2016-04-25 14:32:28

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)

@erlando 2008-09-02 20:25:37

Java is always pass-by-value. Unfortunately, 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");
    Dog oldDog = aDog;

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

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

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

Likewise:

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

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

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

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

@Zoe 2020-07-09 09:36:13

Under the hood though, it's pass pointer by value.

@Felypp Oliveira 2018-02-02 21:23:56

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 param)
{
  // some code in foo...
}

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

  foo(obj);
}

is exactly the same as...

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

  Object param = obj;

  // some code in foo...
}

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

So, in fact, what we're looking for in Java is how variable assignment works. I found it in the docs :

One of the most common operators that you'll encounter is the simple assignment operator "=" [...] it assigns the value on its right to the operand on its left:

int cadence = 0;
int speed = 0;
int gear = 1;

This operator can also be used on objects to assign object references [...]

It's clear how this operator acts in two distinct ways: assign values and assign references. The last, when it's an object... the first, when it isn't an object, that is, when it's a primitive. But so, can we understand that Java's function params can be pass-by-value and pass-by-reference?

The truth is in the code. Let's try it:

public class AssignmentEvaluation
{
  static public class MyInteger
  {
    public int value = 0;
  }

  static public void main(String[] args)
  {
    System.out.println("Assignment operator evaluation using two MyInteger objects named height and width\n");

    MyInteger height = new MyInteger();
    MyInteger width  = new MyInteger();

    System.out.println("[1] Assign distinct integers to height and width values");

    height.value = 9;
    width.value  = 1;

    System.out.println("->  height is " + height.value + " and width is " + width.value + ", we are different things! \n");

    System.out.println("[2] Assign to height's value the width's value");

    height.value = width.value;

    System.out.println("->  height is " + height.value + " and width is " + width.value + ", are we the same thing now? \n");

    System.out.println("[3] Assign to height's value an integer other than width's value");

    height.value = 9;

    System.out.println("->  height is " + height.value + " and width is " + width.value + ", we are different things yet! \n");

    System.out.println("[4] Assign to height the width object");

    height = width;

    System.out.println("->  height is " + height.value + " and width is " + width.value + ", are we the same thing now? \n");

    System.out.println("[5] Assign to height's value an integer other than width's value");

    height.value = 9;

    System.out.println("->  height is " + height.value + " and width is " + width.value + ", we are the same thing now! \n");

    System.out.println("[6] Assign to height a new MyInteger and an integer other than width's value");

    height = new MyInteger();
    height.value = 1;

    System.out.println("->  height is " + height.value + " and width is " + width.value + ", we are different things again! \n");
  }
}

This is the output of my run:

Assignment operator evaluation using two MyInteger objects named height and width

[1] Assign distinct integers to height and width values
->  height is 9 and width is 1, we are different things! 

[2] Assign to height's value the width's value
->  height is 1 and width is 1, are we the same thing now? 

[3] Assign to height's value an integer other than width's value
->  height is 9 and width is 1, we are different things yet! 

[4] Assign to height the width object
->  height is 1 and width is 1, are we the same thing now? 

[5] Assign to height's value an integer other than width's value
->  height is 9 and width is 9, we are the same thing now! 

[6] Assign to height a new MyInteger and an integer other than width's value
->  height is 1 and width is 9, we are different things again! 

In [2] we have distinct objects and assign one variable's value to the other. But after assigning a new value in [3] the objects had different values, which means that in [2] the assigned value was a copy of the primitive variable, usually called pass-by-value, otherwise, the values printed in [3] should be the same.

In [4] we still have distinct objects and assign one object to the other. And after assigning a new value in [5] the objects had the same values, which means that in [4] the assigned object was not a copy of the other, which should be called pass-by-reference. But, if we look carefully in [6], we can't be so sure that no copy was done... ?????

We can't be so sure because in [6] the objects were the same, then we assigned a new object to one of them, and after, the objects had different values! How can they be distinct now if they were the same? They should be the same here too! ?????

We'll need to remember the docs to understand what's going on:

This operator can also be used on objects to assign object references

So our two variables were storing references... our variables had the same reference after [4] and different references after [6]... if such a thing is possible, this means that assignment of objects is done by copy of the object's reference, otherwise, if it was not a copy of reference, the printed value of the variables in [6] should be the same. So objects (references), just like primitives, are copied to variables through assignment, what people usually call pass-by-value. That's the only pass-by- in Java.

@CodeKiller 2018-08-28 14:48:08

Easy answer for beginner

If you pass a complex Object (like a dog as apparently it is the common example) it is the same as passing the reference. If you pass a field of a complex Object (like the name of the dog only) it is the same as passing the value (changing it won't change the dog/parent of the field).

Note that Object that are not "complex" (not like our dog) like Integer or String are passed by value. So even if they are Object with everything you can do on them they cannot be modified inside a method... Yes, this is ****ed up and does not make any sense...

Example (not a Dog) :

public class HelloWorld {
    private Integer i;
    private String s;
    private Boolean b;

    public static void main(String[] args) {
        HelloWorld h = new HelloWorld();

        h.s = "Bill";
        h.ModMe(h.s);
        h.i = 2;
        h.ModMe(h.i);
        h.b = true;
        h.ModMe(h.b);
        System.out.println(h.s + " " + h.i + " " + h.b);

        h.ModMe(h);
        System.out.println(h.s + " " + h.i + " " + h.b);

        String test = "TEST";
        h.ModMe(test);
        System.out.println(test);
    }

    public void ModMe(Object o) {
        if (o instanceof HelloWorld) {
            ((HelloWorld) o).i = (int) Math.pow(((HelloWorld) o).i, 2);
            ((HelloWorld) o).b = !((HelloWorld) o).b;
            ((HelloWorld) o).s = ((HelloWorld) o).s.concat(" modded successfully");
        } else if (o instanceof Integer) {
            o = (Integer) o + (Integer) o;
        } else if (o instanceof String) {
            o = ((String) o).concat(" is modified.");
        } else if (o instanceof Boolean) {
            o = !(Boolean) o;
        }
    }
}

If you run that the object h will be modified if you use the whole object as the argument but not the fields s i or b if you only use them as argument. if you debug that you will notice that for the fields the id of the object will change as soon as you run the line where the value is changed. So it will do the same as "new Integer" "new String" and "new Boolean" automatically.

@Sanjeev 2019-05-06 19:45:48

Passing a reference is not the same as pass-by-reference. Java is ALWAYS pass-by-value. This is true even when passing a reference because the reference is being passed by value (i.e. a copy of the reference is being passed). This is confusing in Java due to the word "reference" in Java to refer to a pointer.

@georgeawg 2018-07-25 15:40:46

Java passes primitive types by value and class types by reference

Now, people like to bicker endlessly about whether "pass by reference" is the correct way to describe what Java et al. actually do. The point is this:

  1. Passing an object does not copy the object.
  2. An object passed to a function can have its members modified by the function.
  3. A primitive value passed to a function cannot be modified by the function. A copy is made.

In my book that's called passing by reference.

Brian Bi - Which programming languages are pass by reference?

@Dennis 2018-08-25 21:08:34

I'm not sure it's technically correct to mention that copies are made for primitive types. Primitive types are immutable which is why they cannot be modified inside a method they are passed to. The difference is negligible for things like numbers, but there is an important difference for potentially large strings.

@Torben 2018-10-03 04:40:21

This answer is completely incorrect and only creates confusion. Java is a pure pass-by-value language. What confuses you is that the value can be a pointer to an object. Pass-by-reference means one would be able to change the identity of an object at the caller's side. E.g. assigning a new object to a method parameter would also affect the pointer that was passed in the code that called the method.

@nasch 2018-12-27 18:49:38

@Dennis Strings are not primitives, they're objects.

@Sanjeev 2019-01-23 00:01:56

It's not about what's "In your book." "Pass by reference" and "Pass by value" are industry standard terms which have very specific definitions. By those definitions Java is "Pass by value" without exceptions.

@AndrewF 2019-12-25 00:00:47

"Passing an object" is not a valid operation in Java. You pass a reference to an object. Doing so is not called "passing by reference". It is called "passing by value". The reference passed is a value, which is copied to a new place on the stack for the method to use, just like any primitive value.

@Hank Gay 2008-09-02 20:21:04

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.

@Ganesh 2013-10-17 07:54:30

Java is always pass by value, not pass by reference

First of all, we need to understand what pass by value and pass by reference are.

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

Pass by reference (also called pass by address) means that a copy of the address of the actual parameter is stored.

Sometimes Java can give the illusion of pass by reference. Let's see how it works by using the example below:

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;
}

The output of this program is:

changevalue

Let's understand step by step:

Test t = new Test();

As we all know it will create an object in the heap and return the reference value back to t. For example, suppose the value of t is 0x100234 (we don't know the actual JVM internal value, this is just an example) .

first illustration

new PassByValue().changeValue(t);

When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function. Since it is passing by value, it passes a copy of the variable rather than the actual reference of it. Since we said the value of t was 0x100234, both t and f will have the same value and hence they will point to the same object.

second illustration

If you change anything in the function using reference f it will modify the existing contents of the object. That is why we got the output changevalue, which is updated in the function.

To understand this more clearly, consider the 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 this throw a NullPointerException? No, because it only passes a copy of the reference. In the case of passing by reference, it could have thrown a NullPointerException, as seen below:

third illustration

Hopefully this will help.

@mc01 2018-03-16 23:25:34

PT 1: Of Realty Listings

There is a blue, 120sq-ft "Tiny House" currently parked at 1234 Main St with a nicely manicured lawn & flower bed out front.

A Realtor with a local firm is hired and told to keep a listing for that house.

Let's call that Realtor "Bob." Hi Bob.

Bob keeps his Listing, which he calls tinyHouseAt1234Main, up to date with a webcam that allows him to note any changes to the actual house in real time. He also keeps a tally of how many people have asked about the listing. Bob's integer viewTally for the house is at 42 today.

Whenever someone wants info about the blue Tiny House at 1234 Main St, they ask Bob.

Bob looks up his Listing tinyHouseAt1234Main and tells them all about it - the color, the nice lawn, the loft bed and the composting toilet, etc. Then he adds their inquiry to his viewTally. He doesn't tell them the real, physical address though, because Bob's firm specializes in Tiny Houses that could be moved at any time. The tally is now 43.

At another firm, Realtors might explicitly say their listing "points" to the house at 1234 Main St, denoting this with a little * next to it, because they mainly deal with houses that rarely ever move (though presumably there are reasons for doing so). Bob's firm doesn't bother doing this.

Now, of course Bob doesn't physically go and put the actual house on a truck to show it to clients directly - that would be impractical and a ridiculous waste of resources. Passing a full copy of his tally sheet is one thing, but passing around the whole house all the time is costly and ridiculous.

(Aside: Bob's firm also doesn't 3D print new & unique copies of a listed house every single time someone asks about it. That's what the upstart, similarly named web-based firm & its spinoffs do - that's expensive and slower, and people often get the 2 firms confused, but they're quite popular anyway).

At some other, older firms closer to the Sea, a realtor like Bob might not even exist to manage the Listings. Clients might instead consult the Rolodex "Annie" (& for short) for the direct address of the house. Instead of reading off the referenced house details from the listing like Bob does, clients instead get the house address from Annie (&), and go directly to 1234 Main St, sometimes w/no idea what they might find there.

One day, Bob's firm begins offering a new automated service that needs the listing for a house the client is interested in.

Well, the person with that info is Bob, so the client has Bob call up the service and send it a copy of the listing.

jobKillingAutomatedListingService(Listing tinyHouseAt1234Main, int viewTally) Bob sends along ...

The service, on its end, calls this Listing houseToLookAt, but really what it receives is an exact copy of Bob's listing, with the exact same VALUEs in it, that refer to the house at 1234 Main St.

This new service also has its own internal tally of how many people have viewed the listing. The service accepts Bob's tally out of professional courtesy, but it doesn't really care and overwrites it entirely with its own local copy anyway. It's tally for today is 1, while Bob's is still 43.

The realty firms call this "pass-by-value" since Bob's passing the current value of his viewTally and his Listing tinyHouseAt1234Main. He's not actually passing along the entire physical house, because that's impractical. Nor is he passing the real physical address like Annie(&) would do.

But he IS passing a copy of the value OF the reference he has to the house. Seems like a silly pedantic difference in some ways, but that's how his firm works ... ..............

PT II: Where things get confusing and dangerous ...

The new automated service, not being all functional and math-oriented like some other trendy financial & scientific firms, can have unforeseen side effects...

Once given a Listing object it allows clients to actually repaint the REAL house at 1234 Main St, using a remote drone robot fleet! It allows clients to control a robot bulldozer to ACTUALLY dig up the flower bed! This is madness!!!

The service also lets clients completely redirect houseToLookAt to some other house at another address, without involving Bob or his listing. All of a sudden they could be looking at 4321 Elm St. instead, which has no connection whatsoever to Bob's listing (thankfully they can't do anymore damage).

Bob watches all this on his realtime webcam. Resigned to the drudgery of his sole job responsibility, he tells clients about the new ugly paint job & sudden lack of curb appeal. His Listing is still for 1234 Main St., after all. The new service's houseToLookAt couldn't change that. Bob reports the details of his tinyHouseAt1234Main accurately and dutifully as always, until he gets fired or the house is destroyed entirely by The Nothing.

Really the only thing the service CAN'T do with its houseToLookAt copy of the Bob's original listing is change the address from 1234 Main St. to some other address, or to a void of nothingness, or to some random type of object like a Platypus. Bob's Listing still always points to 1234 Main St, for whatever it's still worth. He passes its current value around like always.

This bizarre side-effect of passing a listing to the new automated service is confusing for people who ask about how it works. Really, what's the difference between the ability to remotely control robots that alter the state of the house at 1234 Main, vs. actually physically going there and wreaking havoc because Annie gave you the address??

Seems like kind of a nitpicky semantic argument if what you generally care about is the state of the house in the listing being copied and passed around, right?

I mean, if you were in the business of actually picking up houses and physically moving them to other addresses (not like mobile or Tiny Homes where that's sort of an expected function of the platform), or you were accessing, renaming, and shuffling entire neighborhoods like some sort of low-level God-playing madman, THEN maybe you'd care more about passing around those specific address references instead of just copies of the the latest value of the house details ...

@JacquesB 2009-01-12 20:50:25

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.

@cutmancometh 2013-09-11 11:34:30

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".

Related Questions

Sponsored Content

62 Answered Questions

[SOLVED] How to avoid null checking in Java?

35 Answered Questions

[SOLVED] What are the differences between a HashMap and a Hashtable in Java?

32 Answered Questions

[SOLVED] Is JavaScript a pass-by-reference or pass-by-value language?

24 Answered Questions

[SOLVED] Does Java support default parameter values?

27 Answered Questions

[SOLVED] How do I pass a variable by reference?

58 Answered Questions

[SOLVED] How to create a memory leak in Java?

66 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 4114218 View
  • 3550 Score
  • 66 Answer
  • Tags:   java random integer

59 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

35 Answered Questions

Sponsored Content