In this piece of code i pass a name into a method that modifies the String literal name but not the object itself, when the code exits the method, the object (as identified by the hashcode) is the same, however not the name that is modified in the method.
How should i explain this?
public class ObjectContentsPassByReferenceApp {
private static void modifyObject(Bus bus) {
bus.setName("SBS Transit");
}
public static void main(String args[]) {
Bus bus;
bus = new Bus();
bus.setName("Trans Island Bus");
System.out.println("Bus initially set to (hashcode): " + bus);
System.out.println("Bus name: " + bus.getName());
modifyObject(bus);
System.out.println("After calling modifyObject (hashcode): " + bus);
System.out.println("Bus name: " + bus.getName());
}
}
class Bus {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
Run results:
Bus initially set to (hashcode): sg.java.concepts.passByReference.Bus@8d2ed0
Bus name: Trans Island Bus
After calling modifyObject (hashcode): sg.java.concepts.passByReference.Bus@8d2ed0
Bus name: SBS Transit
You haven’t overridden
hashCode– therefore it will use the implementation injava.lang.Object, which doesn’t vary over the course of an object’s lifetime. You haven’t overriddenequalseither… which means thata.equals(b)will only returntrueforBus aandBus bifaandbrefer to the exact same object – rather than objects with equal name.Note that the names in your code suggest that Java uses pass by reference. It doesn’t – it always uses pass by value, but those values are always either primitives or references – never actual objects. The same is true for simple assignment etc.
In your code, you’re creating a single
Busobject. Think of it as a real life bus. It has a name painted on it, and a serial number embossed on it (the latter being the hash code). When you call the method, that’s telling the method how to get to theBusobject – it’s not creating a newBus. The method comes and paints over the name with a new one, but that does nothing to the serial number, which is the same as it ever was.Also note that
nameis not a string literal – it’s a string variable. Its initial value comes from a string literal, but changing the value later does nothing to the original string object.