Comparing Integer and Int

I'm new to java. Now I'm learning Integer's non-primitive type java. I know that the following comparison is invalid and throws a compilation error -

String str = "c";
Char chr = 'c';
if(str == chr) return true;

The above code snippet gives me the errors "Test.java:lineNumber: incomparable types: java.lang.String and char".

But I found that the following code fragment compiles fine -

int a = 1234;
Integer aI = 1234;
if(a==aI) return true; 

Here ais a primitive int and aIis non-primitive. So how are they comparable? I am new to programming, maybe there is something that I do not know.

thank

+4
source share
3 answers

unboxing. aI / . Integer int. int. , (boolean, byte, char, short, int, long, float, double) ( Boolean, Byte, Character, Short, Integer, Long, Float, Double).

, a aI, aI int, int. , -

int a = 1234;
Integer aI = 1234;
int a2 = aI.intValue();
if(a == a2) return true;

- String char. java , char String String char.

+2

unboxing. , . intInteger.

==, , , unboxing, .

, String char / - Characterchar.

5.1.8 JLS unboxing:

  • Boolean boolean
  • Byte to type byte
  • Short to type short
  • char
  • Integer int
  • Long to type long
  • Float to type float
  • Double to type double

5.1.7 , .

+4

In the first case, two types of data are different. Therefore, they cannot be compared. In the second case, the two data types are also different, but the shell Integeris created to support the primitive int. Therefore, the JVM automatically performed shell conversion (decompression) Integerto int, and then compare. So in the second case, two primitives are intcompared with each other at the end.

0
source

Source: https://habr.com/ru/post/1599161/


All Articles