0

I know for a fact that primitives are being passed by value in java. But what are references being passed by? By reference, or by value? I can't find a clear answer.

Danger
  • 3
  • 2
  • http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – Shekhar Khairnar Jan 28 '16 at 13:50
  • 1
    Duplicate of http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – Shiladittya Chakraborty Jan 28 '16 at 13:52
  • The first time you pass the object to a function, is by reference. Inside this function, the reference becomes a "primitive" value, and it's passed by value to other functions. The reference is like a pointer, and a pointer is an integer value. The Java syntax hides this detail. – Jose Luis Jan 28 '16 at 13:57
  • Are you confusing *reference* with *Hash Code*? [refer this](http://stackoverflow.com/questions/4712139/why-does-the-default-object-tostring-include-the-hashcode) – Nikhil Chilwant Jan 28 '16 at 14:11

3 Answers3

0

Java doesn't pass method arguments by reference; it passes them by value.

Example :

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

When swap() returns, the variables passed as arguments will still hold their original values.

In the case of object reference are passed by value hence it appears to be pass-by-reference and This is not the case !

Example :

public void swap(Point p1, Point p2)
{
  p1.x = 100;
  p1.y = 100;
  Point temp = p1;
  p1 = p2;
  p2 = 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(" ");
  swap(pnt1,pnt2);
  System.out.println("X: " + pnt1.x + " Y:" + pnt1.y); 
  System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);  
}

Output :

X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0
Wael Sakhri
  • 397
  • 1
  • 8
0

Indeed, everything is passed by reference. Remember though that all objects in Java are stored as pointers. When you pass an object, you are passing a reference to the pointer, no the object itself.

Frank
  • 153
  • 12
0

Source: Google

Java passes all primitive data types by value. This means that a copy is made, so that it cannot be modified. When passing Java objects, you're passing an object reference, which makes it possible to modify the object's member variables.

A very nice explanation: Is Java "pass-by-reference" or "pass-by-value"?

Community
  • 1
  • 1
user2004685
  • 9,548
  • 5
  • 37
  • 54