Java Integer Cache: Why Integer.valueOf(127) == Integer.valueOf(127) Is True

According to our calculations, Integer.valueOf(127) == Integer.valueOf(127) is true.

In an interview, one of my friends was asked: If we have two Integer objects, Integer a = 127; Integer b = 127; Why does a == b evaluate to true when both are holding two separate objects? In this article, I will try to answer this question and explain the answer.

You may also like:  The Internal Cache of Integers

Short Answer

The short answer to this question is, direct assignment of an int literal to an Integer reference is an example of auto-boxing concept where the literal value to object conversion code is handled by the compiler, so during compilation phase compiler converts Integer a = 127; to Integer a = Integer.valueOf(127);.

How to Customize Serialization in Java Using the Externalizable Interface

In a previous article, Everything You Need to Know About Java Serialization Explained, I explained how we can serialize/deserialize one object using the Serializable interface and explain how we can customize the serialization process using writeObject and readObject methods.

Disadvantages of Java Serialization Process

But these customizations are not sufficient because the JVM has full control of the serialization process and those customization logics are just additions to the default serialization process. We still have to use the default serialization logic by calling ObjectOutputStream.defaultWriteObject() and ObjectInputStream.defaultReadObject() from writeObject and readObject methods. And if we do not call these default methods, our object will not be serialized/deserialized.

5 Different Ways to Create Objects in Java

Being Java developers, we usually create lots of objects daily, but we always use dependency management systems e.g. Spring to create these objects. However, there are more ways to create objects, which we will study in this article.

There are five total ways to create objects in Java, which are explained below with their examples followed by bytecode of the line which is creating the object.

Useful Git Commands

Git is a most widely used and powerful version control system for tracking changes in computer files and coordinating work on those files among multiple people. It is primarily used for source code management in software development, but it can be used to keep track of changes in any set of files.

Git was developed by Linus Torvalds in 2005 as an distributed open source software version control software and of course it is free to use. As a distributed revision control system it is aimed at speed, data integrity, and support for distributed, non-linear work flows.