Java crazyness

April 24, 2007 by Michael

Someone must be hit really hard with some curly braces when he implemented the following behaviour:

public class Braindead {
	public static void main(String[] args) {
		Integer i1 = 10;
		Integer i2 = 10;
 
		Integer i3 = 128;
		Integer i4 = 128;
 
		compare(i1, i2);
		compare(20, 20);
		compare(i3, i4);
	}
 
	public static void compare(Integer i1, Integer i2) {
		System.out.println("Comparing " + i1 + " and " + i2);
 
		if(i1 == i2)
			System.out.print("same ");
		else
			System.out.print("different ");
		System.out.println("Objects");
 
		if(!i1.equals(i2))
			System.out.print("not ");
		System.out.println("meaningfully equal");
		System.out.println("---");
	}
}

I’d expect the following output:

Comparing 10 and 10
different Objects
meaningfully equal
---
Comparing 20 and 20
different Objects
meaningfully equal
---
Comparing 128 and 128
different Objects
meaningfully equal
---

What you get is:

Comparing 10 and 10
same Objects
meaningfully equal
---
Comparing 20 and 20
same Objects
meaningfully equal
---
Comparing 128 and 128
different Objects
meaningfully equal
---

In order to save memory, two instances of the following wrapper objects will always be == when their primitive values are the same:

  • Boolean
  • Byte
  • Character from \u0000 to \u007f
  • Short and Integer from -128 to 127

So in order to save a handfull of bytes we present you some really inconvenient feature 😉

2 comments

  1. tante wrote:

    Well, just another example showing how half-assed OO is in Java 😉

    Posted on April 28, 2007 at 4:05 PM | Permalink
  2. Michael wrote:

    Hark hark…

    I tell you, i fell deep into “love” with ruby…

    The most annoying j2ee thing is the mess of all those damn xml configuration files…

    Posted on April 28, 2007 at 8:05 PM | Permalink
Post a Comment

Your email is never published. We need your name and email address only for verifying a legitimate comment. For more information, a copy of your saved data or a request to delete any data under this address, please send a short notice to michael@simons.ac from the address you used to comment on this entry.
By entering and submitting a comment, wether with or without name or email address, you'll agree that all data you have entered including your IP address will be checked and stored for a limited time by Automattic Inc., 60 29th Street #343, San Francisco, CA 94110-4929, USA. only for the purpose of avoiding spam. You can deny further storage of your data by sending an email to support@wordpress.com, with subject “Deletion of Data stored by Akismet”.
Required fields are marked *