Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Pass by value understanding

I think I understand that it is a copy of the object/data member passed into the method tricky(), as only the value is what matters, not the actual object itself. But the print statements assure me that arg1 and arg2, the copies, are indeed switched within the method. I don't understand why this wouldn't relay the information back to original objects, consequently switching them; Seeing as the method is able to successfully access the arg1.x and arg1.y data members within the method.

// This class demonstrates the way Java passes arguments by first copying an existing
// object/data member. This is called passing by value. the copy then points(refers)
// to the real object

// get the point class from abstract window toolkit
import java.awt.*;

public class passByValue {


static void tricky(Point arg1, Point arg2){

  arg1.x = 100;
  arg1.y = 100;
  System.out.println("Arg1: " + arg1.x + arg1.y);
  System.out.println("Arg2: " + arg2.x + arg2.y);

  Point temp = arg1;
  arg1 = arg2;
  arg2 = temp;
  System.out.println("Arg1: " + arg1.x + arg1.y);
  System.out.println("Arg2: " + arg2.x + arg2.y);
}




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

}
}
like image 271
Cactus BAMF Avatar asked Jul 03 '26 23:07

Cactus BAMF


2 Answers

The object reference is copied, and the copied reference still points to the same object in memory. This is why you can change the object using the copied reference. However, modifying the parameter references modifies the copies, not the original references. This is why redirecting the references within the method doesn't redirect the references you passed in.

Hope this clears things up.

like image 196
LastStar007 Avatar answered Jul 06 '26 12:07

LastStar007


Java does pass by value, but what it passes is the value of the object's reference, which gives the effect of pass by reference (for primitives, it behaves more like pass by value).

But Java is always pass by value.

like image 23
Jeff Storey Avatar answered Jul 06 '26 13:07

Jeff Storey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!