g.pickardou
g.pickardou

Reputation: 35843

Does occur any boxing/unboxing in this code?

Given the following code, does the Java compiler apply any boxing/unboxing this case?

public static Integer sum(Iterable<Integer> numbers){
    Integer sum = 0;
    for(Integer n : numbers){
        sum += n;
    }

    return sum;
}

Upvotes: 2

Views: 82

Answers (2)

Markus Steppberger
Markus Steppberger

Reputation: 638

Here the int 0 is auto-boxed to an Integer sum:

Integer sum = 0;

Here the values are unboxed as the unary plus operator only applies to int:

sum += n;

Here no unboxing happens as you iterate over Integers:

for(Integer n : numbers)

Unboxing in a for loop can happen if you do (e.g.):

for(int n : numbers)

See Autoboxing and Unboxing for very similar examples and explanations.

Upvotes: 1

Darshan Mehta
Darshan Mehta

Reputation: 30819

Yes, Integer object is converted into int literal while performing the addition with + operator. Have a look at this link. It says the following:

Because the remainder (%) and unary plus (+=) operators do not apply to Integer objects, you may wonder why the Java compiler compiles the method without issuing any errors. The compiler does not generate an error because it invokes the intValue method to convert an Integer to an int at runtime.

Upvotes: 1

Related Questions