Null Pointer Exceptions In Java - What EXACTLY They Are and How to Fix Them

Coding with John
28 Feb 202214:20

Summary

TLDRIn this Java tutorial, John, a lead Java software engineer, explains the common issue of NullPointerExceptions. He illustrates with examples how uninitialized or null-assigned variables can cause this exception. John advises using Java primitives over wrapper classes to avoid null values and suggests initializing variables properly. He also recommends returning empty collections instead of null to prevent NullPointerExceptions. For debugging, he highlights how Java 14's improved error messages can pinpoint the cause of the exception. Finally, John offers strategies for avoiding NullPointerExceptions, like null checks and proper initialization.

Takeaways

  • 🐱 NullPointerException is one of the most common and troublesome exceptions in Java, often causing many bugs.
  • πŸ” NullPointerException occurs when you try to use an object reference that is not pointing to any object (null).
  • 🚫 Calling methods or accessing fields on a null object will result in a NullPointerException.
  • πŸ‘¨β€πŸ’» Always initialize variables properly and avoid setting them to null unless necessary.
  • πŸ‘€ Recent versions of Java (starting from Java 14) provide detailed error messages for NullPointerExceptions, making it easier to identify the cause.
  • πŸ”’ Use primitive types (e.g., boolean) instead of their wrapper classes (e.g., Boolean) when possible, as they can't be set to null.
  • πŸ“‹ When working with collections, initialize them to an empty list instead of null to avoid NullPointerExceptions during iterations.
  • πŸ”„ Use null checks before performing operations on variables that might be null to prevent exceptions.
  • πŸ’‘ For string comparisons, use `"literal".equals(variable)` instead of `variable.equals("literal")` to avoid null-related errors.
  • πŸ›  If you encounter a NullPointerException, either ensure the variable is properly initialized or use null checks to handle potential null values.

Q & A

  • What is a Null Pointer Exception in Java?

    -A Null Pointer Exception occurs when you try to call a method or access a field on an object reference that has been set to null, meaning it points to no object in memory.

  • Why is the Null Pointer Exception common in Java?

    -It's common because Java allows object references to be null, and developers might not always check for null before using these references, leading to attempts to perform operations on a non-existent object.

  • How can you cause a Null Pointer Exception with a Cat object in Java?

    -You can cause a Null Pointer Exception by setting a Cat object reference to null and then trying to call a method on it, like 'myCat.makeNoise()'.

  • What does 'null' signify in Java?

    -In Java, 'null' signifies the absence of an object reference, meaning the reference does not point to any object in memory.

  • How do you fix a Null Pointer Exception when it occurs?

    -To fix a Null Pointer Exception, you can either initialize the null variable with an actual object or add a null check before performing operations on the variable.

  • What is the benefit of using Java primitives over wrapper classes when dealing with null?

    -Java primitives like 'boolean' cannot be null, whereas wrapper classes like 'Boolean' can. Using primitives avoids the risk of Null Pointer Exceptions.

  • Why might initializing a collection to null cause a Null Pointer Exception?

    -Initializing a collection to null and then trying to iterate over it or access elements can cause a Null Pointer Exception because the collection itself is null and does not contain any elements.

  • How do recent versions of Java help when a Null Pointer Exception occurs?

    -Recent versions of Java provide more detailed error messages that specify which method or field access caused the exception, making it easier to identify and fix the problem.

  • What is a null check and why is it important?

    -A null check is a condition that verifies if an object reference is null before performing operations on it. It's important to prevent Null Pointer Exceptions when dealing with potentially null references.

  • What strategies can you use to avoid Null Pointer Exceptions in your Java code?

    -Avoid initializing variables to null, return empty collections instead of null from methods, and use primitive types over wrapper classes to reduce the likelihood of encountering null values.

  • How can you safely compare a string to a string literal in Java without causing a Null Pointer Exception?

    -You can safely compare a string to a string literal by using the string literal on the left side of the equals method, so if the string is null, the literal will not cause a Null Pointer Exception.

Outlines

00:00

🐾 Understanding Null Pointer Exceptions in Java

This paragraph introduces the concept of a Null Pointer Exception (NPE) in Java, which is a common source of bugs. The speaker, John, a lead Java software engineer, explains NPEs with an example involving a 'Cat' object. He demonstrates that when a variable like 'myCat' is set to null instead of referencing an actual object, attempting to call a method on it results in an NPE. The explanation includes the difference between a variable referencing an object and being null, which means it points to nothing. John also discusses other scenarios that can lead to NPEs, such as using a Boolean wrapper class set to null or trying to access elements from a null collection.

05:00

πŸ” Diagnosing and Fixing Null Pointer Exceptions

In this section, the video script discusses how to address Null Pointer Exceptions once they occur. John explains that modern Java versions provide detailed error messages that can help pinpoint the exact cause of an NPE. He suggests two approaches to fixing NPEs: initializing the null variable with a value, or performing a null check before using the variable. The paragraph provides examples of both methods, emphasizing the importance of null checks in complex method chains and the use of empty collections instead of null to avoid exceptions.

10:03

πŸ›  Strategies to Prevent Null Pointer Exceptions

The final paragraph focuses on preventative measures to avoid Null Pointer Exceptions. John advises against initializing variables to null unless absolutely necessary and suggests returning empty collections instead of null from methods. He also provides a tip for string comparisons, recommending the reversal of the comparison to avoid NPEs when dealing with potentially null strings. The paragraph concludes with a call to action for viewers to like, subscribe, and check out a full Java course for more in-depth learning.

Mindmap

Keywords

πŸ’‘Null Pointer Exception

A Null Pointer Exception occurs when a program attempts to use a reference that points to no location in memory (null). In the video, it is described as one of the most common exceptions in Java, often caused by trying to call methods or access fields on an object that has not been properly initialized. The presenter demonstrates this with the example of a 'Cat' object, where calling a method on a null reference leads to the error.

πŸ’‘Reference

In Java, a reference points to the memory location where an object is stored. The video explains how a variable like 'myCat' is not the actual object but a reference to it. When this reference is null (i.e., it points to nothing), attempting to perform operations on it, such as calling methods, leads to a Null Pointer Exception.

πŸ’‘Memory

Memory refers to the storage location where objects and variables are held during program execution. The video emphasizes that when a reference variable points to a valid memory location containing an object, operations like method calls can be performed. If a reference points to null, it means there's no object in memory to interact with, causing an exception.

πŸ’‘Wrapper Class

A wrapper class in Java provides a way to use primitive data types (like int, boolean) as objects. In the video, the presenter discusses the 'Boolean' wrapper class (capital 'B'), which can be null, unlike the primitive 'boolean' (lowercase 'b'). This distinction is important as it can lead to a Null Pointer Exception when a null Boolean is used in conditional statements.

πŸ’‘Primitive Type

Primitive types in Java are basic data types like int, boolean, and char, which cannot be null and always have a default value. The presenter contrasts primitive types with wrapper classes, explaining that using primitive booleans avoids the risk of a Null Pointer Exception, since they are never null.

πŸ’‘Null Check

A null check is a programming practice where a variable is checked to see if it is null before performing operations on it. The video introduces null checks as a solution to avoid Null Pointer Exceptions. The presenter demonstrates how adding a condition like 'if (myCat != null)' prevents the program from calling methods on a null object.

πŸ’‘Method Invocation

Method invocation refers to calling a method on an object in Java. The video highlights how invoking a method on a null reference (like 'myCat.makeNoise()' when 'myCat' is null) will lead to a Null Pointer Exception. Proper initialization or a null check is necessary before invoking methods to avoid this error.

πŸ’‘Collection

A collection in Java is a data structure like a List, Set, or Map that holds multiple elements. The presenter uses the example of a list of 'favoriteCheeseburgers' to explain how iterating over a null collection can also cause a Null Pointer Exception. Best practice is to initialize collections as empty rather than null.

πŸ’‘Empty List

An empty list is a collection that contains no elements but is still a valid object in memory. In the video, the presenter explains that it's safer to initialize a list as empty rather than null, because iterating over an empty list won't throw a Null Pointer Exception, while iterating over a null list will.

πŸ’‘String Comparison

