- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Comparison of autoboxed integer object in Java
When we assigned an int to Integer object, it is first converted to an Integer Object and then assigned. This process is termed as autoboxing. But there are certain things which you should consider while comparison of such objects using == operator. See the below example first.
Example
public class Tester { public static void main(String[] args) { Integer i1 = new Integer(100); Integer i2 = 100; //Scenario 1: System.out.println("Scenario 1: " + (i1 == i2)); Integer i3 = 100; Integer i4 = 100; //Scenario 2: System.out.println("Scenario 2: " + (i3 == i4)); Integer i5 = 200; Integer i6 = 200; //Scenario 3: System.out.println("Scenario 3: " + (i5 == i6)); Integer i7 = new Integer(100); Integer i8 = new Integer(100); //Scenario 4: System.out.println("Scenario 4: " + (i7 == i8)); } }
Output
Scenario 1: false Scenario 2: true Scenario 3: false Scenario 4: false
Scenario 1 - Two Integer objects are created. The second one is because of autoboxing. == operator returns false.
Scenario 2 - Only one object is created after autoboxing and cached as Java caches objects if the value is from -127 to 127. == operator returns true.
Scenario 3 - Two Integer objects are created because of autoboxing and no caching happened. == operator returns false.
Scenario 4 - Two Integer objects are created. == operator returns false.
- Related Articles
- Comparison of double and float primitive types in Java\n
- Create an Integer object in Java
- Comparison of Float in Java
- Object comparison Complexity in JavaScript using comparison operator or JSON.stringlify()?
- Comparison of floating point values in PHP.\n
- String Comparison in Java
- Python Object Comparison “is” vs “==”
- Assigning an integer to float and comparison in C/C++
- Comparison of Java and .NET
- Convert JSON object to Java object using Gson library in Java?\n
- Comparison between endl and \n in C++
- Comparison of Exception Handling in C++ and Java
- How to convert an object array to an integer array in Java?
- Case sensitive string comparison in Java.
- Java String Comparison Methods.

Advertisements