Boxing and Unboxing in Java with Examples

In Java, we are facing the term Boxing and UnBoxing and in this short article, I will share with you what is boxing and unboxing in Java with basic examples.

Let say, we have an integer variable and it is a primitive integer variable that should be declared by “int” keyword. Also, we have a reference type for integers which is declared by “Integer“.

Now, let’s make it more tangible with some examples!

Boxing and Unboxing Example in Java

public class BoxingUnBoxing {
    @Test
    public void boxingUnBoxing() {
        //Boxing
        int counter = 30;
        Integer boxedCounter = counter;
        System.out.println("Boxed Counter: " + boxedCounter);

        //UnBoxing
        int unboxedCounter = boxedCounter;
        System.out.println("Unboxed Counter: " + unboxedCounter);
    }
}

The output:

boxing and unboxing in java

GitHub Project

https://github.com/swtestacademy/java-functional/blob/main/src/test/java/basics/boxingunboxing/BoxingUnBoxing.java 

Thanks for reading. 
Onur Baskirt

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.