String comparison in Java is typically done using the '.equals()' method. The video covers how calling '.equals()' on a null string leads to a Null Pointer Exception. The presenter suggests flipping the comparison, using the string literal (which is never null) as the base, to avoid this error.

Highlights

Java's null pointer exception is one of the most common and problematic bugs.

A null pointer exception occurs when a variable set to null is used to call a method.

In Java, a variable is a reference to an object in memory, not the object itself.

Setting a variable to null means it points to nothing, causing a null pointer exception when a method is called on it.

Using Java's primitive types can prevent null pointer exceptions, as they cannot be set to null.

Java's wrapper classes, like Boolean, can be set to null and may cause null pointer exceptions.

Initializing collections to empty instances instead of null can prevent null pointer exceptions.

Java 14 and later provide detailed error messages for null pointer exceptions, aiding in debugging.

To fix a null pointer exception, ensure variables are initialized before use.

Performing null checks before method calls can prevent null pointer exceptions.

Avoid initializing variables to null unless absolutely necessary.

Returning empty collections instead of null from methods can prevent null pointer exceptions.

Flipping string comparisons can avoid null pointer exceptions when dealing with potentially null strings.

Always use null checks when dealing with external code where null values might be present.

The video provides a full Java course for further learning.

The video encourages viewers to subscribe for more Java tutorials.

Transcripts

play00:00

if you've been coding in java for any

play00:01

length of time you've definitely run

play00:03

into the dreaded null pointer exception

play00:06

it's one of the most common exceptions

play00:08

and probably the biggest source of bugs

play00:10

in all of java in this video we'll talk

play00:12

about what exactly causes a null pointer

play00:14

exception how to fix it when you

play00:16

encounter one and strategies for

play00:18

avoiding them in the first place my name

play00:20

is john and i'm a lead java software

play00:21

engineer i also have a full java course

play00:23

available in a link down in the

play00:24

description so go check it out first

play00:26

what exactly causes a null pointer

play00:28

exception let's talk about it with an

play00:30

example let's say you're coding along

play00:32

and at some point you decide you need a

play00:34

new cat object so you go ahead and

play00:35

create cat my cat equals new cat and

play00:39

let's say you want to make that cat make

play00:41

noise so you go ahead and call it's make

play00:44

noise method with my cat dot make noise

play00:47

and we can see that in that method it

play00:49

just prints out meow so of course if we

play00:51

go back here and run our program that's

play00:54

exactly what it does it just prints out

play00:56

meow but what if instead of

play00:57

instantiating this my cat variable to a

play01:00

new cat we instead set it to null let's

play01:03

go ahead and run it and see what happens

play01:05

and oh no we get the dreaded null

play01:08

pointer exception now why exactly is

play01:11

that sure we can see that we're setting

play01:13

our mycat variable to null but what

play01:15

exactly does null mean and why does our

play01:18

code now result in a null pointer

play01:21

exception to visualize it so what we

play01:23

have in our code is a mycat variable

play01:26

right that my cat variable isn't a cat

play01:29

object itself but instead it's a

play01:31

reference to a cat object in memory so

play01:35

when we instantiate our mycat variable

play01:38

to a new cat that means this my cat

play01:41

variable is now a reference to an actual

play01:44

cat object in memory so after that when

play01:48

we call my cat dot make noise it has no

play01:51

problem doing that at all our my cat

play01:53

variable references an actual cat object

play01:56

in memory and so we're able to tell this

play01:58

cat object to make noise with no problem

play02:02

but what happens if instead we set it to

play02:05

null well instead of my cat pointing to

play02:08

an actual cat object in memory it's

play02:10

instead null which essentially means

play02:13

it's pointing at nothing not even like

play02:16

some empty box with no cat in it it's

play02:18

pointing to nothing at all this is a

play02:21

null pointer so when we call the make

play02:24

noise method on our my cat variable that

play02:26

has been set to null there's no cat to

play02:29

make noise we have a mycat variable but

play02:32

it's not pointing to any actual cat

play02:34

object there's nothing to meow all we

play02:37

have is a null pointer and so we get a

play02:40

null pointer exception in our code most

play02:43

of the time when we get a null pointer

play02:44

exception this is the reason we have

play02:47

some variable that's been set to null

