Skip to main content

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

Popular posts from this blog

Architecture Complexity

Here are the items to consider: Coding to an interface Service Oriented Architecture Automated Testing Domain Driven Design Custom Data Access Layer Layered architecture Complexity is relatively equal the number of lines of code. Note that complexity is not bad. It must be justified.

Android Studio:Unknown Host Error

After installing Android Studio, I got the following error: Unknown host 'services.gradle.org'. Please ensure the host name is correct. If you are behind an HTTP proxy, please configure the proxy settings either in Android Studio or Gradle. Consult IDE log for more details (Help | Show Log) Solution File --> Settings --> HTTP Proxy --> Auto-detect proxy settings

Brain as the tool of the spirit

The mind as the bridge between pure consciousness and the body in which that consciousness temporarily resides.