Digital Stronghold - Software Engineering, Musicality and Facts of Life…



February 12, 2009

Sad reality about Wrapper Classes in Java

Consider the snippet.

Integer firstInteger = 1000; // autoboxing
Integer secondInteger = 1000; //autoboxing 
	
if (firstInteger != secondInteger) {
     System.out.println("Different objects!");
}
	
if(firstInteger.equals(secondInteger)) {
     System.out.println("Meaningfully equivalent!");
}

Output:

Different objects!
Meaningfully equivalent!

How about this one.

Integer firstInteger = 100; // autoboxing
Integer secondInteger = 100; //autoboxing 
	
if (firstInteger == secondInteger) {
     System.out.println("Equal objects!");
}
	
if(firstInteger.equals(secondInteger)) {
     System.out.println("Meaningfully equivalent!");
}

And the output?

Equal objects!
Meaningfully equivalent!

And the explanation?

Two instances of the wrapper objects will always be == when their primitive values are the same.
- Boolean
- Byte
- Character from \u0000 to \u007F (0 to 127)
- Short from -128 to 127
- Integer from -128 to 127

Tsk.

Comments »

The URI to TrackBack this entry is: http://eradicus.blogsome.com/2009/02/12/sad-reality-about-wrapper-classes-in-java/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.

Theme designed by Joset Anthony Zamora


Digital Stronghold

↑ Get Headline Animator