No brainer? +

Try to figure out on paper what is printed when you are running the following lines of code:

public class WrapperObjects {
	public static void main(String[] args) {
		WrapperObjects wrapperObjects = new WrapperObjects();
		wrapperObjects.compareObjects();
	}

	private void compareObjects() {
		Integer i0a = null;
		Integer i0b = 0;
		Integer i1a = 64;
		Integer i1b = 64;
		Integer i2a = 128;
		Integer i2b = 128;

		compareIntObjects(i0a,i0b);
		compareIntObjects(i0a,i1a);
		compareIntObjects(i1a,i1b);
		compareIntObjects(i1a,i2a);
		compareIntObjects(i2a,i2b);
		compareIntObjects(i2a,i0a);
	}

	private void compareIntObjects(Integer i1, Integer i2) {
		System.out.println(i1 + " " + i2);
		System.out.println(i1 == i2 ? "same object" : "different objects" );
		System.out.println(i2.equals(i1) ? "equal" : "not equal");
	}
}

Don’t cheat and run the code as program.

4 Responses to “No brainer?”

  1. Without going throigh the whole thing on paper, i would assume the comparisons between i1a and i1b (i2a and i2b, respectively) print “same object” because the autoboxing mechanism reuses wrapper objects for the same value. After that, the last call to compareIntObjects will throw a NulPointerException because you’re calling equals on null.

    Do I win a cookie?

  2. A little bit wrong, but one trap is found.

  3. <a href=”http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#190730″http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#190730


    assert ((Integer)-128) == ((Integer)-128));
    assert ((Integer) -1) == ((Integer) -1));
    assert ((Integer) 0) == ((Integer) 0));
    assert ((Integer) 64) == ((Integer) 64));
    assert ((Integer) 127) == ((Integer) 127));
    assert ((Integer) 128)!=((Integer) 128));

  4. null 0
    different objects
    not equal
    null 64
    different objects
    not equal
    64 64
    same object
    equal
    64 128
    different objects
    not equal
    128 128
    different objects
    equal
    128 null
    different objects
    Exception in thread “main” java.lang.NullPointerException
    at biz.tiffert.scjp.boxing.WrapperObjects.compareIntObjects(WrapperObjects.java:28)
    at biz.tiffert.scjp.boxing.WrapperObjects.compareObjects(WrapperObjects.java:22)
    at biz.tiffert.scjp.boxing.WrapperObjects.main(WrapperObjects.java:6)

    What a bad code:
    Yes, i1a == i1b, but i2a != i2b.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>