Search⌘ K
AI Features

Boxing

Explore Java boxing mechanisms and the caching behavior of wrapper classes like Integer and Boolean. Learn why comparisons using == differ based on cached values, and understand how this relates to memory optimization and the flyweight pattern in Java.

We'll cover the following...
1.

What is boxing or autoboxing?

Show Answer
Did you find this helpful?
Technical Quiz
1.

What will be the output of the following code snippet?

        Long value = 7L;
        System.out.println(value.equals(7));
A.

True

B.

False


1 / 1
Technical Quiz
1.

What will be printed when the following Java code is executed?

        Long value1 = 7L;
        System.out.println(value1 == 7);
A.

true

B.

false


1 / 1
Technical Quiz
1.

What will be the output of the following change made to the snippet presented earlier?

        Long value = 7L;
        System.out.println(value.equals(7L));
A.

true

B.

false


1 / 1
Technical Quiz
1.

What will be printed when the following Java code is executed?

        Long value1 = 7L;
        Long value2 = 7L;
        System.out.println(value1 == value2);
A.

true

B.

false


1 / 1
Technical Quiz
1.

What will be the output of the following snippet?

        Long value1 = 7L;
        Long value2 = 7L;
        System.out.println(value1.equals(value2));
A.

true

B.

false


1 / 1
Technical Quiz
1.

What will be the output when the following Java code is executed?

        Long value1 = 20007L;
        System.out.println(value1 == 20007L);
A.

true

B.

false


1 / 1
Technical Quiz
1.

What will be the output of the following Java code?

        Long value1 = 20007L;
        Long value2 = 20007L;
        System.out.println(value1 == value2);
A.

true

B.

false


1 / 1

Questions 4 - 8 are below:

Java
class Demonstration {
public static void main( String args[] ) {
Long value = 7L;
System.out.println("\nLong value = 7L;\nvalue.equals(7) " + value.equals(7));
System.out.println("value == 7 " + (value == 7));
System.out.println("value.equals(7L) " + value.equals(7L));
Long value1 = 7L;
Long value2 = 7L;
System.out.println("\n\nLong value1 = 7L;\nLong value2 = 7L;\nvalue1 == value2 " + (value1 == value2));
System.out.println("value1.equals(value2) " + value1.equals(value2));
value1 = 20007L;
value2 = 20007L;
System.out.println("\n\nvalue1 = 20007L;\nvalue2 = 20007L;\nvalue1 == 20007L " + (value1 == 20007L));
System.out.println("value1 == value2 " + (value1 == value2));
System.out.println("value1.equals(20007L) " + value1.equals(20007L));
}
}

Note in the above snippet how the comparison using == operator for the variables initialized to 7 yields true, whereas the same comparison when values are initialized ...