Comparing boxed Long values 127 and 128

后端 未结 4 1184
忘掉有多难
忘掉有多难 2020-11-27 10:48

I want to compare two Long objects values using if conditions. When these values are less than 128, the if condit

4条回答
  •  爱一瞬间的悲伤
    2020-11-27 11:05

    Java caches the primitive values from -128 to 127. When we compare two Long objects java internally type cast it to primitive value and compare it. But above 127 the Long object will not get type caste. Java caches the output by .valueOf() method.

    This caching works for Byte, Short, Long from -128 to 127. For Integer caching works From -128 to java.lang.Integer.IntegerCache.high or 127, whichever is bigger.(We can set top level value upto which Integer values should get cached by using java.lang.Integer.IntegerCache.high).

     For example:
        If we set java.lang.Integer.IntegerCache.high=500;
        then values from -128 to 500 will get cached and 
    
        Integer a=498;
        Integer b=499;
        System.out.println(a==b)
    
        Output will be "true".
    

    Float and Double objects never gets cached.

    Character will get cache from 0 to 127

    You are comparing two objects. so == operator will check equality of object references. There are following ways to do it.

    1) type cast both objects into primitive values and compare

        (long)val3 == (long)val4
    

    2) read value of object and compare

        val3.longValue() == val4.longValue()
    

    3) Use equals() method on object comparison.

        val3.equals(val4);  
    

提交回复
热议问题