play02:49

and we try to call some method on it

play02:51

more generally speaking just having some

play02:53

variable set to null won't give you a

play02:55

null pointer exception but you will get

play02:57

a null pointer exception if you try to

play02:59

do pretty much anything with a null

play03:02

variable for example if you try to get

play03:05

or set a field on that object like my

play03:07

cat dot age equals three we get a null

play03:10

pointer exception for essentially the

play03:12

same reason there is no actual cat

play03:14

object so we can't set its age to three

play03:17

there are other things that can give you

play03:18

a null pointer exception that you might

play03:20

not expect for example what if we had a

play03:23

boolean just called should print hello

play03:26

and right now let's just initialize it

play03:28

to true then we can have some if

play03:30

statement so if should print hello then

play03:34

we will print out hello so obviously if

play03:37

we run that it will print out hello but

play03:39

what will happen if instead of setting

play03:41

this to true or false we initialize it

play03:44

to null well as you may have guessed we

play03:46

get a null pointer exception if you're

play03:48

using a capital b boolean variable this

play03:51

is the wrapper class for jabba's

play03:53

lowercase b primitive boolean a

play03:56

primitive boolean like all java

play03:58

primitives can't be set to null as we

play04:01

can see by the error we're getting here

play04:03

but a capital b boolean the wrapper

play04:05

class can be set to null and if you do

play04:08

have a capital b boolean that is set to

play04:10

null and you try to evaluate it in an if

play04:13

statement it'll give you a null pointer

play04:14

exception best practice in this

play04:16

situation is to always use the java

play04:19

primitive boolean whenever possible a

play04:22

primitive boolean will never be null

play04:24

it'll always be true or false another

play04:27

way you might get an old pointer

play04:28

exception that you may not expect is

play04:30

let's say you have a collection like a

play04:32

list of strings called like favorite

play04:35

cheeseburgers and let's say you wanted

play04:37

to use a for each loop to loop through

play04:40

those cheeseburgers and just print them

play04:42

all out so four string burger

play04:45

in favorite cheeseburgers we're just

play04:47

going to print out that burger what

play04:49

happens is if this favorite

play04:51

cheeseburgers list has been set to null

play04:54

you get an old pointer exception so best

play04:56

practice in these sorts of situations is

play04:58

even if you have nothing to put in that

play05:00

list instead of initializing it to null

play05:03

you should just set it to be some empty

play05:05

list so like new arraylist so when you

play05:08

run this program with an empty list

play05:10

instead of a null list which are two

play05:12

very different things you don't get any

play05:14

null pointer exception so all of that is

play05:16

of course good to know right but what if

play05:18

you're running into a null pointer

play05:19

exception in your code right now how

play05:22

should you go about fixing it well the

play05:24

great news is with recent versions of

play05:26

java starting with java 14 when you get

play05:28

a null pointer exception the error

play05:30

message that it prints out is enormously

play05:32

helpful so if we go ahead and run this

play05:34

our original code if we take a closer

play05:37

look at this null pointer exception when

play05:38

it's thrown it says cannot invoke cat

play05:41

dot make noise because my cat is null

play05:44

and it gives an exact line number in our

play05:47

class in line 9. with earlier versions

play05:50

of java all it would tell you is the

play05:52

line number so you would basically just

play05:54

see this part you'd see that there's a

play05:56

null pointer exception and you could see

play05:58

which line it was on but it wouldn't say

play06:00

anything about which method it was

play06:01

trying to call or which variable was

play06:04

null that caused the problem now that

play06:06

might be enough in a simple case like

play06:08

this right where on line nine there's

play06:10

only one thing that can be null that can

play06:12

cause this problem it would have to be

play06:13

when this my cat object is null and it

play06:16

tries to call the make noise method on

play06:18

it but there are plenty of other times

play06:20

when just the line number wasn't enough

play06:22

to know exactly what was going wrong for

play06:24

example what if in our code we had

play06:26

something like this if we got an error

play06:29

and all it said was there was a null

play06:31

pointer exception on line 36

play06:34

we have no idea what's actually causing

play06:37

the problem it could be that this cat's

play06:39

variable is null and it gets a null

play06:41

