Null Pointer Exceptions In Java - What EXACTLY They Are and How to Fix Them
Вставка
- Опубліковано 6 лют 2025
- Full tutorial for Null Pointer Exceptions in Java.
Complete Java course: codingwithjohn...
Null Pointer Exceptions! Every Java programmer has run into this dreaded Exception.
But what exactly causes a NullPointerException in Java? We'll talk about What a null pointer exception is, how to fix it, and how to avoid them in our Java code.
NullPointerExceptions can be scary and confusing, but they're simple to fix as long as you understand why they happen.
Learn or improve your Java by watching it being coded live!
Hi, I'm John! I'm a Lead Java Software Engineer and I've been in the programming industry for more than a decade. I love sharing what I've learned over the years in a way that's understandable for all levels of Java learners.
Let me know what else you'd like to see!
Links to any stuff in this description are affiliate links, so if you buy a product through those links I may earn a small commission.
📕 THE best book to learn Java, Effective Java by Joshua Bloch
amzn.to/36AfdUu
📕 One of my favorite programming books, Clean Code by Robert Martin
amzn.to/3GTPVhf
🎧 Or get the audio version of Clean Code for FREE here with an Audible free trial
www.audibletria...
🖥️Standing desk brand I use for recording (get a code for $30 off through this link!)
bit.ly/3QPNGko
📹Phone I use for recording:
amzn.to/3HepYJu
🎙️Microphone I use (classy, I know):
amzn.to/3AYGdbz
Donate with PayPal (Thank you so much!)
www.paypal.com...
☕Complete Java course:
codingwithjohn...
codingwithjohn...
Great video explaining that concept. In general I really like your videos. But I was missing the mentioning of Optional in that context. Maybe you could make a follow up video to complete the null topic.
I never clicked faster on a video before
Sameeeeee
If you had clicked any faster, the video would still have been null.
Totally
John is such a natural teacher. Great communicator, excellent teaching vocal, well-organized materials and examples. Easy to follow. I bought his Java programming tutorial. Great for very beginners. I wish he develops more advanced topics.
Well I didn't think I'd learn anything but I did! Written 10 Spring Boot microservices over the past 3 years or so with Java 8. Whenever I got those null pointers (ex: cats.get(0).getName().length(); ) I would just end up System.Out.Println to console for debugging to see what was null. Java 14 or higher migration here I come! I can't believe something as useful as this wasn't put in earlier versions of java. Thank you for the great content as always!
Also @ 11:42 instead of returning new ArrayList() you can just return Collections.emptyList().
Hi John, good explanation as always. I'd like to suggest you cover BigDecimals in Java in your upcoming video and do a comparison with other types
String defaultMessage = “Excellent video as usual”;
System.out.println(defaultMessage);
Hi John, I've recently subbed to your channel. The thumbnails and titles to your videos are just spot on and your videos are short but full of information that are very helpful. I hope you help more learners like me.
He quickly became the top Java youtuber. Those who came before him were very bad.
I'm not even a Java developer, I use C# but I still enjoy watching your videos and for a lot of your videos I still learn from them as Java and C# are really similar.
I don't know what it is about your videos, is it your voice or the way you talk but I love you videos.
Man I work at company with a pre 14 Java version and you have no idea how many times I had a npe on a line with like 5 different objects and I would have no idea where to start. I actually didn’t know about the new exception text, very nice!
I have registered yesterday to John's course. I highly recommend his course. he is unbelievably good.
The best java channel on UA-cam. Good job, John!!!
Objects.equals(...) also avoids NPEs very successfully. However, the best way of avoiding NPEs in the JVM is introducing the language Kotlin in your Java project. It allows you declaring anything as not Nullable on language level.
To be honest null pointers exceptions can also happen in a kotlin program. It will for as long as it will stay compatible with Java. The best away of avoiding NPE is to just stop using null, and there are a ton of ways to do that. One way is to use an Optional datatype, or you could even use a simple null object pattern. What kotlin does is essentially the same as what you would get with java.lang.Optional, albeit with a much cleaner and elegant syntax. Same goes for Scala's Option.
@@altus3278 Kotlin forces you to think about what you are doing when dealing with nullable variables. Optional is not a good solution in Java. Often it is used incorrectly (e.g., as parameter value). My experience with Java shows, that even if you try really hard avoiding null values you will at one point or another fail doing so. Even if you use those placebo annotations (@NotNull...) you will encounter NPEs. And yes you are correct in saying that NPEs can also occur in Kotlin. However, they happen very rarely and if they do, you get a better explanation in the exception message (e.g., "lateinit var was not initialized" instead of "null").
Another great video, John. I've gotten to the point in my practice where I'm considering initializing stuff to null. This came just in time.
Today I understood why people write string literal first followed by a string method. Thanks mate
A nice way to do chains of null checks is with optionals:
For example: If i want to return some value a.getB().getC().getD(), i can just do:
return Optional.ofNullable(a).map(A::getB).map(B::getC).map(C::getD).orElse(myDefaultD);
yes, this is a better way.
if I am not wrong.. in this case we have to use flatMap in order to get the value.. for examlpe if the object that comes in from method argument has the type "Optional" it will return Optional.. then flatmap can handle it
@@codingwithraphael if getB, getC and getD return an Optional of something, then the solution would probably be flatmap, otherwise map would be the obvious choice.
Hi John, thanks for the brilliant video.
Thank you so much John, you are the only one able to teach me Java and put a smile on my face at the same time, I hope you de best.
You are THE BEST. precise and concise to perfection
Thanks a lot. I vê never thought about your last example. Now, I will always compare strings like "string".equals(a.getB())
I am waiting for this topic for a long time. Great explanation. Thanks John so much
10:21 if cats is Null, will the other statements be also tested? And if so, wouldn't we get an exception for trying cats.get(0) ?
Welcome back John! Nice video as always!
As always, exactly just what you need to understand the topic. Thanks John for these great videos.
Hi John, we could be also using Optional.ofNullable to avoid NullPointerException
That's right! Functional programming rocks! By the way, Optionals are a kind of Monad:)
An awesome video about nullpointerexception. The tutor knows the way how to teach java in a simple way
helps a lot for my essay.. thy john!
You can also avoid null pointers by ensuring data basically can't be set to null.
For example, the .setName() method in his example could easily have a null check where it sets the name to a default value like "Unknown" when you call setName(null).
Do this carefully, though. Sometimes it's better to have the exception come up and then have to write code to deal with it explicitly than to have hidden behaviors that a user of that method may not anticipate/understand. In the contrived example in the video, your suggestion would be fine because no one is named "unknown" but you can imagine in real use cases just returning a filler value for the sake of having a value could cause unexpected behaviors further down the line. So it's a great idea if it's appropriate for the situation but a recipe for a debugging mystery if used haphazardly.
Hi, Jonh. Nice video. You could talk about the garbage collector. It's a good subject.
Great Video, John!✨
Thank you for sharing this awesome video Jhon. I wonder if In the future you could share some tips and tricks with Maven, Spring, or Webservices. The way in which you turn complex things into simple concepts is beautiful.
BEST EXPLANATION EVER
Hi jhon ... your explanation is to good .... please upload videos ...how to read any api documentation for any library
Can you create a video on Annotations and how they simply the developer work
I always learn something new with you! Thanks a lot!!
Perfect summary, however I am missing a neat trick: java.lang.Objects isNull and requireNonNull. Generally I think it makes the code more readable and can have some additional benefits compared to a null check, with requireNonNull (custom exception message) it is in Java since Java 1.7 (???)
He should do a separate video on that.
This still throws a nullpointer exception so it's not really a equivalent to a null check. It's rather a clarification why the program failed at this point. IsNull is pretty useless in my opinion since it's just a verbose version of x == null.
What about Optionals?
@@redcrafterlppa303 You can't prevent null pointer with anything really - if you ever have a null reference - but you can prevent the program from halting. IsNull might be "useless", it is only for readability. RequireNonNull is just a short hand for exception throwing for null checks, that only says: hey, this null, can't proceed with the execution.
@@emoutraspalavras-marloncou4459 Optionals are encapsulation of objects. If some fields are null, you'd still get a null pointer. This does not have a deep "scan" of every field that can be null. It is only an extension that can help prevent null pointers, with handy functions, e.g. used as a result of a search function from an array of data where data may or may not be present. Used commonly in JPA, ORMs (Database Management).
Anyone else keep thinking of Schrödinger's 🐈 cat at the beginning of the video lol 🤣
What about using Optional from java 8?
thank u so much for the help. and I wish that thé next vidéo gone à be about thé streams.
Great explanation, thanks
Hi john, could you please explain us the difference between object and instance.
They're often kind of used interchangeably. But one good way to think about it is that an object is an instance of a class.
as always you nailed it, thank you a lot for your great way to teach us what we really stuck with for a long time :)
Please do a video about reflection or callbacks !!!
Wasn't this video also a good opportunity to talk about the nullable and not null annotations so that your IDE's linter can help find NullPointerExceptions early?
And for the String comparison at the end you could have also used Objects.equals(string1, string2) which will do a null check for you.
Hi John, please make a video tutorial on " interface and implementing interfaces in java", java process memory. Thank you so very much.
Thank you John, great explanation.
Really appreciate it! Thank you John
Excellent tutorial bro
Great video! This is java 11 or above?
Hi John! What's about Optional objects? That's a great way to get round Null values and NullPointerExceptions 8.-)
also... just a newbie but I learned this the hard way-
• Wrapper classes for primitives (String, Boolean, Integer, Double) are initially null when set ↓
Integer boxCount; // integer is null
• Accessing a global (wrapper) variable (or object) from a function may also return null (basically if I access a global variable from function 1 and I set it beforehand in another function; the accessing function may throw NullPointerException; even if the class/object is instantiated globally and pre-modified in function 2. It may be avoided by using getters and setters tho)
thank you so much, i got what i want
Hey John please please make series on SpringBoot and microservices :(
The way you explain stuff is Amazing
Hey John could you please make a separate playlist on Data Structures and Dynamic Programming in Java
Great tutorial!
Can use Optional API when dealing with null pointer with chained methods
"Null was a mistake"
- Tony Hoare, inventor of Null
His billion dollar mistake, probably many billions
Hello John,
Thank you for this wonderful video!!
Currently I am working on a project someone else wrote before, and I an new to Microservices (IoC & DI, all that fun);
Since it's structure is a bit complicated and not usually we can use null checker in production environment, how can we avoid that?
I am new to Microservices, and noticed recently when I wrote some codes, it came back with null pointer in the log, and I had to spend some time to find the issue, sometime more than others.
hi john. you are a great teacher.
can u make tutorials on usefull design patterns
Nice explanation. Good work.
Could you cover
JVM and memory management in JVM?
What do you want to know? I am researching the inner workings of the jvm and memory management in java for a project. So I should be able to answer your questions pretty well.
Hi please explain about the string classes StringBuilder and StringBuffer. And its execution in multithreading.
Thank you John
Good explanation, but can't we use try catch to handle NPE?
Very good video, thank you for the lessons!
Algorithm-boosting comment. Keep up the excellent work!
u have a private course?
thanks a lot... for sharing this.
When creating a method with a parameter, where null doesn't make sense as an input, should you throw an IllegalArgumentException or a NullPointerException? For example if the cats List was null. I could see an argument for either. I'm particularly interested in the "convention" for something like equals and compareTo.
I'm not shure about the convention but I would throw both. Like this:
throw new IllegalArgumentException(new NullPointerExcrption("The argument arg1 can't be null. ")) ;
This will produce a stack trace similar tl this :
... IllegalArgumentException... caused by... NullPointerException : The argument arg1 can't be null...
Witch explains the reason for the exception pretty well in my opinion.
Very helpfull. Thank you !
I was hoping you would talk of the Optional wrapper and the NullObject pattern, maybe you thought it was too advanced. Nice explanation nonetheless.
Thanks. Can you elaborate on throwable, throws and throw in java
SENSEI !!!!!!! THANK YOU SO MUCH !!! WOW !!
Hi John, can you make some tutorials about Event listeners, Event handling etc
Thank you
Talking about nulls and not to say anything about Optionals? :)
At some point I plan to have a whole video dedicated to optionals
Any videos coming out on the functional interface?
Hi John, good explanation , but why you don't use optional.ofnullable it's simplify powerful of using != null
The solution for this problem is: Optional. Use on methods that may or not return a result. It will force you, on the client code, to handle it. Thus avoiding null pointer situation.
Hey could you make a tutorial on locking methods like hand over hand on linked lists
cool!!! Thanks for video!!
Not related, but, what can you say about the Iterator()?
Thanks for the great video!
Why not using a try ... catch (NullPointerException ex) ... instead of all the conditions in that if statement? Wouldn't it be cleaner? Or has it a mature disadvantage?
Dealing with a thrown exception is less efficient than a null check. And generally speaking, it's best to not use exception handling to do the basic logic of your code.
Incase of logging I am adding logger for tracking log but after adding new log4j logger it's giving me null pointer exception from logger but when I removed the logger and using sysout it's working great. But I have to add logger for logging, how to fix that type of issues?
Hey, thanks for that
Hi John, how useful are JML, checker framework, Nullaway these annotation tools in professional development work? Thanks
thanks man !, can you please explain the "optional" keyword it is also used to avoid null values, please add it as you make things super easy :), waiting
It's not a keyword, it's a type. Lookup java.util.Optional
No mention of Optional?
I may have a separate video on Optionals at some point since it's a larger subject in itself. I do think they're sometimes misinterpreted as being a replacement for the need for any checks at all, and also used where they're not really intended. It's mostly just useful as a return type, not to remove the need for any check, but to essentially force the user of the method to deal with the potential of the value being not present. By itself, just using something like optional.get() without an isPresent check is the same as using a nullable value without a null check.
@@CodingWithJohn force the user to provide default value with orElse/orElseGet
on that catGetNameLenght method it would make more sense to try/catch the NPE, or at least cache the list.get(0), which on a linked list or some other implementation might not have O(1) access time
Exactly. It's always better to store a result in a variable then to call a method twice. In situations like in the example you should think about splitting the actions in multiple methods to prevent the huge unsightly and unreadable if tower. Never concern yourself over speed when splitting something into a new method. The compiler will inline most methods so there's no real difference other than readability of the code.
Please make one on Java optional
It happens to me when working with spring boot. tbh I don't like this exception; it's hard to fix. Lol
Thank you John, this tutorial really helps my mind.
Yep same lol, especially when setting relationships between entities for me
Thanks ❤
what about class Optional man
Thank you so much for the lesson. I have a question: what about using Optionals instead of if for the null check? I've seen that somewhere, just can't recall how to implement it. Could Optional.ofNullable deal with that?
Thank you
Hey John could you make a video over 2D arrays? I’m having some trouble iterating through a matrice with double or triple nested for loops. It can get really confusing quick.
Come on, buddy. You can figure them out on your own.
Have you thought about doing something on Design Patterns - I find almost all teaching on this is awful. I'm confident you can change that.
Company will start adopting Java 17 when I am a feeble old man.
Same. Most of our stuff is still 8 ☹️
@@CodingWithJohn I am working with Java 11 here 😆 Could be a good start. Bless var "keyword", but old legacy projects are still maintained using Java 7 😭 We may see Java 17 adopted when Oracle releases Java 100 😭
Silly question. I know java doesn't make executable ".exe". But could you make a video to explain how to make a java program usable on a computer that doens't have any java installed (no JVM, JDK, Eclipse...), in a close to similar way to a .exe?
?Or show how a home-made java program can be used by an other program from an other programming language?
I hope this makes sense. Thanks for the videos. I'm binge-watching them.
Java code is 100 dependent on the jvm it is impossible to execute even a single line of code without it running. When your only concern is windows convert your Java code to c# code using a converter. C# code does compile to exe files. It requires .NET but it's default installed on 99% of windows pcs.
Video on ways of cloning arrays??
System.arrayCopy
Or
Arrays.copyOf
They are as efficient as possible with perfect results.
@@redcrafterlppa303 System. arrayCopy primarily
@Coding with John Sir,love from INDIA plz make video on java competitive programming includes number system and so on...
Hi John
Why null pointer exception is occuring while I'm entering a policy number after clicking on run illustration button it's show error that is null pointer exception why this occur can you pls exam explain this plsssss
If you share your code, maybe I or another viewer can take a look and help?
@@CodingWithJohn yeah sure