Primitive and object comparison with the == operator

I am wondering what is the internal Java behavior for the following snippet:

Long a = 123L;
long b = 123;
System.out.println("a equals b?: " + (a == b));

The result true, although the comparison of the two objects Longwill be false(because it compares their reference). Is this converting Java Longto its primitive value because it detects an operator ==against another primitive object?

+4
source share
2 answers

Is Java converting a long object to its primitive value because it detects the == operator against another primitive object?

. , .

JLS 15.21.1 ( ):

, , (. 5.1.8) , (§5.6.2).

, (§5.1.13), (§5.1.8).

, , , . JLS 15.21.3 :

, , .

+5

Java:

Autoboxing - , Java . , int Integer, .. , unboxing.

:

Character ch = 'a';

. , . () .

:

List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
    li.add(i);

int , , li, . li - , int, , Java . , Integer li. , :

List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
    li.add(Integer.valueOf(i));

(, int) (Integer) autoboxing. Java , :

  • , .
  • . :

    public static int sumEven (List li) {     int sum = 0;     for (Integer i: li)          (i% 2 == 0)             sum + = i;          ; }

(%) (+ =) Integer, , Java - . intValue Integer int :

public static int sumEven(List<Integer> li) {
    int sum = 0;
    for (Integer i : li)
        if (i.intValue() % 2 == 0)
            sum += i.intValue();
        return sum;
}

(Integer) primitive (int) . Java unboxing, -:

  • , .
  • .
+2

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


All Articles