Thursday, September 23, 2010

Java is 'Pass by value'

In case of primitive types, the actual value is passed so the changes inside the method won't effect outside.
In case of objects, the memory address is passed by value again, so the changes effect outside the method too, unless the object is newly created inside that method.


-- Here is the test code snippet --

public class Java {
@Override
public int hashCode() {
// TODO Auto-generated method stub
System.out.println(super.hashCode());
return super.hashCode();
}

public static void updatePrimitive(int i) {
i = 999;
System.out.println("inside updatePrimitive " + i);
}

public static void updateString(String s) {
s = "bye";
System.out.println("inside updateString " + s);
}

public static void updateObject(Dto dto) {
dto.setValue("555");
System.out.println("inside updateObject " + dto.getValue());
}

public static void updateObjectNew(Dto dto) {
dto = new Java().new Dto();
dto.setValue("777");
System.out.println("inside updateObjectNew " + dto.getValue());
}

public static void main(String args[]) {
int i = 8;
updatePrimitive(i);
System.out.println("outside updatePrimitive " + i);

String s = "hello";
updateString(s);
System.out.println("outside updateString " + s);

Dto dto = new Java().new Dto();
dto.setValue("666");
updateObject(dto);
System.out.println("outside updateObject " + dto.getValue());

Dto dtoNew = new Java().new Dto();
updateObjectNew(dtoNew);
System.out.println("outside updateObjectNew " + dtoNew.getValue());
}

class Dto {
private String value = "Test1";

/**
* @return the value
*/
public String getValue() {
return value;
}

/**
* @param value the value to set
*/
public void setValue(String value) {
this.value = value;
}
}
}

No comments: