Optionals In Java - Simple Tutorial

Поделиться
HTML-код
  • Опубликовано: 1 окт 2024
  • Full tutorial on Optionals in Java!
    Thanks to FlexiSpot for sponsoring! 🖥️ Get your coupon code for an extra $30 OFF through my link: bit.ly/3QPNGko
    FlexiSpot Pro Plus Standing Desk E7
    bit.ly/3xTvGNF (US site)
    bit.ly/3OEL9aT (CAN site)
    Join FlexiSpot Member Day during 29-30th June 2022! Up to $100 OFF! bit.ly/3u0akNa
    #MyFlexiDesk #flexiblewfh
    Complete Java course: codingwithjohn...
    Optionals were added in Java 8, but can be a confusing thing to learn. This tutorial will walk through all of the aspects of Optionals in Java detail, then walk through step by step when and how to use optionals in your own code!
    If you're confused by Optionals in Java, either just what they are and why they exist in general, or how to code to use them in Java, you're in the right place!
    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...

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

  • @stevenschelling8452
    @stevenschelling8452 Год назад +193

    This is the gold standard of coding tutorials, thanks for such well-structured info

  • @YatiAcharya
    @YatiAcharya Год назад +48

    You know how I am certain this is the best Java channel? I have no interviews to crack, I have no exams to clear and I'm still here learning because it just is explained in such an interesting, problem-solution kinda way.
    Brilliant work, John!

    • @Amitjha406
      @Amitjha406 11 месяцев назад

      Agreed

    • @BryanChance
      @BryanChance 10 месяцев назад +2

      Yes, I second that. This is the best Java channel. :)

  • @nikamz6077
    @nikamz6077 2 года назад +113

    My coding exam is in just about a month - and I would like to thank you, John! You have helped me so much. If I pass, thats because of you. Love your channel! Greetings from germany. :)

  • @lolloBriggi
    @lolloBriggi Год назад +2

    Sometimes, I feel like programmers always need to overcomplicate things and come up with Schrödinger's cat solutions. I'll stick to 'if not null else'. Verbosity is better than Schrödinger's cat solutions to me.

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

    Why not just IF this? Seems like java is full of useless garbage, starting to remind me javascript

  • @RsZ789
    @RsZ789 2 года назад +26

    Great job, John. Can you please cover logging and best practices for it?

  • @LightningLion500
    @LightningLion500 2 года назад +22

    I just started watching your channel and I love your calm and reassuring way of explaining complex coding aspects! It motivated me to work a little harder on my own projects, unlike the often condescending explainations of the teachers at my university. Thanks John!

  • @triyanbhardwaj934
    @triyanbhardwaj934 Год назад +3

    There's a Schrodinger's cat joke in here somewhere

  • @biswarana4491
    @biswarana4491 Год назад +5

    Cat be like : things i need to comply with for some food..

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

    Great, a Schrodinger's Optional... hahahahaa

  • @MBerg-qq6gf
    @MBerg-qq6gf 6 месяцев назад +1

    At 10:50 instead of demonstrating orElse with an "unknown cat" I would have used something like _string catDisplayValue = optionalCat.orElse("");_ because the whole point is to skip the "fake cat" (whether null, empty or unknown) and use directly the fallback value that needs to be used in the println when there's no cat! Please note that I suggested *pseudo code* -- my suggestion is not entirely syntactically correct (I come from c# and I don't know the Java equivalent to C#'s question mark yet)

  • @Andrew-ss7jd
    @Andrew-ss7jd Год назад +1

    You didn't call it schrodingersCat, my disappointment is immeasurable and my day is ruined.
    But otherwise great tutorial xD

  • @sivakumar.s2559
    @sivakumar.s2559 2 года назад +1

    Create a video for intellij shortcuts like eclipse why you switched intellij I am switched from vscode to eclipse after Watching your video now you switch to intellij compare ad tell about the advantage of intellij IDE

  • @zaph8015
    @zaph8015 Год назад +6

    Null safety is one of the reasons I fell in love with Kotlin. It's caught me out so many times and helped me to think about where NPEs might be found even when working in other languages.

  • @Cloydz
    @Cloydz 2 года назад +11

    i just started my internship for the summer and the code they have us working with has a ton of optionals, which was something i had never heard of. You’re videos are truly always a highlight to my day and explain it so neatly and concisely, not to mention the timing! please keep doing what you do

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

    THANK YOU SO MUCH for actually explaining when are where optionals are actually useful as opposed to using a return annotated with "@Nullable". I am lucky to have understood this topic before watching your video, but before i got to that point i was *severely struggling* to get behind why i would use Optional instead of null in the first place. That is due to many tutorials on optionals just leaving things at "it's a container where a value may or may not be present" but not going as far as you did. I'm absolutely certain this video of yours will help tons of people!

    • @pauldhartley
      @pauldhartley Год назад +2

      I must confess to still being confused at the usefulness of optionals, though the video explains admirably some of the characteristics.

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

      @@pauldhartley cleaner and more functional code. Try working with streams for example. You cannot unlock the full power of streams using null checks

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

      @@pauldhartley I point out functionality because you cannot much with a null value, other than check it and pass it. Optionals on the other hand, are integrated into javas core functionality. You can do tons of things with them just with what java provides. That doesn't even take into account what you or others may code for it

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

    Love the cat example and box metaphor! :) 4:45

  • @neolin.99
    @neolin.99 Год назад +1

    ah, a classic
    "we do not know if the cat is null or not null until we open the box, so until then, it is simultaneously null and not null"

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

    1 Question.
    You mean Optionals should only be returned, but I find them also useful for optional request parameters in my rest api. Would you agree?

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

    I don't usually comment on any youtube videos. But here John, You are doing an excellent job describing topics in a simpler manner. Thank You.

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

    Hi John thank u for ur efforts , can u please do a tutoriel about the spring and spring boot it will be amazing by u

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

    I m surprised there is no comment on the cat and the box ? that was the best part

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

    My thanks are Default, not Optional !

  • @alinesinclaire2854
    @alinesinclaire2854 Год назад +2

    epic explanation with the cat in the box it was so funny!

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

    Schrodinger's Variable

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

    oohhhhhhh poor kitty..he was very happy on the video🤣🤣🤣🤣🤣🤣... very good lesson anyway...Thanks john ,from Luxembourg

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

    Threat, like optionlalCat......ORELSE! LOL made my day with that face :D
    Btw great vid as always!

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

    "Only as return value". I disagree. Very powerful e.g. combined with StringBuilder when creating SQL queries, when all search parameters are not mandatory.

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

    I'm not sure. Seems like "really powerful" can turn into "really messy" quickly. Why not stick to @Nullable and @NotNull and save on quite a few object instances?

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

    for some reason i didnt at all think he would be 6 feet 5

  • @DericksonCaballero
    @DericksonCaballero 10 месяцев назад

    Thanx God I know a little of java now, I used to be so stupid that the Cat class will got me thinking: "where the "heck" did he get that Cat script from", because I never saw him creating the class, now I know that he had it created somewhere in the same package or project.

  • @дабеда-л9о
    @дабеда-л9о 2 года назад

    Between Producer and Signature, wNice tutorialch SKU would you recomnd? Is Signature worth the 50% price bump? ItNice tutorialnk I want to have

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

    Need your cat to be in every video ❤❤

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

    Top notch shit. Quickly becoming my faborite java tutorials on youtube. If you can expand to springboot would be amazing.

  • @AsifShaikh-kr7vu
    @AsifShaikh-kr7vu Год назад

    why don’t we have something like this obj.isPresent().get().orElse(“do something”). ??

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

    Cats definitely love playing with/in Optionals

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

    This to me looks like the Haskell Maybe Monad.
    Am wondering if Java supports pattern matching, it would make using optionals very easy.

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

    Very cool, thanks for sharing this information -- just to be nitpicky -- would negative 1 not be a better age to fallback on instead of 0? Kittens can be of age 0 for example -- my comment is less about the technicalities of feline lifespans and more about if in Java- is -1 is an more idiomatic way to express a fallback number for a value that could be 0 OR > 0? For example this is the case in JS where methods like indexOf will return -1 to express that the searched value doesn't exist at any index. OR is it that in java specifically that -1 has a specific integer type that would have complicated your video and been outside of the scope of the subject you were discussing?

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

    You could use String type of method and it could return String type of message "object was not found". I think java dev in oracle has serious problems in their mind. Instead making things easy they are complicating. No doubts why android abondan java. With all respect im java learner.

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

    Tall? Lanky? Glasses? Balding? This is what a peak programmer looks like. To increase his power he needs a hunch back, and a desk of empty energy drinks while blaring electronic music.

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

    Schrodinger's cat

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

    Thanks! Direct to the point, it worth all 16 minutes. If I could give 100 likes I will ask why I can't give 1,000

  • @yaroslavpanych2067
    @yaroslavpanych2067 4 месяца назад

    Unfortunately language wise, Optional didn't solve anything.
    I'll keep using my nullable container, as it really provides me with what I need: an optional update value that can be also updated to null. Meaning: i can initialize my option with null, and it will indicate presence of the value NULL, which I will set nullable column in database. If I want to my optional be empty, I will clear it explicitly, not relying on false detection of its emptiness by value. Pity json doesn't support it, or rather serialisation implementations

  • @NBSgamesAT
    @NBSgamesAT 2 месяца назад

    Soo, ahh. What is the purpose of Optional.of()?
    We are just creating an object in it that can‘t be null or it throws an error? The only reason I can think of inside a try catch but eh?
    I‘d personally just return the normal value if I already know that said value can be null

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

    can i use optional against collections, for exmple for i have java.util.List, upon this collection can i apply Optional and access its API? Is that right way of doing?

  • @Baltr
    @Baltr 9 месяцев назад

    i don't know if it's in java or not, but the thing i like about c# is the null conditional. instead of going through all the optional stuff you'd just do myCat?.getAge() ?? 0 which just means if myCat is null it defaults to the value after the ??

  • @69k_gold
    @69k_gold 2 года назад +2

    This entire video is a demonstration of "Life is too short to code in Java"

  • @kevin_mitchell
    @kevin_mitchell 2 месяца назад

    This doesn't work for me unless I import java.util.Optional;

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

    Nowadays I'd only use Optional for public methods, or when I don't feel like using a bunch of if-else blocks.

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

    IMHO this just makes the code harder to understand. Simplicity is underrated, but I can see the value of it in functional code.
    But the video was good.

  • @flytoinfinityvivi
    @flytoinfinityvivi 5 месяцев назад

    How to know if a youtube video is successful and worth watching?
    When you even enjoy watching the ads inserted into the videos lol love it

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

    But null coalesce like php was too hard to implement? 😅
    Java is full of bloat code to write, and it makes simple things difficult.
    this is typical of java 😁🤣

  • @icjay1793
    @icjay1793 8 месяцев назад

    Can someone give me a tips or suggestion while im still learning java what should i make or do to improve my java knowledge should I make application ? using java what platform should I use? :

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

    why not just have findCatByName return the "default" cat. and maybe have the Default cat a singleton since theere is exactly one. or do you do this in the clip after 11:09 ?

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

    John could you send a link to your laptop holder/stand? I couldn't find something with this angle. Thanks!

  • @adolfocarrillo248
    @adolfocarrillo248 2 месяца назад

    "Hey John, you must be a stick for the piñata, huh? 1.95 meters!" 0:55min

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

    Ohh man.... this will be catastrophic when we will start programming the first Quantom computers 😅

  • @dario-viva
    @dario-viva Год назад

    13:57 thats not entirely true. If getAge could be Empty and thus is an Optional, you would need to flatMap it. In your example you return a primitive int. ints can not be empty, they can not even be null. the closest they can get to being empty is being set to 0.

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

    Optionals demystified with your video. Thanks a lot for this precise explanation

  • @StarTheExplorer
    @StarTheExplorer 9 месяцев назад

    One question why ?
    It's better to put a guard instead of remembering that much syntax.

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

    I never used Optional. If a programmer doesn't do null check for the returns, he shouldn't be a programmer at all.

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

    hahaha ,.. u have a cat in real ,.. so cute , pretty .. Now i got to know Why cat object is there in many video. Give me this optional to me .. orElse ..

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

    Hey John, first off, fantastic Video and well explained. Second, would you be able to do a video on the Java Garbage Collector and ways to utilize it?

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

    Looks like the original potato peeler woth brake lights to me. you do the same thing, run into the same problems, solve them the same way. Only now your code monkeys can be almost entirety, but not quite as competent as before.

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

    Hello mr jhon .
    Thanks for your teaching video 🎉🎉🎉

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

    Alright I've had enough of you cooking I'm subscribing 🥵

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

    Nice solution for dealing with null exceptions. So much cleaner than use ifs to check the return value. Hopefully some day java implements de null safe operator like groovy or kotlin. Great video John!

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

    It's extremly inefficient. That's why most of the IDE's tells You that's a mistake

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

    hi.
    how to change the terminal from line-mode to character-mode in windows using java ??

  • @LeandroOliveira-kn9qx
    @LeandroOliveira-kn9qx Год назад

    The best is the final .. advice where to use, generally in return of funciona, not every where creating a mess.

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

    guard keyword should also be introduced in Java to handle optionals in a systematic way…

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

    This is an example of a monad, in case anyone here has heard of monads but doesn't know what they are useful for yet. They generally provide a "Wrapper type" that you can use to chain operations safely on, without having to do intermediate work between every function/method.

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

    Came here to review optionals - left here with a better understanding of optionals and a standing desk... lol..

  • @scrambledmc3772
    @scrambledmc3772 9 месяцев назад

    This looks like a really annoying alternative to javascript's ?? and ?. operators.

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

    I would risk a Code Review bollocking to have called the Optional Variable schrodingersCat.

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

    Great video, thanks for buying a cat for the sole purpose of explaining this to us.

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

    What if the cat exists in the DB, and simultaneously doesn't exist?

  • @Anon-jz7iw
    @Anon-jz7iw 7 месяцев назад

    holy crap i was getting everything but the end just screwed with my head more, would definitely try to apply this in my project to learn it more

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

    Remember, a cat in a box has three possible states: dead, alive and bloody furious.

  • @Ahmad_Al-Deeb
    @Ahmad_Al-Deeb 5 месяцев назад

    "As a side note, if you know for sure, that the thing that you want to put into this optional is not NULL, then you can instead just use optional dot of"
    6:06
    Well, it sounds useless in this case, since the reason we used it was because of null case, right?

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

    I always check out your videos cause it’s very easy to understand even the difficult concepts because of easy to understand explanations.
    I would love to buy the keyboard that you are using , which one is that :)
    Thanks in advance .

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

    Absolute mind blown when you said ur 6’5” holy crap

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

    Maaaan i did not know the orElse() method and its subvariants, as well using Maps on It!

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

    Schrodinger's Optional Cat Box. Great tutorial

  • @hashcodehub6717
    @hashcodehub6717 2 дня назад

    love all of your content , it is clear precise and easy to consume i was thinking that it was really really tough but now i am very much comfortable with optionals

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

    Best video i ever saw on Optional.🎉🎉

  • @Iceman-gm1fu
    @Iceman-gm1fu 2 года назад +1

    thanks for the video. I liked the cat object being used since cats like boxes. to me, it sounds like optionals are used as a communiation device to say something may or may not be there. really drive home the idea that it might be null. if I could, I think I would rename the class to Maybe:
    Maybe maybeCatExists = findCatByName("Fred");
    the next question that I want to ask is "What are actual use cases of this?" You have me thinking. Checking the database for a record is a great example.
    I am thinking about using a jdbc bridge connecting java to sql. Thinking of right/left join on two or more tables where there won't be an exact match one very row. Maybe maybeRecordExists = findRecordByName

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

      We probably get a second optional class in some future release of java. Since there are some huge performance improvements planned for the near future especially effecting optional. And then to keep compatibility they might add a similar type with better performance. Like they did with Vector and ArrayList.

  • @Zerow45yw
    @Zerow45yw 9 месяцев назад

    For your ending statement, what if the return type contains a nullable value but the entire object is not nullable? Is it fine to use optional there as well?

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

    I would've loved a secondary parameter to the .of method that asks for a default of the type contained in the optional, and a method orDefault on the optional, that would basically act like the get but return the default in case of an empty optional. This would allow for a null object pattern to be implemented from the start of the optional and for the users of the returned optional to decide if they care if the optional is empty or to go forward with the default provided by the creator method of the optional. It will also make sense, because who know better what a suitable default of the optional is, if not the creator of the returned value, and if the users of the value want they can always go with orElse, orElseGet, etc if they need a different default behavior on empty optionals. With the way it is now, everywhere you will get an optional as a return type you will have to interact with it in some way, granted, better than an if statement everywhere but can be better imo.

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

    Everything is Good, except delay between two videos :(

  • @nahid7994
    @nahid7994 10 месяцев назад

    The way you explain things, which is really amazing , really short and exact.
    Can you make a video with Java Stream API? Please. Thanks a lot for sharing great way to learn and grasp things.

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

    "OrElse almost sounds like threat" got me rolling😃😃😃😃

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

    It would have taken me hours to look for and understand this information by myself. Thanks John.

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

    "orElse, It almost sounds like a threat." I laughed at this more than I should have. 😂

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

    Long story short: fluent wrapper for nullable objects.

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

    Optionals are great. Or you can just switch to Kotlin :)))

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

    Wondering if you are planning to create Spring Boot content anytime soon :)
    After watching several videos in your channel, I believe that with that highly intuitive style of explaining subtle as well as complex, hard to understand concepts, the new content will attract a lot of views. Happy to be a subscriber :)

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

    So java is for programmers who don't read documentation. 🤔

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

    you just compiled all the facts about optional, thanks.
    can you also make a video on streams and lambdas and collections
    using them together to build business grade logical error-proof solutions..

  • @gokulchandra2566
    @gokulchandra2566 Месяц назад

    Bro literally showed his cat to visualize class named "cat" 😮