Autoboxing Makes Java Be 99% Object-Oriented

JavaI remember that back to the early age when I was first beginning to learn the Java programming language, there was a famous quote (in China): Java is a 95% object-oriented programming language..

Why was it? Because Java has primitive types built-in. I have to admit that I both love primitive types and hate them. Loving them because I can use “+” to add them up instead of “add” method; hating them because they are NOT objects!

But things had been changed by Java 1.5 or Java 5. This version of Java introduced a significant number of new features into the language, one of them is called Autoboxing (and auto-unboxing). That is, Java is going to wrap (unwrap) primitive types for you automatically when you are trying to “object-orient” primitive types.

As before, when you type in something like

1
Integer i = 5;

You are expecting to get some nice compile errors. However, your expectation will NEVER be true in Java 5 or later!

You can do the following with Autoboxing:

1
2
3
4
Integer i = 5;
Integer j = new Integer(5);
int k = i + j;    // "Integer + Integer" ? No compile errors? No!
System.out.println("k = " + k);    // k = 10, awesome!

You can even do this:

1
2
3
Integer i = new Integer(5);
int j = 5;
System.out.println("i == j, " + i == j);    // What? Yes, it is true.

Surprised? Yes! You should see now, with Autoboxing, you can bring your favorite ints, doubles into the beauty of the OO world without any explicit ugly wrappers. That’s why I say that Autoboxing makes Java become 99% object-oriented programming language.

Wait, why there is 1% missing? Well, primitive types are still there, they need room to stay and they are not objects. That means you still cannot do

1
5.getClass();

kind of stuff in Java. Yes, you can do this in Ruby or whatever pure OOPs, but it’s another story.

I know this topic is a little bit out dated, but some of my classmates haven’t been aware of these cool “new” features. Most of them knew foreach and generic, but what the hell is Varargs? You see my point ;)


Leave a Comment

(required)

(required)

Formatting Your Comment

The following XHTML tags are available for use:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">

URLs are automatically converted to hyperlinks.