pointer exception when it tries to call

play06:43

the get method on it or it could be that

play06:45

this zeroth element in the cats list is

play06:48

null and it gets a null pointer

play06:50

exception when it tries to call the get

play06:51

name method on it or it could be that

play06:53

neither of these are null but instead

play06:56

the name of that first cat in that list

play06:59

is null and you get a null pointer

play07:00

exception when you try to call the dot

play07:02

length method on it but now with our

play07:04

nice modern error messages we can scroll

play07:08

over here and see okay cannot invoke

play07:11

string.length because the return value

play07:14

of cat.getname is null so once you know

play07:17

what exactly is causing your

play07:19

nullpointerexception how do you go about

play07:21

fixing it you basically have two options

play07:23

the first option is you can identify the

play07:26

exact variable that's null that is

play07:28

causing you problems and initialize it

play07:30

with some value if the variable causing

play07:33

your null pointer exception should never

play07:35

be null this is what you'll need to do

play07:37

so here i can look at the code that was

play07:40

calling this method and see that okay

play07:43

i'm creating this new cat object and i'm

play07:46

adding it to my list but i never gave it

play07:48

a name and that's why down here when

play07:51

it's trying to get the name of that cat

play07:53

object and then getting its length it's

play07:55

causing a null pointer exception so just

play07:57

back up here where i'm creating my cat

play07:59

object i just need to set

play08:02

the name on this my other cat so just my

play08:04

other cat dot set name to jerry so now

play08:08

when we run the program there are no no

play08:10

pointer exceptions and it's correctly

play08:11

printing out the length of the name that

play08:14

we gave our cat and jerry has five

play08:15

characters so it's printing out five but

play08:17

what do you do if you don't have any

play08:19

control over whether the variable that

play08:21

you're working with is null or not or

play08:23

maybe the variable being null is just a

play08:26

valid situation that you have to deal

play08:28

with the simplest way to fix it in that

play08:30

situation is to just add a piece of code

play08:32

that checks to see if that variable is

play08:34

null and only performs the operation on

play08:37

that variable if it's not null this is

play08:39

commonly referred to just as a null

play08:41

check so from our first example we know

play08:44

that if this mycat variable is null if

play08:46

we try to call the make noise method on

play08:48

it we're going to get a null pointer

play08:50

exception so what we can do is add just

play08:52

a simple null check so we can say if my

play08:55

cat is not equal to null

play08:58

then we can call the make noise method

play09:00

on it you'll see this kind of coding

play09:02

pattern all over for the rest of your

play09:04

java coding career it might seem overly

play09:07

simplistic but there's really no need to

play09:09

complicate things if a simple piece of

play09:11

code like this will do the trick now if

play09:14

you have a long chain of method calls

play09:16

like this one and any one of these

play09:18

values might be null you might need

play09:20

multiple null checks which can get a

play09:22

little bit nasty looking so to make sure

play09:24

we can call this.length method at the

play09:26

end first we need to make sure that this

play09:28

getname method won't return null but to

play09:31

make sure that we can even call this

play09:33

getname method we have to make sure that

play09:35

this get method won't return null and to

play09:37

make sure that that won't cause a null

play09:39

point or exception we first need to make

play09:41

sure that cats is not null so that means

play09:44

that we have to have a pretty large

play09:45

series of null checks so we can say if

play09:48

cats is not equal to null and

play09:51

cats.get zero is not equal to null and

play09:56

cats.get

play09:57

zero

play09:58

dot get name is not equal to null

play10:02

then we know that we can successfully

play10:04

return this value as the length of that

play10:08

name otherwise maybe we'll just return

play10:10

zero so this can definitely get kind of

play10:12

ugly but sometimes you don't really have

play10:14

a good way around it and the only way

play10:16

you can make sure that you won't get a

play10:18

null pointer exception is just having a

play10:20

large series of null checks so now we

play10:23

know how we can fix null pointer

play10:24

exceptions when we get them but what are

play10:26

some strategies for avoiding them in the

play10:28

first place so in situations where you

play10:30

have just a local variable like this

play10:33

where you're declaring it and

play10:34

instantiating it right in the same

play10:36

method that you're using it you have

play10:38

