Object reference in java

consider this simple servlet example:

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

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

+4
source share
4 answers

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

Depends on what you mean by β€œchange” here. If you change the value of the link, i.e. cookie = someOtherObject , then the original object itself will not be changed; it's just that you lost your link to it. However, if you change the state of the object, for example. cookie.setSomeProperty(otherValue) calling cookie.setSomeProperty(otherValue) , you, of course, change the object itself.

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

+10
source

Java methods pass an object reference by value . Therefore, if you yourself change the link, for example

 cookie = new MySpecialCookie(); 

it will not be displayed by the calling method. However, when you use the link to modify the data contained in the object:

 cookie.setValue("foo"); 

then these changes will be visible to the caller.

+3
source

In the next line of code

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

The request.getCookie() method passes refrence to the Cookie .

If you change the cookie by later cookie by doing something like

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

Then you change the internal refrence. This in no way affects your original Cookie in (1)

If you changed the Cookie by doing something like

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

Then you change the original object obtained in (1)

0
source

the reference to the object is different from the object. 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(sx); Shape s1; //creating object reference s1 = s; //assigning object to reference System.out.println(s1.x); } } 
0
source

All Articles