Skip to main content

NullPointerException in Java – Explaining the Billion Dollar Mistake

Null Pointer Exception Java

Credit: Adam Sinicki / Android Authority

While Java is one of the most in-demand and widely used programming languages in the world, it is not without its detractors. Java is not a particularly beginner-friendly language and it is rife with rigid rules and structures that can be tough to wrap your head around. Then there’s the NullPointerException.

Null pointer exception is an “exception” (error) that is particularly common when programming in Java. For a beginner, this is a confusing and daunting message to receive, but it can be just as much of a headache for pros to deal with! In fact, null pointer exceptions are so common and so damning, that they are referred to as “the billion-dollar mistake.” Ouch!

In this post, we’re going to unwrap the phrase to discover exactly what it means and what you should do when you encounter a null pointer exception in your own code!

What does null pointer exception mean?

First, we need to understand precisely what is meant by a pointer and how it can be null!

To do this, it helps to remember that a variable is actually a “pointer” that tells the computer to look at a certain location. That location will then contain a value, which is the value of the given variable.

So, if we say “int x = 3” then the computer will choose a location to call “x” and it will store the value “3” there. Whenever you refer to x further on in your code, the computer will look at that location and see that it is a “3” (unless you changed it). The variable points the computer to the right destination.

See also: Understanding variables in Java

This is why it’s useful to know the potential size of a variable first, as it tells the computer how much space to allocate for that value.

But what happens when you have a pointer that doesn’t point anywhere? That’s where the null pointer exception comes in.

Objects and references

An integer like “x” is what we call a “primitive type.” That means that it is a fundamental value.

An object, on the other hand, is a more complex data structure that can have multiple values and methods. Like primitive types, however, they still need to be stored somewhere and they still need an address and a pointer.

An example is String. This is not a primitive type in Java, but rather a reference type: in this case it “points” to a class that can have multiple values and methods. Once you have initialized an instance of a string, you can do things like:

myString.length();

This will tell you how long said string is by using the method that belongs to that class. But this is also what makes the null pointer exception possible because “length()” is a value that refers to a specific instance of an object. That means it acts on a specific string once it has been created.

Thus, you need to say:

String myString = “Hello”;
myString.length();

But were you to say:

String myString = null;
myString.length();

You would have created a pointer (myString) but that pointer does not point anywhere – it doesn’t know where to look. Another way to say this? The pointer is null.

The key thing to understand is that it is not that there is no value, but rather that the variable isn’t pointing anywhere for there to be a value.

There are certain coding design patterns that benefit from the ability to assign null values, so it’s a useful feature in those circumstances. As long as you remember that the object is null!

How to prevent null pointer exceptions Java

The reason that null pointer exceptions are so unpopular in Java is that they are runtime exceptions. That means the app will compile just fine and you’ll only hear about them when you reach that point in the code. It is, therefore, possible for a null pointer to slip through the net if you are initializing lots of objects on the fly.

This is why it’s useful to include measures to prevent null pointer exceptions during runtime.

The easiest way to do this?

if (myString == null) {
                return;
                }

This will help you to quickly check if an object is null, thereby circumventing code that would throw an exception. There are other tricks you can use, too. For example, when comparing strings, it’s a good move to invoke the method from the string literal, rather than the other way around:

If(“Hello!”.equals(myString)) {

Rather than:

If(myString.equals(“Hello!”)) {

You will avoid throwing an exception this way. OR you could just use Kotlin, which is “null safe” by design!

See also: Kotlin tutorial for Android for beginners: Build a simple quiz

Want to learn more about writing well-designed, flawless Java code? Then check out our guide to the best resources to learn Java. Or why not get started with our free, comprehensive Java tutorial for beginners?



source https://www.androidauthority.com/null-pointer-exception-1156263/

Comments

Popular posts from this blog

4 Surprising Ways Artificial Intelligence will Empower Consumers

Ever wonder what makes Siri search the items inside the iPhone and on the web by recognizing your voice? How does Google listening work? Artificial Intelligence and data science have already infused in this consumer-oriented generation, but we have not realized it yet. It has been quite a while that natural language processing, speech recognition, and gesture recognition system took over the market with their all new features, but what are the new things in AI that are yet to come? Few amazing transformations are: Retailing sector to become AI-ready Voice Recognition will change the game Search engines to become smarter Machine learning to bring revolutionary changes Recently we got to learn about a verbal spat between Elon Musk and Mark Zuckerberg over the probable risk and opportunities brought by AI . Believe it or not, but we already accustomed to Artificial Intelligence and probably waiting to witness jaw-dropping inventions. Some of AI inventions we have known till yet are: Mach

How to unhide or show folders in mx player list

In this blog post, I tell you about how to Show or Hide folders from MX player list. There are two methods to Show folder from MX Player list. Method 1: Unhide / show folders If you want to temporarily Show / Unhide hidden folder from MX Player list, then go to Settings and untick Recognize .nomedia ".  Method 2: Permanently unhide / show folder: Open memory by any file explorer and I recommend X-Plore, and open the folder that is Hidden and find the file " .nomedia ". If you didn't find it, you should first enable "Show files hidden files that starts with .(dot)". Delete the file and you just need to refresh MX Player list to take changes. Note: MX Player always hide those folders which file " .nomedia " exists.

How to use arrays in Python

Arrays in Python give you a huge amount of flexibility for storing, organizing, and accessing data. This is crucial, not least because of Python’s popularity for use in data science. But what precisely is an array? And how do you use arrays in Python? Also read: How to use dictionaries in Python Read on, and we’ll shed some light on the matter. What is an array? An array is a way to store multiple values in a single variable. That means that you can use a single “reference” in order to access your data. A list is also an example of a variable that stores multiple values, but has some slight differences. When using lists in Python, you store a series of values each with a numbered index. For example, this is how you would create a list of fruits in Python: fruits = [“apple”, “orange”, “pear”, “nectarine”] If we then say: print(fruits[3]) We will see “nectarine” appear on the screen (the first entry is stored as “0”). Also read: How to use lists in Python This is not an