What is difference between of listofIntegers.add(ValueOf(50)); and listofIntegers.add(50); in Java
Asked Answered
E

1

6

What is the difference between these 2 codes:

Arraylist<Integer> listofIntegers = new Arraylist<Integer>();
listofIntegers.add(666);
System.out.println("First Element of listofIntegers = " + listofIntegers.get(0));

And

Arraylist<Integer> listofIntegers = new Arraylist<Integer>();
listofIntegers.add(Integer.ValueOf(666));
System.out.println("First Element of listofIntegers = " + listofIntegers.get(0));

Both of them have the same output.

Thank you.

Evalynevan answered 14/1, 2018 at 16:9 Comment(2)
Same, you just perform boxing explicitly by calling Integer.valueOf(...)Venal
Exactly the same. The compiler will turn the first into the second. Now ask what happens when you call new Integer(666)...Carvelbuilt
D
21

The boxing conversion uses Integer.valueOf implicitly, so there's no difference between the two.

For example, consider this code:

public static void main(String[] args) {
    Integer x = 100;
    Integer y = Integer.valueOf(100);
}

The byte code for that (as shown by javap) is:

public static void main(java.lang.String[]);
    Code:
       0: bipush        100
       2: invokestatic  #2                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
       5: astore_1
       6: bipush        100
       8: invokestatic  #2                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
      11: astore_2
      12: return

As you can see, the two pieces of code are identical.

Although the language specification section on boxing doesn't guarantee that it will be implemented by valueOf, it does guarantee limited caching:

If the value p being boxed is the result of evaluating a constant expression (§15.28) of type boolean, char, short, int, or long, and the result is true, false, a character in the range '\u0000' to '\u007f' inclusive, or an integer in the range -128 to 127 inclusive, then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.

This is the same guarantee made by Integer.valueOf.

Dimaggio answered 14/1, 2018 at 16:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.