Weird Integer boxing in Java

前端 未结 12 2087
广开言路
广开言路 2020-11-22 00:15

I just saw code similar to this:

public class Scratch
{
    public static void main(String[] args)
    {
        Integer a = 1000, b = 1000;
        System.o         


        
12条回答
  •  日久生厌
    2020-11-22 01:03

    Integer Cache is a feature that was introduced in Java Version 5 basically for :

    1. Saving of Memory space
    2. Improvement in performance.
    Integer number1 = 127;
    Integer number2 = 127;
    
    System.out.println("number1 == number2" + (number1 == number2); 
    

    OUTPUT: True


    Integer number1 = 128;
    Integer number2 = 128;
    
    System.out.println("number1 == number2" + (number1 == number2);
    

    OUTPUT: False

    HOW?

    Actually when we assign value to an Integer object, it does auto promotion behind the hood.

    Integer object = 100;
    

    is actually calling Integer.valueOf() function

    Integer object = Integer.valueOf(100);
    

    Nitty-gritty details of valueOf(int)

        public static Integer valueOf(int i) {
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }
    

    Description:

    This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

    When a value within range of -128 to 127 is required it returns a constant memory location every time. However, when we need a value thats greater than 127

    return new Integer(i);

    returns a new reference every time we initiate an object.

    == operators in Java compares two memory references and not values.

    Object1 located at say 1000 and contains value 6.
    Object2 located at say 1020 and contains value 6.

    Object1 == Object2 is False as they have different memory locations though contains same values.

提交回复
热议问题