How to avoid NPE while Auto-Unboxing

Auto-Boxing/Unboxing is introduced in Java 5 version. It supports automatic conversion of primitive type (int, boolean, float, double) to their equivalent Objects ( Integer, Boolean, Float, Double) in assignment , method and constructor invocation and other way also. Here is the examples

Auto-Boxing

Integer i = 10; // Auto-boxing converts primitive int value to Integer Object

Auto-Unboxing

int i = 0;

i= new Integre(10); // Auto-Unboxing converts Integer Object to primitive int

There is serious problem with using Auto-bocing/Unboxing, it may result null pointer exception. Take an example of following program

package testproject;

public class TestAutoUnboxing {

private static TestAutoUnboxing test= new TestAutoUnboxing(); //cause Null Pointer Exception
public static final Boolean YES = true; // Autoboxing for
private boolean amIHappy = YES; // Instance Variable

public static void main(String[] args){
System.out.println("Inside Main");
}
}

This example will cause null pointer exception. Here test is an Object of same class TestAutoUnboxing and it is private and static, it is like Singleton Object. As execution of class is sequential, test object will get instantiated and for that all instance variable has to instatiate. So amIHappy set to value of YES, but YES is not yet initialized to value true. So YES is hold neither true nor false. So non initialized Boolean object is assigned to primitive variable amIHappy auto-unboxing will cause null pointer exception. Here is the exception trace

java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at testproject.TestAutoUnboxing.<init>(TestAutoUnboxing.java:7)
at testproject.TestAutoUnboxing.<clinit>(TestAutoUnboxing.java:5)
Could not find the main class: testproject.TestAutoUnboxing. Program will exit.
Exception in thread "main" Java Result: 1

Exception stack trace shows that exception trace starts at line 5 and ends at 7. Line no 5 is test object initialization and line 7 is amIHappy instance variable initialization . To avoid this NPE sequence of statements need to be changed as below.

package testproject;

public class TestAutoUnboxing {

//private static TestAutoUnboxing test= new TestAutoUnboxing(); //cause Null Pointer Exception
public static final Boolean YES = true; // Autoboxing for
private boolean amIHappy = YES; // Instance Variable
private static TestAutoUnboxing test= new TestAutoUnboxing();
public static void main(String[] args){
System.out.println("Inside Main");
}
}

Now this program will run successfully without any error. Here By the time test get initialized static variable YES would have been initialized and auto-unboxing while assigning value to amIHappy instance variable goes fine without any error.

Best practice of avoiding such problems, make use of boolean primitive type instead of mix of object and primitive variable.

Comments

  1. What's the point of this ugliest code formatting used here? Do you really expect someone will decipher those center-aligned text? I will definitely not under any circumstances. This is just disrespecting your readers. No, never, ignored.

    ReplyDelete
  2. Booty calls modded apk is a very popular topic at present and that is because it is a very exciting way to make money. The booty calls app is very popular, especially with men, and with the right mods you can earn yourself money and other resources.

    ReplyDelete
  3. Fm whatsapp apk is a simple to use but powerful android app for sending and receiving text messages, images, videos and audios via android phones and tables. Download our Fm whatsapp apk and get the unlimited features.

    ReplyDelete
  4. This guide provides a lot of tips to help you have a smooth and enjoyable experience while playing Lovestruck Choose Your Romance Mod APK. I hope that you’ll find this article to be very useful and that you’ll be able to have fun while playing it.

    ReplyDelete
  5. Football Strike Mod Apk is one of the most popular sports in the world. Millions of people around the globe follow professional football matches and teams. This game has a very complex rule set, which makes it hard for new players to learn the game. This blog will cover the basics of football, making it easy for new players to understand.

    ReplyDelete
  6. GTA Vice City OBB is a popular video game. The game is set in Miami, Florida. Players can choose to play as one of several different characters. The game allows players to engage in various activities, such as driving cars and motorcycles, shooting people, and flying helicopters.

    ReplyDelete
  7. Zedge modded is a great app for customizing your Android phone. With it, you can change the wallpaper, ringtone, and notification sound on your phone. You can also find new ringtones, wallpapers, and notification sounds by browsing the Zedge website. The app is free to download and use.

    ReplyDelete
  8. Pixaloop Pro 2022 is an app that lets you create gifs and videos with a simple, user-friendly interface. You can add movement and life to your photos in seconds, without having to learn complicated editing software. With Pixaloop Pro, you can easily create professional-quality animations right on your phone.

    ReplyDelete
  9. Plotagon story mod download is an android app that lets you create your own stories with just a few taps. You can choose from a variety of characters, settings, and props to create your story. The app also includes built-in sound effects and music to help you create a more immersive experience.

    ReplyDelete
  10. Androrat Apk is a new app designed to help people connect with those who are important to them. The app allows users to post messages, photos and videos with ease. Androrat also provides a social networking platform for people to connect with others in their area.

    ReplyDelete
  11. 8 ball pool mod apk unlimited money cash and cues is a fun, challenging and fast-paced game that can be enjoyed by all. There are many different ways to improve your skills in this game, and the best way to do that is by using a mod apk. Mod apks allow you to customize the game to make it more your own, and there are many different ones available online. So if you're looking for a way to improve your 8 ball pool skills, consider using a mod apk.

    ReplyDelete
  12. University Empire Tycoon is a game that allows you to manage a university. You take charge of students and their dormitories, make sure they are progressing in their studies and help them graduate with honors. The game offers an excellent opportunity to practice your managerial skills while managing various aspects of an educational institution. And you can do this using the university empire tycoon mod apk free shopping /

    ReplyDelete

Post a Comment

Popular posts from this blog

Composite Design Pattern by example

State Design Pattern by Example

Eclipse command framework core expression: Property tester