Why Java does not see that Integers are equal?

后端 未结 6 1784
野的像风
野的像风 2020-11-29 06:51

I have integers that are supposed to be equal (and I verify it by output). But in my if condition Java does not see these variables to have the same value.

6条回答
  •  情深已故
    2020-11-29 07:00

    In java numeric values within range of -128 to 127 are cached so if you try to compare

    Integer i=12 ;
    Integer j=12 ; // j is pointing to same object as i do.
    if(i==j)
       print "true";
    

    this would work, but if you try with numbers out of the above give range they need to be compared with equals method for value comparison because "==" will check if both are same object not same value.

提交回复
热议问题