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

Поделиться
HTML-код
  • Опубликовано: 23 ноя 2024

Комментарии • 191

  • @redcrafterlppa303
    @redcrafterlppa303 2 года назад +35

    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.

  • @raz0229
    @raz0229 2 года назад +45

    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

  • @feiwong70
    @feiwong70 6 месяцев назад

    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.

  • @oligawen
    @oligawen 2 года назад +38

    I never clicked faster on a video before

  • @briansutton1005
    @briansutton1005 2 года назад +2

    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().

  • @tommilton1458
    @tommilton1458 2 года назад +2

    String defaultMessage = “Excellent video as usual”;
    System.out.println(defaultMessage);

  • @nesuleo1779
    @nesuleo1779 2 года назад

    I have registered yesterday to John's course. I highly recommend his course. he is unbelievably good.

  • @DKaldes
    @DKaldes 2 года назад

    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.

  • @chvis002
    @chvis002 2 года назад +2

    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!

  • @kamesh70
    @kamesh70 2 года назад +1

    Today I understood why people write string literal first followed by a string method. Thanks mate

  • @christophdietrich4240
    @christophdietrich4240 2 года назад +5

    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);

    • @ichengzi
      @ichengzi 2 года назад

      yes, this is a better way.

    • @codingwithraphael
      @codingwithraphael 2 года назад

      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

    • @altus3278
      @altus3278 2 года назад

      @@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.

  • @pedroalbertogomes3809
    @pedroalbertogomes3809 2 года назад

    Thanks a lot. I vê never thought about your last example. Now, I will always compare strings like "string".equals(a.getB())

  • @cedricmendoza8316
    @cedricmendoza8316 2 года назад +6

    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.

    • @socaljusticewarrior558
      @socaljusticewarrior558 2 года назад

      He quickly became the top Java youtuber. Those who came before him were very bad.

  • @richiemercury
    @richiemercury 2 года назад

    You are THE BEST. precise and concise to perfection

  • @gahnendesgnu9012
    @gahnendesgnu9012 Год назад +1

    Hi John, thanks for the brilliant video.

  • @snoopy1alpha
    @snoopy1alpha 2 года назад +1

    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.

    • @altus3278
      @altus3278 2 года назад +1

      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.

    • @snoopy1alpha
      @snoopy1alpha 2 года назад

      @@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").

  • @josenavio74
    @josenavio74 2 года назад

    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.

  • @socaljusticewarrior558
    @socaljusticewarrior558 2 года назад +1

    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.

  • @HouseExpertify
    @HouseExpertify 2 года назад +2

    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).

    • @jimconingsby4616
      @jimconingsby4616 Год назад

      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.

  • @teslagang3923
    @teslagang3923 2 года назад

    The best java channel on RUclips. Good job, John!!!

  • @jamesorpilla
    @jamesorpilla 2 года назад

    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)

  • @krava3213
    @krava3213 2 года назад +10

    Hi John, we could be also using Optional.ofNullable to avoid NullPointerException

  • @bunnihilator
    @bunnihilator 2 года назад +1

    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.

  • @ody7850
    @ody7850 2 года назад

    helps a lot for my essay.. thy john!

  • @laurentblanc6354
    @laurentblanc6354 2 года назад +2

    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) ?

  • @mozammalhaquetonoy1983
    @mozammalhaquetonoy1983 2 года назад

    An awesome video about nullpointerexception. The tutor knows the way how to teach java in a simple way

  • @fede.lencina
    @fede.lencina 5 месяцев назад

    BEST EXPLANATION EVER

  • @hariupadhyay9031
    @hariupadhyay9031 2 года назад

    Hi jhon ... your explanation is to good .... please upload videos ...how to read any api documentation for any library

  • @kamesh70
    @kamesh70 2 года назад +2

    Can you create a video on Annotations and how they simply the developer work

  • @rhr-p7w
    @rhr-p7w 2 года назад +2

    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.

  • @khiemdo5527
    @khiemdo5527 2 года назад

    I am waiting for this topic for a long time. Great explanation. Thanks John so much

  • @aidoka2000
    @aidoka2000 2 года назад

    As always, exactly just what you need to understand the topic. Thanks John for these great videos.

  • @OneShout100
    @OneShout100 2 года назад +4

    Hi John! What's about Optional objects? That's a great way to get round Null values and NullPointerExceptions 8.-)

  • @akoskovacs5467
    @akoskovacs5467 2 года назад +6

    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 (???)

    • @JLSXMK8
      @JLSXMK8 2 года назад +3

      He should do a separate video on that.

    • @redcrafterlppa303
      @redcrafterlppa303 2 года назад +1

      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.

    • @emoutraspalavras-marloncou4459
      @emoutraspalavras-marloncou4459 2 года назад +1

      What about Optionals?

    • @akoskovacs5467
      @akoskovacs5467 2 года назад

      @@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.

    • @akoskovacs5467
      @akoskovacs5467 2 года назад +1

      @@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).

  • @Caranthirn
    @Caranthirn 2 года назад

    Thank you John, great explanation.

  • @gringodf83
    @gringodf83 2 года назад

    Hi, Jonh. Nice video. You could talk about the garbage collector. It's a good subject.

  • @mohammadkarim5764
    @mohammadkarim5764 2 года назад

    Hi John, please make a video tutorial on " interface and implementing interfaces in java", java process memory. Thank you so very much.

  • @gabucarneiro
    @gabucarneiro 2 года назад

    I always learn something new with you! Thanks a lot!!

  • @JeroenV1602
    @JeroenV1602 2 года назад +1

    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.

  • @sololevelling7582
    @sololevelling7582 2 года назад

    Please do a video about reflection or callbacks !!!

  • @bradhollis1862
    @bradhollis1862 2 года назад

    Really appreciate it! Thank you John

  • @PK-tm4nw
    @PK-tm4nw 2 года назад +1

    Hey John could you please make a separate playlist on Data Structures and Dynamic Programming in Java

  • @Abdullah-rv1pk
    @Abdullah-rv1pk 2 года назад

    Hey John please please make series on SpringBoot and microservices :(
    The way you explain stuff is Amazing

  • @JonasKeil
    @JonasKeil 2 года назад +1

    Great Video, John!✨

  • @swapnildubey414
    @swapnildubey414 2 года назад

    Great explanation, thanks

  • @richskater
    @richskater 2 года назад +1

    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.

    • @redcrafterlppa303
      @redcrafterlppa303 2 года назад

      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.

  • @vicranttangde6711
    @vicranttangde6711 2 года назад +1

    What about using Optional from java 8?

  • @mechanicraft-mc7203
    @mechanicraft-mc7203 2 года назад

    Welcome back John! Nice video as always!

  • @zakagg4707
    @zakagg4707 2 года назад +1

    thank u so much for the help. and I wish that thé next vidéo gone à be about thé streams.

  • @grayyeung757
    @grayyeung757 2 года назад +1

    Can use Optional API when dealing with null pointer with chained methods

  • @staffmoto4939
    @staffmoto4939 2 года назад +1

    Anyone else keep thinking of Schrödinger's 🐈 cat at the beginning of the video lol 🤣

  • @MislanSuyatin
    @MislanSuyatin 7 месяцев назад

    I was hoping you would talk of the Optional wrapper and the NullObject pattern, maybe you thought it was too advanced. Nice explanation nonetheless.

  • @venkateshmarneni385
    @venkateshmarneni385 2 года назад +1

    Hi john, could you please explain us the difference between object and instance.

    • @CodingWithJohn
      @CodingWithJohn  2 года назад +2

      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.

  • @ahmedbishree9429
    @ahmedbishree9429 2 года назад

    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 :)

  • @altus3278
    @altus3278 2 года назад +1

    "Null was a mistake"
    - Tony Hoare, inventor of Null

    • @CodingWithJohn
      @CodingWithJohn  2 года назад +2

      His billion dollar mistake, probably many billions

  • @dylant3414
    @dylant3414 2 года назад +1

    Could you cover
    JVM and memory management in JVM?

    • @redcrafterlppa303
      @redcrafterlppa303 2 года назад

      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.

  • @daiyrkanybekov8575
    @daiyrkanybekov8575 2 года назад

    Excellent tutorial bro

  • @shahrokhfiroozi
    @shahrokhfiroozi Год назад

    Thank you John

  • @alfredomenezes8814
    @alfredomenezes8814 2 года назад

    Very good video, thank you for the lessons!

  • @farhad9579
    @farhad9579 2 года назад

    hi john. you are a great teacher.
    can u make tutorials on usefull design patterns

  • @girishamara4483
    @girishamara4483 2 года назад

    Nice explanation. Good work.

  • @m.hakania2251
    @m.hakania2251 2 года назад

    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.

  • @jeanjacquesbosson4411
    @jeanjacquesbosson4411 2 года назад

    SENSEI !!!!!!! THANK YOU SO MUCH !!! WOW !!

  • @vladthe_cat
    @vladthe_cat 2 года назад

    Any videos coming out on the functional interface?

  • @Semma_Bore
    @Semma_Bore 2 года назад

    Hi please explain about the string classes StringBuilder and StringBuffer. And its execution in multithreading.

  • @Jurigag
    @Jurigag 2 года назад

    There is also 3rd option - just catch this exception in other place and never care about it. You should avoid null/nullchecks in your code as much as possible. This technic is called fail fast and i would recommend it to anyone.
    But i also like the way you did it here with ArrayList - like return actual fake null implenentation which will have the same methods, for example by including interface, but i wouldn't do things like return 0 etc, sometimes when debugging your code why something is behaving the odd way - it can be actually this 0 thing.

    • @jimconingsby4616
      @jimconingsby4616 Год назад

      a bunch of try/catches that just swallow the exception and allow it to continue is far more obtrusive and much sloppier code than some null checks.

  • @fonte1184
    @fonte1184 2 года назад

    Thanks. Can you elaborate on throwable, throws and throw in java

  • @endihyseni3858
    @endihyseni3858 2 года назад

    Hi John, can you make some tutorials about Event listeners, Event handling etc
    Thank you

  • @yashaswipandey7923
    @yashaswipandey7923 2 года назад

    Please make one on Java optional

  • @ramabookstroremalang9131
    @ramabookstroremalang9131 2 года назад

    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.

    • @pt_trainer9244
      @pt_trainer9244 2 года назад +1

      Yep same lol, especially when setting relationships between entities for me

  • @my_love_sanatan
    @my_love_sanatan 2 года назад

    Good explanation, but can't we use try catch to handle NPE?

  • @saronabi1387
    @saronabi1387 2 года назад

    thank you so much, i got what i want

  • @meghraj
    @meghraj 2 года назад

    thanks a lot... for sharing this.

  • @geneolo
    @geneolo 2 года назад

    Great tutorial!

  • @lethality3704
    @lethality3704 Год назад

    Hi John, how useful are JML, checker framework, Nullaway these annotation tools in professional development work? Thanks

  • @ccruzp06
    @ccruzp06 2 года назад

    Man, I really hope Java finds a way to add nullable types to the language. Once you start using them on Kotlin, you really miss them ):

  • @zairsadiqov356
    @zairsadiqov356 2 года назад +1

    Talking about nulls and not to say anything about Optionals? :)

    • @CodingWithJohn
      @CodingWithJohn  2 года назад +2

      At some point I plan to have a whole video dedicated to optionals

  • @libertymedicalcommunicatio4908
    @libertymedicalcommunicatio4908 2 года назад

    Algorithm-boosting comment. Keep up the excellent work!

  • @saikatchakraborty7262
    @saikatchakraborty7262 2 года назад

    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?

  • @mafakka2
    @mafakka2 2 года назад +2

    what about class Optional man

  • @dhaw
    @dhaw 2 года назад

    Very helpfull. Thank you !

  • @bakadirmohamed7310
    @bakadirmohamed7310 2 года назад

    Hi John, good explanation , but why you don't use optional.ofnullable it's simplify powerful of using != null

  • @germimonte
    @germimonte 2 года назад

    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

    • @redcrafterlppa303
      @redcrafterlppa303 2 года назад

      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.

  • @ryanpatel2001
    @ryanpatel2001 2 года назад

    Hey could you make a tutorial on locking methods like hand over hand on linked lists

  • @emoutraspalavras-marloncou4459
    @emoutraspalavras-marloncou4459 2 года назад

    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?

  • @hammett79
    @hammett79 2 года назад

    Great video! This is java 11 or above?

  • @konstantinurban1598
    @konstantinurban1598 2 года назад

    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?

    • @CodingWithJohn
      @CodingWithJohn  2 года назад +1

      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.

  • @tarunbalchandbhaimulchanda6929
    @tarunbalchandbhaimulchanda6929 2 года назад

    I haven't faced this exception too many times, but yes this is the thing that people talk too much over the rooms

  • @crazynnaf
    @crazynnaf 2 года назад

    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.

    • @redcrafterlppa303
      @redcrafterlppa303 2 года назад

      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.

  • @ilyaivlev6620
    @ilyaivlev6620 2 года назад

    cool!!! Thanks for video!!

  • @TasneemAlEmam
    @TasneemAlEmam 2 года назад

    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

    • @altus3278
      @altus3278 2 года назад

      It's not a keyword, it's a type. Lookup java.util.Optional

  • @romulosendoromulo
    @romulosendoromulo 2 года назад

    Hey, thanks for that

  • @hritiknegi687
    @hritiknegi687 2 года назад

    @Coding with John Sir,love from INDIA plz make video on java competitive programming includes number system and so on...

  • @vincenzofortunato3461
    @vincenzofortunato3461 2 года назад

    I think you missed an important part of "strategies to avoid null pointer exception" that is "design your code to not use nulls at all!" Instead of nulls use default values, empty collection or throw an exception. This way you can avoid all the null checks and make the code more readable. If a null pointer exception happens that is for sure a bug that needs to be resolved. A null check with an if statement is just a workaround the issue in my opinion and is a very bad practice in modern java code.

  • @aaronrio4271
    @aaronrio4271 2 года назад

    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.

    • @turuus5215
      @turuus5215 2 года назад

      Come on, buddy. You can figure them out on your own.

  • @Mirtguitar
    @Mirtguitar 2 года назад

    Not related, but, what can you say about the Iterator()?

  • @monisha2144
    @monisha2144 2 года назад +1

    Hi.. Create a crash course for collections in java

    • @CodingWithJohn
      @CodingWithJohn  2 года назад

      I have some videos almost ready to add to the course soon about Collections, and at some point there's likely to be a RUclips video in the topic but not sure when exactly.

    • @monisha2144
      @monisha2144 2 года назад

      @@CodingWithJohn thank you

  • @AbhishekChanda
    @AbhishekChanda 2 года назад +1

    No mention of Optional?

    • @CodingWithJohn
      @CodingWithJohn  2 года назад +2

      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.

    • @AbhishekChanda
      @AbhishekChanda 2 года назад

      @@CodingWithJohn force the user to provide default value with orElse/orElseGet

  • @drcl7429
    @drcl7429 2 года назад +1

    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.

  • @MrFieseMoep
    @MrFieseMoep 2 года назад

    Or use Kotlin. There is a button up there in the Intellij to convert your Projekt to Kotlin. PRESS IT!