This is an article I wrote a while ago, but is still relevant to many languages still in use. Figured I’d repost it to this blog.


Many of you may have learned the following in Java 101, but I thought I’d repeat it just in case.

Most of the variables you’ll use in Java are going to be Objects. So in the following code, we’re creating three Objects:

BigDecimal number = new BigDecimal("9.5");
String welcome = "Hello";
Connection conn = DriverManager.getConnection(props);

The first case is using the standard constructor of a Class to create an Object, the second is creating a String via a String literal, and the third is creating an Object via a Factory (an Object that creates other Objects). All of these create an Object and puts it in the variable to the left.

Except I’m lying. Do you know where I’m lying?

Little Errand Boys

number , welcome , and conn aren’t holding Objects, they’re holding references to Objects. These are called pointers because they “point” to an Object and don’t actually do anything except pass messages along to the Object they’re pointing at. They’re basically the Objects’ errand boys. When you say something like:

number.toString();

You’re basically saying “Hey, errand boy. Go ask your Object what its string value is and then let me know.” That becomes important when you consider that you can do this:

BigDecimal sameNumber = number;

sameNumber is now pointing to the exact same Object as number . That means that one Object has two errand boys. If I tell one errand boy to change the Object, then the other errand boy sees the change too, because it’s the same Object! This can be confusing if you’re not expecting it.

Cha-Cha-Cha-Changes

This has important repercussions when looking at methods calls. For instance:

public static void addItem(List listToAdd){
    listToAdd.add("Hello");
}

List group = new ArrayList();
System.out.println(group.isEmpty());  // Prints true

addItem(group);

System.out.println(group.isEmpty());  // Prints false

So even though our code didn’t add anything to the List Object, listToAdd() did. Since they point to the same Object, both errand boys see the change. This is very important to remember when coding in Java.

Remember: Multiple variables can point to the same Object, so be careful changing them!