Member-only story
Unraveling the Mystery: Why Comparing 1 to 1 and 128 to 128 in Java Can Have Different Outcomes
In Java, the comparison operators (like ==) are used to compare two values or expressions. At first glance, using these operators seems straightforward, but there’s more than meets the eye, especially when it comes to comparing objects and primitives in Java.
You might think that checking if one number equals another is simple. For small numbers, this seems to be straightforward, as 1==1 returns true
. However, for seemingly similar comparisons with larger numbers, such as 128==128, we might get false
. This might seem illogical.
To understand this behavior, we need to delve into the world of Java and explore how it handles data types, memory allocation, and the difference between primitive data types and object references.
Primitive Types and Object References in Java
Java has two major data type categories: primitives and objects (or reference types).
Primitive types include byte
, short
, int
, long
, float
, double
, char
, and boolean
. These types hold the actual values and are stored in the stack memory. Therefore, when you compare two primitive values using the ==
operator, you compare their actual values.
int a = 1;
int b = 1…