A Rookie's Guide to Java Part 2 - Conditional Statements | Harry Wainwright | Skillshare

Playback Speed

  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

A Rookie's Guide to Java Part 2 - Conditional Statements

teacher avatar Harry Wainwright, BSc Software Engineer

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

6 Lessons (35m)
    • 1. Class Introduction: Conditional Statements

    • 2. Handling User Input

    • 3. "If" Statements

    • 4. "Else If" Statements

    • 5. "Else" Statements

    • 6. Try/Catch

  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.





About This Class

The second class in A Rookie's Guide to Java, we cover branching statements and how they can be used to handle a situation with two or more outcomes.

A Rookie's Guide to Java, previously released on Udemy currently holds a 5-star rating and boasts hundreds of happy students. Now I'm bringing it to Skillshare! A Rookie's Guide to Java assumes no prior programming knowledge. We start at the very basics and work our way up to some fairly advanced topics, including Java Swing. This course comes with written material to recap what you've learned at predetermined points. This truly is one of the best ways to learn.

I often see courses claiming that you can "Learn To Make Video Games (No Programming Needed!)" But unfortunately if you want to make anything more advanced than flappy bird you'll need a programming language under your belt. Learning programming is fundamental to any career in the software industry, games or otherwise, and Java is a great starting point.

Java is the most widely used programming language currently so you cannot go wrong by getting to grips with it. It holds a heavy focus on the "Object Orientated" part of "Object Orientated Programming" and as such it is a subject that features heavily in this course. 

Meet Your Teacher

Teacher Profile Image

Harry Wainwright

BSc Software Engineer


I have years of programming experience and have spent time working on projects ranging from video games to dynamic websites, and responsive databases. With a particular interest in object orientated programming, I intend to share all here on Skillshare.

Professional, concise, informative tutorials on a variety of object orientated programming languages for all levels of experience.

See full profile

Class Ratings

Expectations Met?
  • 0%
  • Yes
  • 0%
  • Somewhat
  • 0%
  • Not really
  • 0%

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.


