Java pass by reference or value?

This is an old but good one. After 15 years of java programming, I carelessly fell into one of the greatest pass-by-value traps 🙂  I constructed this simple example to illustrate my bug.

public class SBTester {

String s = “hello”;

public void a(StringBuffer sb){
System.out.println(“Object HC in a before ”  + sb.hashCode());
sb.append(s);
System.out.println(“Object HC in a after ”  + sb.hashCode());
}

public void b(StringBuffer sb){
System.out.println(“Object HC in b before ”  + sb.hashCode());
sb = new StringBuffer(“”).append(s);  // careless bug
System.out.println(“Object HC in b after ”  + sb.hashCode());
}

public static void main(String[] args) {

SBTester sbt = new SBTester();
StringBuffer sb = new StringBuffer(“”);
System.out.println(“Object HC before ”  + sb.hashCode());
sbt.b(sb);
System.out.println(“Object HC after ”  + sb.hashCode());
System.out.println(“–>” + sb + “<–“);

}

}

See above code. The method a works as intended. The printout in main() will be ‘–>hello<–‘. But the b method will printout just ‘–><–‘. This is because Java is pass by value all the time!! Even when passing an object, the value (hashcode) of the object is passed. And if you re-init an object with a new keyword, another instance of the object (in this case, a StringBuffer) is created and the “value” of the reference is changed to the new Object’s hashcode. Thus, whatever you do to the new object will have no bearing on the one that was passed over by its reference value.

The output of the program shows the hashcodes are different in and outside the b method.

Object HC before 1787303145
Object HC in b before 1787303145
Object HC in b after 202703779
Object HC after 1787303145
–><–

Cheers!

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s