complete and full control in general

play10:40

just try to avoid initializing variables

play10:43

like that to null it's almost always

play10:45

best to just initialize it properly

play10:48

right there when you declare it there

play10:50

are some very specific situations where

play10:52

you might have to initialize a variable

play10:54

to null just take very good care to make

play10:57

sure that it is always getting

play10:58

initialized to some actual object

play11:01

somewhere down the line before you use

play11:03

it also try to avoid returning null as

play11:06

the return value in methods that you

play11:08

write if at all possible for example if

play11:11

you have some method that returns like a

play11:13

collection right so this method here git

play11:15

cats returns some list of cats so what

play11:18

if at the end of this method ah you

play11:20

don't have any cats that you want to

play11:21

return you might think well it's a good

play11:23

idea to just return null well that's

play11:26

okay but then in whatever piece of code

play11:28

that's calling this method it has to

play11:30

deal with the possibility of the result

play11:32

of this method being null what you can

play11:34

do instead is just return an empty

play11:36

collection so here we're using a list so

play11:38

instead of returning null we can just

play11:40

return a new arraylist as we saw earlier

play11:44

an empty list won't give you any null

play11:45

pointer exceptions when you try to loop

play11:47

through it but a null list will another

play11:50

small tip often you'll find yourself

play11:52

having to do some string comparisons

play11:55

where you need to take some string that

play11:56

you have and compare it to some constant

play11:59

value or some string literal for example

play12:02

let's say we just wanted to take the

play12:03

name of this my other cat object and we

play12:06

wanted to see if it was equal to some

play12:09

string literal which is just a string

play12:10

that you write out literally in quotes

play12:13

in the code like this so if we wanted to

play12:15

see if this name was equal to newman so

play12:19

we could write something like this so we

play12:20

can say if

play12:22

my other cat.getname

play12:26

then we print out hello newman so this

play12:29

code will work fine right but what will

play12:32

happen if instead of setting the name to

play12:33

jerry we have it set to null well if we

play12:37

try and run that we're going to get a

play12:38

null pointer exception and we can see

play12:40

that it says we can't invoke string dot

play12:43

equals because the return value of

play12:46

cat.getname

play12:47

is null so what's happening here is

play12:51

get myothercat.getname is returning null

play12:52

because that cat's name has been set to

play12:55

null so when we try to call the dot

play12:57

equals method on that null name we get a

play13:00

null pointer exception so what you can

play13:02

do instead to eliminate the possibility

play13:04

of a null pointer exception in this

play13:06

scenario is just flip this comparison

play13:09

around so instead of saying my other cat

play13:11

dot get name dot equals newman we can

play13:14

say newman as a string literal in quotes

play13:18

dot equals and pass in my other cat dot

play13:21

get name so now when we run our code

play13:24

just by flipping around that comparison

play13:26

we no longer get a null pointer

play13:28

exception this string literal newman is

play13:30

of course not null we can see the string

play13:33

value right there so there's no chance

play13:35

of a null pointer exception when we call

play13:37

dot equals on it and if this my other

play13:39

cat dot get name does return null here

play13:42

it doesn't cause any problems this

play13:43

equals method just compares newman to

play13:46

null and sees that they're not equal so

play13:49

this equals method just ends up

play13:50

returning false and everything just

play13:52

works as it should with no exceptions

play13:54

sometimes though you just don't have

play13:56

complete control over the code that

play13:57

you're having to deal with in those

play13:59

cases it's best to just do a simple null

play14:01

check before doing anything with that

play14:03

variable if you enjoyed this video or

play14:05

learned something please let me know by

play14:07

leaving a like and be sure to subscribe

play14:08

so you don't miss each new java tutorial

play14:11

and be sure to check out the full java

play14:12

course in the link down in the

play14:13

description thank you so much for

play14:15

watching i really do appreciate you

play14:17

being here with me i'll see you next

play14:18

time

Rate This
β˜…
β˜…
β˜…
β˜…
β˜…

5.0 / 5 (0 votes)

Related Tags
Java ProgrammingNull PointerException HandlingCoding TutorialSoftware BugsJava EngineerError MessagesBest PracticesJava CourseDebugging Tips