1. Class Introduction: Conditional Statements: Okay, then. So, kicking off this section, we start off by handling user input. I mean, if you think back to any problem you use in your daily life, how many of those actually go on by without any user interaction? Pretty much every program that I can think of any way it requires some form of user input. So we kick off section to with that before we move on to conditional statements, which is, you know, the name of the section, as includes, if also if else statements along with a try catch, there was a bit more advanced know, exactly necessary number the if else if else certainly are. And it basically just allows us to handle more than one outcome. It is the simplest why I can put it instead of just linear programs. If that doesn't make a whole lot sense here right now, we do spread it out across, You know, five different lectures, so you'll have plenty of time to learn what that means. 2. Handling User Input: Okay, then. So let's talk about user input. Um, is your input? As you probably tell by the name, it's fairly descriptive his getting the user to import something amusing. You know, they cabled, Oh, my house or control or whatever in Java is slight. More difficult than, say, python or C plus. Plus, those are both very simple, but it's easy enough again. User input will allow us to do, ah, bunch cool things because so far, all we've been doing is using, you know, these pre programmed values. But, you know, if I could get the user tend to their own age, for example, or their own name, and it's obviously a little interesting, So the first thing we're gonna have to do is import a package. They're uncovered this year. Essentially importing a package jar is built up of many of these packages. I don't know whether beast old probably somewhere in here be exceeded is that there's a lot of, um, trying out so it And if it if imported all of those by default, then the program would be huge and and take hours to run on FB Super super inefficient. So if we want a special package, then we have to bring in ourselves. So we're gonna do that. So blow this package line. If it's created that by default, it might know of if it has below that. If not, then just first thing in the program. You wanna type input? Imports are a java dot You till the scammer capital. Yes, it's all that does. Is imports this scanner class within this utility package? Pretty simple. So far, you will have to do that. Sometimes you're type a line of code and you'll get an error. But if you hit old tent er over the era, then they'll probably just the first line will be import this package. Then we have to do something with this scanner so better we're calling the scanner class here. I'll go into more detail on this in late tutorial, but now just no, that we're calling this kind of class similar to how we were calling a string to make the words variable or an instrument the age variable. We're calling the scanner to make an input variable called input. What we do after is a bit more different that we are telling the computer the scanner is going to be equal to whatever the system takes in. So so far we've been printing out with system out system dot in is the opposite. As you can imagine, it's printing in from the council into our input variable. So if we want to print this out, we'll print out what the user is saying. We're just gonna do I usual system the other print. Then we have to user input that they will not work. You have to use another function called next line, which is input dot next line Capital L. With these open and close brackets, it seems far more confusing than it actually is. So I was gonna get rid of these two prints down here so you don't get confused. Its last run, the partner, we run the program and we brought to a consul. So what it's doing now is it is on this line here waiting for the scandal to pick something up, and it won't obviously print anything out until we've type something in. So let's type something in one's got like, Hello world E. C. On the next line in Prince. Hello world. Why is that? Because the programmes pauses weighing something's come in. And then once we type wherever we typed in a system out print import don looks like fall is doing is printing out exactly what we've taken in Incredibly useful. Why'd you want Teoh Taipower? No prints out whether the uses just typed in. Well, you could do with this what you can do with any other information and can store in variables. So let's create a string called at a No name, no names. Good strength on we gotta I have it as import dot Next, the line got extra bracket. There are so and then instead of Print Scout Iran put down next line, which is gonna print out name space that out for you. It's not from this is gonna wait for us again, But this time name is being stored. Oh, the imports being sold us the variable name. Now this is far more useful, but I'm sure you can imagine So now the program, we can ask the user to enter whatever name they have, so we could have exactly the same with inter jizz getting user input. There is a slight difference, however so Hey, we've been taking a string of have been using the next line function. The next lines reads in the next. You think next Lime is actually reading in the next set of strings. If we want to bring in a and interview, go change, open it. So first, let's change our variable. Teoh Ah, In age we've already got one of down there, so I just coming out for now. Come on, both of those out. Eso We're still getting the Saracens incompatible types Drink cannot be converted in Why they're saying that? Well, because age is an integer but next line is looking for a strength. So we just gotta change this next line into next really simple change. But now it is just gonna look for the next interview. Obviously, if retired tried to type a string band in the consul into into this interview when we get an error. So we have to specify that not only is it going to be in in there were typing in, but we're putting it into a didn't type is well, get it, get it. Let's give this a will. Find out how to run it. We've looked at my friend. It's already running. It's gotta cancel that one there again. Let's try again. Bit more successful. So 20 years old boot prints out 20. Uh, let's run it again. Try and type in a string. What's gonna happen? Exception in thread Main Java util Input miss much so you can see it gives you the error very clearly. Um right there input, miss. Much exception. I don't break it down by line specifically online. 11 here. Eso We've tried typing a string and put it into this interview age here. I was never gonna work. I was curious to see what would happen. So always remember, if you're typing in into an interview is the next in function Otherwise she's the next line function. 3. "If" Statements: okay again. So we're going to be introducing the ISS if else if else statements in this section of the course, Um, you coming on programming before? Basically, what this will allow us to do is to have branching statements. Will have more than one answer to a specific question. It doesn't make much sense of the moment. I know, but we'll go through it step by step, will introduce each time, as I've done in my past courses. And hopefully, by the end of it, you have a good understanding of actually how important these are, too. Any object orientated programming language. So let's stop. I walk through what I did to this program. Basically added, Put it all together, have needed off of it. So we declare our scanner appear which still called input. Just ask them to import their name. They do so in prints out. Hello. Name Real Simple. Carrying on West. Um, how old they'll then put their age, which is an integer next in in and then print out. You'll, however old exclamation or question all simple. So what we're gonna do is write a program where if the user is a certain age whether they're older, younger or the same ages May we're going to print out a different response to that. So first thing have to do yourself a computer age. She was gonna dio up here without input. Variable. I guess that 2020 in computer age equals 20 one of the used in variables that you're gonna reuse plenty. It's best to declare them at the top of the, uh it is. It is the top of the program. We don't mind declined string down here because it's we need to get after after this line. I mean, we could declare string up here, name appear, call the string name, and then get rid of the declaration down here. Seven name equals. I think it would do actually exist. Nita, I think it's a good idea to declare our variables all at once at the top of your class or function. They okay, sensitive. So if you do a capital out there and not down there, you're gonna have problems. So we got compute rage with declared 20. They're gonna input whether age they'll on what was named They are. Names are important. So to branch off, we're gonna have them being younger than me. So if computer age is less than age, we're just gonna system out print very lazy. I've hit a magical key that will delete everything I get along. Nice go. Let's go Ignore it said that, Ben, there's a horrible key compressing it really annoying. Always forget which cancels it. Let's run this program here. I'll talk you through after it. So it's saying Hello. What is your name? Harry. This line's pretty irrelevant. How old you? Let's enter 18. 18 you're 18. Build successful. So why didn't imprint this? Well, it runs through our program. That's full of variables. Asas are name ass in their age ages. Input into this variable prints out that line and I guess, to hear you notice them on this room. But did it run behind the scenes? He did. Ah, this if statement here checks whether computer age is less than age. We just said, aged 18 there's no way computer age is less than 18 cause peerage 20 twenties, not less 19. So this system will only run. What's inside of it If this is true, computer age or 20 is not less than 18. That's not true. So this line isn't gonna room. So if we run it again, if anything preferably without typing were typing in council from this again, we enter 21. You're 21. Your older than me. So this time this line run, he didn't for my properly, but he did run your older than me. That's because 21 is greater. Sorry. 20 is less than 21. That was true. This lying around over the next two videos, we're going to you create the other two outcomes. So we're gonna have, you know, older than age and exactly equal to it. The hopefully baggage in inside. A bit of an insight into what if statements are 4. "Else If" Statements: So let's run through the other two outcomes we can have. We can have. Computer age is less than ages. We've already written here. It is greater than H or we have it exactly equal to age. So we've got more than one possible outcome. What do we do? Do we write another? If statement we could do it would be valid, but it would be it be pretty crap card in a lot of state. It looked terrible. And it's not great Will cause problems later on what we actually want to do instead of another If statement, we want an else if statement so if If Yeah, if this if statement isn't true, it will move on to the next else if statement and inside of this else of statement was gonna have computer age is great to that age. Yeah, that's what wrong on. And I was gonna prints are feel old roommate. So it's gonna be less than 20 this one. So just type in 15. Your 15 year old with a great So it runs through the program blah, blah, blah checks This if statement that comes out as false because compute rages, not less than age. That's 20 as 15 that is. A false statements of this line will never get printed. None of the code inside of these two brackets will ever get rented. Eso it moves on to the next else if statement checks if compete rages. Great of them. Age finger is 20 is gray than 15. So it goes into the else a statement into the first line of code, which this system out your old with may. So you put duper simple. 5. "Else" Statements: so the final the only outcome have left is the computer age is equal to age. We've got one more key word that we can use to signify this, and that is else. So if that is not true and that is not true by default, else must be true. That's how it works. It checks full. The ifs and lfc are not true, false, false. That means the else will print. So this is kind of the default. If you will know in those true, then the else will print. And obviously, if compute rages not less than age, it's not great oven age and anything that it could be a is equal to age. So let's type in here we all the same age now if we enter 20 into the council. So it's exactly the same as Computer Egypt here. When will any look it will trigger the else. Yet we all the same age perfect, so that works fine and dandy else just triggers. If nothing else is true, This white units called else, uh, this is an ideal bar using an else statement. In this way, it's not. It's not the best outcome because as programs. Progress says you get later on into Java, you will be crying bigger and better things. Except for etcetera. You'll come onto branching statements that have more than one outcome more than three outcomes. Even so, it would be far more complicated. Won't just be less than greater than or equal to. He could have dozens on do you don't want to try And you could always forget One is what I'm saying. You could always forget one. So really, you want to use l statements as can work a catchall error message, if you will. Someone's gonna typing error here. Uh, you can get way more specific as to what they are actually is obviously, uh which lto era? Not greater, then less than a lot equal to If that happened, I'd be very surprised. That's what you want to use out statements for If you want to try and catch with many outcomes as you can, you know, on your own, uh, we know all three outcomes. So we're gonna right the equals two in a different else. If statement you notice I had to use to equal signs there. If you're using one than it, we're trying to sign webs on the right. The left. That's how we declare alive variable. So saying computer age to whatever is on the right of the equal sign. If we just used one equal sign, then we'd get an error message. He can't convert into Boolean. It doesn't help. So if you comparing two different numbers and you need to use double equals, it's now if it run, this is gonna run exact for the same. Do you have to type in council? Yeah. See what we're What's happened here is Prince about your old with me because I never changes. I saying I want to be a big error message. In fact, it's not just me being silly. Yes, I did work up from us. We're the same age. So it checks the if statement, false checks, the also statement, false cheques, this else of statement, true prints the line. If obviously, if none of those are true, they'll come back false. Then we've got a big problem and I'll print out this else s That's else. If else statements they are pretty fundamental program. And so I do recommend you have a play around. It's a soup. Simple example are back to use in all of my courses 6. Try/Catch: said today I'm gonna have ah, try and catch closes. Previously it was it was a while ago now, but it turns to replace this in the in the course of supposed. But previously I've said I tend to use else statements as a sort of catch. Ah, catchall for errors. Eso do if else if you keep repeating else if you only use else for errors or error messages . Last generally just my coding preference, but certainly not necessary. Java has a built in function that will allow you to catch errors. Ah is called a try and catch. Try and catch. I don't run. A late call is but two key woods. Try and catch the first thing I wear. Those import our job utility, which will take in, um, which allow us to take in user input. Something like that. Yeah, I guess so. The main hams got type in. I was gonna get the user to import their age on its age. Uh, let's have it go to a function. Um, it's cool. Check age. So here we're gonna create our function. Got never that's just going to find it. It's gonna be a public aesthetic int this gonna take in? Um, that's going to check for us. The scare check for us. So call it Check Ouija s. So this is where we introduce our try and catch statements. So try essentially how to try and catch was is it? Tries? Ah, our input on def. It's not correct. Then will be able to catch in the catch bit and do if we want in the country Just put our errors or we condemn to enter again because in tribe it I'm gonna get the user input. Ah, I'm not defined. User input Generally I thought it was done automatically. Haven't been honest. Ah, goes up. Scanner of MMA having a deal again. Taking user input in job It is a bit of a pain from being honest. It's not something I cover. I felt something. I've done too much in just using scandals of pain. I believe that's right. Ah, string can't be covered in Oh, it's Clinton. Take abs while searching for a string there with next S o Donnell There are here. Let's just catch just last names for a catch. So I'll be sure to fix that now. Um, catch We just typing. Catch Chapman. I'm gonna get back to the Iraq's it. You see it? Yeah. Give us. Finally, is another option the home's gonna stick to catch, I believe finally come using conjunction with catch so that no wise point it way out. It's kind of annoying. I was never given anything, uh, believing Put finally down here correct year. So asbestos to catchall off the catchall. Essentially, if if you don't do everything you want in here and catch then finally finally will be a last resort. Nobody cover finally there. Ah, it's a figure more ready Going to be on my way to just do try and catch trying catches and something I personally using my in code that I figure it's worth known eso We haven't given any import here. The catch bit You're gonna have to look up on the Internet because catch takes in a bunch of exceptions. That's how they work. Ah, I would still quick giggle, see if I can get you a few examples. Uh, and that's no help. Yeah, I suppose, is so And see just from the gel for documentation, there's no catch in. Try and catch on here But if you go down here, we've got a an example of the exceptions here. This is just one that is given when you go outside the bounds of an array, her index have bounds exception. We're obviously not working on a raise. We're working on imports, so the one we're gonna have to use is input, mismatch, exception. And then we've got to give that a variable type off that exception. So I was called mine era. It doesn't have to be our It could be anything. You just give it a thorough way. Variable name. So you have to look at which exception you're trying to catch. Essentially, you be able to find it in the documentation. You just saw the array one there. But because we're checking the users import, gonna need import miss much exception. So this is assuming that the import is incorrect. If it's correct, then we'll just return it. But this will be triggered. If it's not correct, Onda ways could be triggered. I'm not entirely familiar with the ins and outs of input match mention miss Much exception . Sorry, but as we're looking for an end ital check If it, you know if it's a double or a flow or a string, essentially making sure that is just in interview because that's what we're looking for here. I'm sure it covers some other things, but mass. The main reason we're using it for. So let's go back to our user input here. Sorry if you had the thundering them. Uh, so we're using our input that use input dot Next. Obviously we're not returning it. We're just using it. So this is gonna essentially ignore the line. Um, that makes sense of these is import with the import appear? Um, it's incorrect. So we're gonna call this line here, and it will essentially just ignore the line move onto the next one which users want to put anything into. So we're basically just clearing out the crap that was incorrect and then was given some error message, like and, uh, into it. Manimal Trouble type can stay. I'm spelling, apparently Internets. Yeah, so that should be fine. I think, uh, I made it so missing return statements because we haven't put a return out here. So obviously, is this an interview? If it's correct, will need toe in return. Whatever the uses import. But if it's incorrect, we need to return a default. Someone's gonna have it returns zero in that case, and then up here, we can step in if statement. So if age does not equal zero ah does not equal zero. We'll just have it printed out. That should be it, I think, Ah, saying there is not used. But that's fine, I believe. I'm sure it's fine. Ah, and this should not be here. That's what I was actually thinking off. Put it outside the try there than cause problems happen inside. The catch sends me clean. That's one that. How old do you assistants? 10. You're 10 years old. Satisfied? Walk us through the program here. So how old do you in check age? So we've import our answer there, and it goes straight into check age. So we're going to check age here. It tries it. It tries our line High user input dot Next in so weather into two of type two. Um, obviously, if I didn't come back as an integer, then it never get to the stage here. Expedia isn't here. It returns there again to the in checks. It's not Zira and then it prints out this line. Let's run it again. We'll try string. This shouldn't even get past the first line because we're obviously checking just for next in, uh, such as type in string, he says. Entered into just so it was cool by catch the so input match exception, it looks for the next and put ah, it is not correct snot into your So we sort you out. Ask him to type it into you and then we return. Zero. There we go. We return zero. So we never get to this line felt If if we didn't have that, then it just print out well, but it print up. It gives an era high margin, so we'd be trying to put a string into age. Let's give it a go Internet into Julia's area, years old. So I think it was an age, actually, just past three. The default zero put that like in, uh, I was just going a bit off track there to see what happened. Yes, that's fine. That's how trying catch works is a fairly simple concept. Let me just see if it works with, I mean should work with floats, but Yeah, we're still working. Fine is it's looking for an interview, and if it doesn't get inside your them, it will be caught by the catch. Anything that's might get you on this bit is the exceptions that you'll need tonight. I can't list them all because there's a There's a fair few, but there'll be a page somewhere on the job for documentation that will give you what you need tonight. Ah, if you if you don't know which one you need specifically that just Google it stack overflow . Have a 1,000,000 different questions about that, I'm sure.