Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object reference in java

Tags:

java

object

consider this simple servlet sample:

protected void doGet(HttpServletRequest request, HttpServletResponse response){
    Cookie cookie = request.getCookie();
    // do weird stuff with cookie object
}

I always wonder.. if you modify the object cookie, is it by object or by reference?

like image 809
allan Avatar asked Dec 14 '22 05:12

allan


2 Answers

if you modify the object cookie, is it by object or by reference?

Depends on what you mean by "modify" here. If you change the value of the reference, i.e. cookie = someOtherObject, then the original object itself isn't modified; it's just that you lost your reference to it. However, if you change the state of the object, e.g. by calling cookie.setSomeProperty(otherValue), then you are of course modifying the object itself.

Take a look at these previous related questions for more information:

  • Java, pass-by-value, reference variables
  • Is Java pass by reference?
like image 85
Zach Scrivena Avatar answered Feb 01 '23 21:02

Zach Scrivena


Java methods get passed an object reference by value. So if you change the reference itself, e.g.

cookie = new MySpecialCookie();

it will not be seen by the method caller. However when you operate on the reference to change the data the object contains:

cookie.setValue("foo");

then those changes will be visible to the caller.

like image 28
Kieron Avatar answered Feb 01 '23 22:02

Kieron