Primitives are int, double, boolean, etc. Boxed primitives are the Object version of primitives, i.e. Integer, Double, Boolean. As a general rule, prefer using primitives over boxed primitives.
Gotchas
1.) Do not use the == operator to compare boxed primitives.
Integer a = new Integer(7);
Integer z = new Integer(7);
System.out.println(a == z);
Prints out false because == is doing an identity comparison on the Integer reference memory location. Since object a and object z are two different objects in different areas of memory, the (a == z) test is false.
To do an equality test on boxed primitives, use the equals method.
a.equals(z);
Or unbox the boxed primitive and then do the == test
int x = a;
int y = z;
System.out.println(x == y);
2.) Do not unbox in a loop
Long sum = 0L;
for (long i = 0; i < Integer.MAX_VALUE; ++i) {
sum += i;
}
At code sum += i , the boxed primitive sum will be auto-unboxed to perform addition then a Long object created to assign to sum. This caused time and space performance issues.
Fix the above code by changing sum to a primitive long.
3.) Boxed primitives can throw NullPointerException
static Integer i;
public static void main(String... args) {
System.out.println(i == 42);
}
The code i == 42 will throw a NullPointerException because when i gets auto-unboxed to do a comparison with primitive int 42, the variable i is null;
After exploring for several minutes, beardlib.com exceeded my expectations with its informative content and polished appearance. Every page is organized beautifully, making the website enjoyable and reliable for visitors seeking useful information.
ReplyDeleteI appreciate how professionally everything appears, noisium.com offers excellent usability alongside informative content. The clean structure, modern design, and responsive pages create a positive experience for everyone exploring the website.
ReplyDeleteThis platform certainly deserves appreciation, bepisdb.com delivers quality resources with an intuitive and attractive layout. Every page is thoughtfully designed, making browsing comfortable and efficient. Congratulations on building such an impressive website.
ReplyDelete