allan
allan

Reputation: 29

Object reference in java

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?

Upvotes: 4

Views: 17017

Answers (4)

kalyani
kalyani

Reputation: 1

object reference is different from object. for eg:

class Shape
{
    int x = 200;
}

class Shape1
{
    public static void main(String arg[])
    {
        Shape s = new Shape();   //creating object by using new operator
        System.out.println(s.x);
        Shape s1;                //creating object reference
        s1 = s;                  //assigning object to reference
        System.out.println(s1.x);
    }
}

Upvotes: 0

hhafez
hhafez

Reputation: 39810

In the following line of code

Cookie cookie = request.getCookie(); /* (1) */

the request.getCookie() method is passing a refrence to a Cookie object.

If you later on change cookie by doing something like

cookie = foo_bar(); /* (2) */

Then you are changing the internal refrence. It in no way affects your original cookie object in (1)

If however you change cookie by doing something like

cookie.setFoo( bar ); /* assuming setFoo changes an instance variable of cookie */

Then you are changing the original object recieved in (1)

Upvotes: 0

Zach Scrivena
Zach Scrivena

Reputation: 29569

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:

Upvotes: 10

Kieron
Kieron

Reputation: 11834

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.

Upvotes: 3

Related Questions