Saturday, November 19, 2011

Java Mysteries


What shall be the output of the code?


I found this Question in one of the Java Groups on LinkedIn. Wanted to share with all of you?

  public class JavaMysteryCode {

      public static void main(String args[]) {
            Integer a = 100;
            Integer b = 100;
            Integer c = 5000;
            Integer d = 5000;
            if (a == b) {
                  System.out.println("a & b Both are Equal");
            }
            else {
                  System.out.println("a & b are Not Equal");
            }
            if (c == d) {
                  System.out.println("c & d Both are Equal");
            } else {
                  System.out.println("c & d are Not Equal");
            }
      }
}

Out is as Below:

a & b Both are Equal
c & d are Not Equal // This was not expected right.

At first shot I was also shocked and not able to figure out the Correct output and Why?

Thanks to Gulshan (http://in.linkedin.com/in/gulmathur) for providing the Answer:

JVM has Pool memory for constants from Integer values -128 to 127, so if you create two or more Integer Ref having value from -128 to 127 then they all are pointing to a same memory area. So a and b both having value in range of 1 byte they are referring same memory address while c and d contain value outside this range and memory address for c and d are diff.

4 comments:

  1. Was quite surprised looking at the output.
    Useful tip.

    ReplyDelete
    Replies
    1. How large a cache you want is configurable in most JVMs by the way.

      Delete
    2. Its Javas way to optimize memory usage...

      Delete
  2. This is the really Socking!!!

    How does JAVA optimize the memory usage using such limitation?

    ReplyDelete