In today's world there are multiple levels of abstraction everywhere. Since why would you go extra mile to re-invent a wheel if the car already exists. Just like that there are multiple levels in java architecture as well. In that context, one of the in-build concept is Boxing.
Well its not a cardboard box where you store stuff. But it's a way to handle memory and objects by optimizing performance too. To understand Boxing, we first need to introduce ourselves 2 core techniques in java -
- Primitive Data type
- Wrapper classes
Primitive Data type refers to int, float, double etc. And Wrapper classes are Object Templates build around the data types to convert a primitive data type to corresponding Objects, like Integer, Float, Character etc.
Like,
Integer wraps int
Character wraps char
Now coming to the point of boxing - There are again 2 terminologies
- Autoboxing
- Unboxing
In Autoboxing a primitive data type(e.g. int) is converted to its corresponding wrapper class(e.g. Integer)
List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
li.add(i);
In the example above, even though li is a Integer type ArrayList but the compiler autoboxes the primitive values to Integer to treat the elements as "int" objects. You can say this is one of the distinguishing factor between arrays and Lists.
And in Unboxing wrapper class is converted to its primitive type.
int sum = 0;
List<Integer> list = new ArrayList<>();
for (Integer i : list) {
// Unboxing of i automatically
if (i % 2 != 0)
sum += i;
// Unboxing of i is done automatically using intvalue implicitly
if (i.intValue() % 2 != 0)
sum += i.intValue();
}
for more info you can visit https://www.geeksforgeeks.org/java/autoboxing-unboxing-java/ as well as oracle docs.
Now where does Streams come into picture?
Java from version 8 onwards introduced Streams. Which are basically a unique way to handle stream/collection of objects. Previously how we used to handle collections is by using collections framework and arrays. But Streams provide a wide variety of usages as it supports functional programming and lambdas. It makes managing a pool of objects very swift.
As I said Streams are flow of objects not their primitives. You can have stream of employees, cars, and all kinds of objects. But what if you need to work with only int values. But here comes an extra hurdle of managing stream of objects. But java has a native solution to this problem - intStream. Let's say you need to search an item in a stream of employees and need to get int as return then use intStream.
This image is from one of my projects -

But why to use intStream not regular Streams-
- int processing will be faster in terms of performance
- Since we know the outcome is int, then it saves writting extra logic
- No need to manual unboxing
Well, I am not very good at explaining but dear readers you can always google it, oops๐ I mean GPT it.๐
Top comments (0)