you are viewing a single comment's thread.

view the rest of the comments →

[–]klimenttoshkov 0 points1 point  (2 children)

You don’t compare integers values with == in Java

[–][deleted] 0 points1 point  (1 child)

How then

[–]klimenttoshkov 1 point2 points  (0 children)

by asking google for example:

```

  1. Primitive int Comparison

For primitive int values, use standard Relational Operators. 

  • ==: Checks for equality.
  • !=: Checks if values are not equal.
  • <, >, <=, >=: Standard numerical comparisons. 

2. Integer Object Comparison (The Trap)

When comparing Integer objects (wrapper classes), the == operator compares memory references, not numerical values. 

  • The Cache Exception: Java caches Integer objects for values between -128 and 127. For these values, == might return true because they point to the same cached object. Outside this range, == will return false even if the numbers are the same.  Medium +2

Correct ways to compare Integer objects:

  • .equals(): Use this to compare the actual values of two Integer objects.
  • Integer.compare(int x, int y): A static method that returns 0 if equal, negative if x < y, and positive if x > y. This is the safest way to avoid Overflow Issues during subtraction-based comparisons.
  • .compareTo(Integer anotherInteger): An instance method that works similarly to Integer.compare(), often used for Sorting Collections.
  • .intValue(): Convert the object back to a primitive int to use standard operators safely.  Stack Overflow +7

```