DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Singleton: 6 Ways To Write and Use in Java Programming
  • Fluent Assertions Reloaded
  • How Cache Invalidation Caused Memory Pressure and API Failures at Scale
  • Memory Optimization and Utilization in Java 25 LTS: Practical Best Practices

Trending

  • Why Kotlin or Java Is the Wrong Question For Enterprises
  • Designing Frontend Applications for Failure, Not Just Success
  • Evals in CI: How to Catch Agent Regressions Before Production Does
  • Batching Strategies: Throughput vs Latency in Practice

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Data
  4. Why 1000 == 1000 Returns False, but 100 == 100 Returns True in Java?

Why 1000 == 1000 Returns False, but 100 == 100 Returns True in Java?

Here's a little code puzzler to help you be a little better at Java.

By 
A N M Bazlur Rahman
DZone Core CORE ·
Nov. 18, 15 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
60.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

This is probably one of the well discussed topic, but I found it interesting.

if you run the following code

    Integer a = 1000, b = 1000;  
    System.out.println(a == b);//1
    Integer c = 100, d = 100;  
    System.out.println(c == d);//2

You will get

false
true

Here are the basics:  we know that , if two references point to the same object, they are equal in terms of ==. If two references point to different objects, they are not equal in terms of == even though they have the same contents.

So here the last statement should be false as well.

This is actually where it gets interesting. If you look into the Integer.java class , you will find that there is an inner private class, IntegerCache.java that caches all Integer objects between -128 and 127.

So the thing is, all small integers are cached internally and when we declare something like –

Integer c = 100;

What it does internally is

Integer i = Integer.valueOf(100);

Now if we look into the valueOf() method , we will see-

    public static Integer valueOf(int i) {

      if (i >= IntegerCache.low && i
          return IntegerCache.cache[i + (-IntegerCache.low)];

      return new Integer(i);
    }

If the value is in the range -128 to 127, it returns the instance from the cache.

So...

Integer c = 100, d = 100;

basically points to the same object.

Thats why when we write

System.out.println(c == d);

We get true.

Now you might ask, why does this require caching?

Well, the logical rationale is that “smaller” integers in this range are used much more often than larger ones, so using the same underlying objects is worth it to reduce the potential memory footprint.

However, you can abuse this feature using the reflection API.

Run the following code, and enjoy the magic

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

      Class cache = Integer.class.getDeclaredClasses()[0]; //1
      Field myCache = cache.getDeclaredField("cache"); //2
      myCache.setAccessible(true);//3

      Integer[] newCache = (Integer[]) myCache.get(cache); //4
      newCache[132] = newCache[133]; //5

      int a = 2;
      int b = a + a;
      System.out.printf("%d + %d = %d", a, a, b); //
    }


Java (programming language) Object (computer science) Cache (computing) Memory (storage engine) API Data Types

Published at DZone with permission of A N M Bazlur Rahman. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Singleton: 6 Ways To Write and Use in Java Programming
  • Fluent Assertions Reloaded
  • How Cache Invalidation Caused Memory Pressure and API Failures at Scale
  • Memory Optimization and Utilization in Java 25 LTS: Practical Best Practices

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook