Optionals In Java - Simple Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we'll talk all about optionals in java optionals are tough to understand and even when developers do understand them they're constantly using them the wrong way so we're going to clear up exactly what they are when they should be used and how to use them before that this video is sponsored by flexispot flexispot makes high quality reasonably priced ergonomic office furniture and is probably best known for their standing desks they have a ridiculous number of desks to choose from each with tons of customization options this one is the e7 pro plus standing desk i'm recording on it right now its carbon steel frame and dual motor design make it capable of holding up to 355 pounds so you can keep all of your work school and gaming devices and 100 pounds set of adjustable dumbbells on top with no worry it has a crazy height range from 22.8 inches all the way to 48.4 inches i'm six foot five and it goes even higher than i need it to you can program in four height presets to quickly go from sitting to standing with a single touch there's even a usb port right here on the side of the keypad so you can conveniently charge your devices i use that all the time the e7's quality and smart design make it the best ergonomic desk choice for your home office be sure to check it out through my link down in the description because you'll get an extra thirty dollars off your purchase plexi spot is also having their own prime day sale on june 29th and 30th with up to a hundred dollars off their products so start customizing your own standing desk through my link down in the description to get that extra 30 off and i know you'll love it as much as i do now let's get to it first just what exactly is an optional all an optional is is a container that either has something in it or doesn't that probably sounds super weird right what's the point of that so let's start right away with an example let's say that we had a simple method in our program that took in the name of a cat as a parameter and then went to the database and retrieved a cat object with that name and returned it so that would be just private static cat because we want to return a cat and we'll call this method find cat by name and we'll take in as a parameter that string name for the cat that we're looking for now in a real application this would actually fetch a cat from the database but here we're just going to create a cat object with that name and return it so to do that we'll just say cat cat equals new cat now this constructor takes the cat's name as the first parameter so we'll just enter in the name that's passed into this method and it takes the cat's age as the second parameter so we'll just give it the age of three and then all we have to do is return that cat so now back here in our main method we can call this fine cat by name method and we can pass in the name of the cat that we want to find so let's just pass in bread so that method will of course return the cat it retrieved from the database and if we want we can store it in variable so let's do that cat my cat equals the result of this method call so now of course if we want we can print out the age of the cat that it retrieved so print out my cat dot get age and of course if we run it that all works fine and it prints out three but what if there is no cat named fred in the database in that case what should a method like this return well it probably makes sense to just return null right if that cat doesn't exist it doesn't make sense to return a cat it just makes sense to return null but now we have a problem this method is now returning null which means that we're now trying to call the get age method on a null variable and of course if we try that we will get a no pointer exception you see this kind of situation all the time and the only way we can really handle this situation is with a null check just something like if my cat does not equal null then go ahead and print out its age otherwise maybe we print out some default age like zero so this is the way you had to handle this type of situation for a long time in java this whole situation is where optionals come in optionals are a better way to handle a situation where a method like this might not have a value to return so here's the idea instead of returning an actual cat object or null it instead returns an optional an optional is like this box it either contains the cat or it doesn't so basically now what our method will do is if it finds a cat with that name in the database it will put that cat in the optional box and return it and if it doesn't find anything it will just return the empty box and then the code that is processing this return value can ask this optional box whether it contains a value or not and then do the appropriate thing if it does or doesn't so really the main purpose of an optional is to explicitly tell the user of a method that the value that they're looking for might not exist and they have to account for that possibility so maybe instead of just thinking of optionals as a box you can instead think of it as a box that says hey i might not have a value in here so you have to be prepared to handle that situation so now that we know that we want to return an optional of a cat here in our method instead of just a cat object how exactly do we go about doing that so all we have to do is instead of having cat as our return type we'll instead have optional of cat so we just have optional and then cat in angle brackets and here we have this cat object to return but we have to put that cat inside the optional box first the easiest way to do that is with this method here optional.of nullable and then you just pass into this method as a parameter the thing you want to create an optional of which here is cat now this value that you pass into the of nullable method can either be null or not if it's not null it'll just put that value into the optional as we said but if it is null like if this cat didn't exist in the database it will instead just create an empty optional 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 but if you pass in something that is null to this method you're going to get an exception so if you're not sure whether or not the thing that you're passing in is null just go ahead and use of nullable also if you ever want to explicitly create an empty optional you can just use optional dot empty anyway now up here of course we're not just getting a cat object anymore we're getting an optional of cat returned from this method call so we have to change this to optional of cat and we'll change the name to optional cat so now instead of having just a cat we have an optional that may or may not contain a cat so how do we actually get the cat out of this optional first let me show you how basically everybody does it when they first use optionals so there is a method on each optional just called get and the get method will return the value that's inside the optional so you can just use this get method which will return our original cat object and then we can call get age on it and of course like before if we want we can go ahead and print that out and it works however if there is no value in this optional to get so that's like the case if this method didn't find that cat in the database it might create an optional of null so this will return an empty optional and if you try to call git on an empty optional you get a no such element exception which will ruin your day so that's a problem right it's just as bad as a null pointer exception so then most developers figure that out pretty quickly okay i have to do a check on this optional to see if there's a value in it before i call dot git but luckily there's a method that you can call on the optional to check whether there's a value present so we can just call optional cat dot is present is present will return true if there is a value in the optional and false if it's empty so we can set things up like this uh if optional cat dot is present then go ahead and print out the age otherwise like we did before we'll go ahead and print out some default like zero and we can go ahead and run it and it's all good it prints out the default of zero if this optional was empty well perfect that settles it right except hey this whole setup looks suspiciously exactly like the null check that we were trying to get away from in the first place so what's the deal right all of that work just to get something that looks almost exactly like we had before so there's a couple of things here first remember that the primary reason for returning an optional in a method like this is to blatantly convey to the user of this method that it might not return a value that they're looking for and make sure that they know that they have to deal with that situation so even if the end result did look similar it's still making that clear to the user just by returning an optional in the first place but also optional offers some other nice methods to use instead of using this is present get combination and actually the people who created java optionals kind of regret that they even offered this get method in the first place because it's just so easy for people to call something that looks so harmless as dot get without checking is present first so i think when you're first learning the concept of optionals and how to work with them it's fine to use this is present and get combination just to get the feel of things as long as you are always checking is present every time before you call git but once you get more familiar with them there are nicer methods you can use to work with them one of the methods that's commonly used is actually called or else kind of a weird name for a method right almost sounds like a threat optional cat or else but what this method does is kind of interesting so if this optional contains a value it will just return that value but if this optional is empty this method will instead return the value that you pass in here as a parameter you can kind of think of it as a default so we could have something like cat my cat equals optional cat or else so maybe as our default cat we could say new cat and just give it a name of unknown and an age of zero so what this will do is if this optional contains a cat it will just return it exactly the same way that the get method did however or else if the optional is empty instead of just blowing up this method will return this default unknown cat with an age of zero so that's a pretty elegant solution right it gives you the value if it's there but if it's not it doesn't ever throw an exception or anything it just provides you the default value another method that's available is called or else get if you're comfortable with lambdas and check out this lambdas video if you're not you can use this method and pass in a lambda supplier function so with this method if the optional contains a value as before it will just return it but if the optional is empty it will use your lambda method to supply the default value to return again if you aren't super comfortable with lambdas yet don't worry too much about this method but if you are it's good to know about ironically there's also this method called or else throw now what this method does is if the optional contains a value it just returns it but if the optional is empty it will throw a no such element exception now if that sounds familiar to you it's because that's exactly the same thing that the dot get method does those two methods do exactly the same thing there is no difference in fact in the javadocs for git so if you hover over get here in the ide it tells you api note the preferred alternative to this method is or else throw but here's an example of some of the real power of optionals notice that in our situation we were mainly interested in just getting the age of the cat that was pulled back from the database right well we can actually do that with optionals with just a couple of chained method calls so what we can do is take our optional cat and then call a method on it called map what this map method allows us to do is to take our cat optional and transform it into an optional of another type and it does that with a method that we pass in as a parameter that may sound a bit weird but let me show you what i mean so we can actually pass into this method cat colon colon get age again if you're not really used to lambdas yet this looks a little weird but what this method call will return is an optional containing the result of calling the getage method on the cat that was in our original cat optional if our original cat optional was empty then the result of this method call will just be an empty optional as well and it won't throw any exceptions or anything so now with this method call we have an optional that contains the age of that cat and to safely get the value of that optional we can just use a method like or else which if you remember we'll just return the value inside the optional if it exists and otherwise it will return some default that we give it here it probably makes sense to return a default age of zero so now if our original cat optional has a value and its age has a value then this will successfully return that age but if either this original cat optional was empty or its age was empty it will just return a default age of zero and it does all of that logic with just this tiny bit of code of course you can have even more layers of transformation in here as well and once you get used to using it it can be really powerful and there are other methods that are offered by optionals as well and i encourage you to take some time and go through them and play around with them so now with all of that said a question you might have is so where should i be using optionals should i use them anywhere something might be null what exactly should i do and here's the answer that not everybody wants to hear optionals are really intended to only be used how we're using them here and that's as a return type where without optionals your method has the possibility of returning null so it is certainly technically possible to have an optional as like a method parameter optionals are just like any other objects so technically you can create and use them wherever you want but the truth is that optionals were only intended to be used as a return type and that's to blatantly tell the user of that method that the value that they're looking for might not exist and they have to deal with that situation they're not intended to be used just anywhere you have a null variable it's meant for just this type of situation so try not to overuse them but in this type of situation they can add a lot of value and help you avoid null pointer exceptions as always if you enjoyed this video or learned something please let me know by hitting the like button and be sure to subscribe so you don't miss each new java tutorial and be sure to check out my full java course in the link down in the description as always thank you so much for watching i really do appreciate you being here with me and i'll see you next time
Info
Channel: Coding with John
Views: 75,689
Rating: undefined out of 5
Keywords: java, codingwithjohn, coding with john, java beginner lesson, java 8, java 8 optional, java optionals, optional in java 8, optional usage in java, java 8 features, java tutorial, what is java optional class, what is optional class, java optional, java 8 interview questions, java optional ifpresent return value, java optional tutorial, java 8 tutorial, java 8 lambda expressions, java 8 new features, java 8 interview questions and answers, learn java, java full course
Id: vKVzRbsMnTQ
Channel Id: undefined
Length: 15min 53sec (953 seconds)
Published: Mon Jun 27 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.