Methods in Java


In the previous video,
we talked about the if keyword, and then went into more
detail about the code block. And we also talked about some of
the issues with code blocks and duplication of code. What we’re going to do in this
video is talk about methods, which is a better way of ensuring
that your code isn’t duplicated, and also makes your code
a lot easier to maintain. So I’m gonna make a bit of space here. And what I’m going to do is I’m
gonna paste the code that we used in the previous video. And if you recall it was this code and
then when we ran it, we got two final scores. So we got a 2,300 and 11,600. And of course the big
issue was if you recall, I changed the code in one place
in the first code block, but not in the second code block, showing
you how easy it was to have errors. Because you’ve got duplication of code
that is essentially doing the same thing. And it’s just not really convenient. And if nothing else,
it’s actually more effort for you to have to create
this code multiple times. A lot easier if we can create code once,
put it in an area, and use it time and time again. And that’s what a method gives us. So let’s have an attempt
at creating a method now. Firstly, you may not be aware of this,
but we’ve been using a method all along. This entire thing here,
this entire section of code, that is actually a method. And the method has the name of main. And all the code in the middle of it
is the statements that form the method. So if we wanna execute the method main,
this is what’s gonna be executed, all that code that’s in there. So what we’re gonna do is we’re
going to create our own method. We’re gonna call it calculateScore. So I’m gonna put it down here,
underneath the last brace. And you can see that brace matches
up with the public static void main. This is an IntelliJ’s way of saying
that these two things line up. So we have to start our code for
a new method outside of another method. You can’t put a method within another
method, they need to be outside of it. And also when you’re creating a method,
you don’t wanna put it too far down. We don’t wanna put it outside
this public class definition, and we’ll be talking more about
that in future videos. It has to be within that area there. So, this is where we
would actually type it. So, we’re gonna call our
method calculateScore. So, we type it,
we type public static void, I’m putting spaces between all of them,
calculateScore. Now don’t worry about public and static, we’ll be talking about
those a lot in the future. For now just keep note that you
need to actually specify and use the terms public and
static when you’re defining a new method. And void, so, for the three terms
here the public, the static and the void, all in lower case and
all separated by a space. Don’t worry what they mean at the moment,
we don’t need to know that. We’ll come back to that shortly. But, they are all keywords as we
discussed in a previous video. The ones highlighted in blue are keywords,
so they’re part of the Java language. So what we need to do is put
our code in between the braces. Anything that’s in between the braces
is a statement that is part of this method that we’ve
called calculateScore. And when we execute this method, and I’ll show you how to do that shortly, all
the code we put in here will be executed. So to do that, I’m gonna copy this first portion of
the code and I’m gonna paste it in. So, I’ve pasted it into
our calculateScore method. And now what we can do is from within
the main method, we can call this method. So, how do we do that? Well, firstly we’ll delete this part
out cuz we don’t need this now, because actually that will occur in here. So to execute this calculateScore
method we just type calculateScore. I can see as I started typing,
IntelliJ came up and said oh, do you mean calculateScore? If that’s the one we want, you just press
Enter and just put it in there for us. And you also may not have noticed but this
was a light gray before the actual name. But now we’ve put that
in to turn to black. And what that’s saying
is IntelliJ’s saying, I can see that this
method is being used now. Just to confirm, if I delete that, it goes to light gray
again and it says it’s never been used. So that’s a handy way to know if you’ve
got any methods that aren’t being used in your programs. Check to see whether they’re
light gray in IntelliJ. We’re gonna put that code back. So, what we’ve done now is we’ve
actually said, when we get to this portion of the code, I want you
to jump ahead and then run all this code. And once you get to the end,
come back where you left off, then continue on from down here. So what should happen is, look,
it’ll define the variables. It’ll run this through once and then it’ll come through and
run the second part for us. So, let’s try it out. We should get the same result. And you can see that
it’s worked quite nicely. So, how would we do the second component? Well, we would normally have to
create a second method to do this second part of the code. But of course, doing that would mean that we are
effectively duplicating our work again. So we haven’t really fixed anything. All we’ve really done would have been just
to convert our two code blocks to two methods. So there must be a better
way of doing that. Well there actually is with methods, because we’ve only started to use
the very basic components of methods. So if you think about it, so what we’d
really wanna do, what would be ideal would be is if we could pass this information,
whether it was gameOver, the score, the level completed, and also
the bonus, to pass this to the method. So it doesn’t have to create
the variables, so they’re sent to it and that it can actually work
with those variables. Well, as it turns out, we can do that. We can actually pass
information to a method. So what we need to do is we need
to look in this bracket area and we need to define the parameters
that are part of this. I’m just gonna close this so
I’ve got a bit more space. So, what we need to do is define
in the method what parameters or what information we’re sending
through to it from our main method, from where we’re actually
calling the method. So to do that, we just type in
the type of the variable and then the name we wanna use it. So we can top Boolean, gameOver. And we separate each variable that we
wanna pass the type of information with a comma. So the second one, we’re gonna put
a score, which of course is an int, so it’s int score. You notice I’m not
putting the value there, I’m only putting the data type,
and the name of the variable. You’ll understand why shortly,
why we’re not putting the value. The third one, was the level completed,
also an int, levelCompleted. The last one was a bonus,
we’re going to call that int bonus. So, what we’ve done is we’ve now said this
method now has to be sent four parameters. And they’re a Boolean and three ints. So, you notice by doing that,
first we’ve got errors here now. But we’ve also got an error up here now. So it’s actually wanting,
it’s expecting four parameters and these are the four parameters
we’ve defined here. But, it’s actually saying well,
the arguments that you’ve actually sent, you haven’t sent me any at all. So there’s none at all and
that’s why it’s actually complaining. So, the parameters is what we define in
this section when we’re setting up a new method. They’re the parameters, but arguments are
the actual values, not the data type and not the variable name but the actual
values that we wanna send to the method. Now, so
we’ll come back to that in a second. So what we wanna do here is we
wanna actually send the data by placing the arguments to
the calulateScore function. So how do we do that? We can type the values that we want. So, we can actually just type, true 800. And just to confirm,
if you go back and have a look. We’ve only typed two parameters. IntelliJ is saying, okay,
you’ve got two there, I can see gameOver, the actual argument is set to true and
score set to 800. So they’re gonna be the values that
match up as we call the method, but there’s still two we need to finish off. And they are level completed, noticing I’m putting a comma between
them both, levelCompleted and bonus. As soon as I enter the last one, we
suddenly haven’t got any errors anymore, because as far as IntelliJ’s concerned,
the actual arguments that we’re passing match the parameters
we’ve defined for the method. And this is really important. If you don’t match those entirely,
you will get an error. So in this case,
because we’re matched up properly, IntelliJ is happy with that error,
but it’s still complaining here. And the thing is when you’re
creating a method, and you’re defining parameters of
a certain type and a name, you then don’t have to create
them in the method at all. So we can actually delete that. Cuz what actually happens is if you define
these parameters, Java will automatically create variables with the appropriate
data type for us, which is really nice. And they’ll be deleted when the process
goes back to the line after the calculateScore. So in this case I deleted those variables,
so there’s now a variable called gameOver, score, levelCompleted and bonus that have
been created automatically by Java for us. Because we’ve defined those
as parameters for our method. And now, we’ve got no errors, so what we should be able to do is
actually just run this code. And we should get the same result
as we had with our code blocks. And you can see,
we got exactly the same answer. So far, so good. And we cleaned up some of the code,
but it’s still a little bit messy. And the reason it’s messy is we’ve
still got this extra line here. And I’ve also got these variables. Let’s change the second one by doing this. calculateScore(true,) again,
cuz that’s the first parameter. You notice as I’m typing, IntelliJ is highlighting which parameter
you’re up to when you’re typing. Which is really nice,
it does that automatically. So, the second parameter was 10,000. Third level was 8, and
the fourth one was 200. So they’re the four parameters and
they match up to the score, the levelCompleted and the bonus, which is the second statement that
we’re actually going to execute. But notice this time,
I’m actually typing the values indirectly, I’m not using variables or
anything like that. So, consequently,
what I can now do is delete that. Then I can actually delete these
cuz we don’t need them anymore. And now when I run,
the first value’s the same but notice the second value has been fixed. Why has it been fixed? Well, we’re calling
the calculateScore method. It’s got the fix. So of course the second value
has now got a score plus 1,000, cuz it’s correctly got the fix in there. You’ve noticed that we’ve only actually
programmed this code once now. So there’s only one place that we can make
changes to it and we can make one change, like we could change that
final score to 2,000. Execute it. And both scores automatically get updated. That’s because they’re both using
the same method, which is pretty cool. Now the other thing we could do here is,
instead of putting half values and half variable names, I could actually finish
this off and actually put five there. Cuz that was the level completed,
five and the bonus was 100. I can make this even more efficient by
deleting these variables because of course we don’t need them anymore. And we’ve now got a far more
efficient looking bit of code. We’ve literally only got two lines that
actually send information through to the method. And we run it and
we get the same result but of course we’ve added the final score of
2000, which is why the values are higher. So that’s one of the great
features of methods, is that it makes it a lot easier for
you to maintain your code, because we’ve only got one place now
where our code is modified, one method. And also you notice that we
cleaned up a lot of code, there was a lot of extra code
we had in our main method. We’re down literally to two lines. Now incidentally there’s nothing stopping
us actually using the variables that way, the way that we had them before. Like for example,
we could paste this in and then we could change our
arguments to put gameOver, score, levelCompleted, bonus, like so. And also down here we
can do the second thing, we can put those new values there,
delete this out. I’m putting that new call, so
this is a good way of also creating code. Cuz looking at this now, you can say okay,
this is the calculateScore method. GameOver must be in some sort of
indicator as to whether it’s game over. That’s obviously the score we’re sending
through the levelCompleted and the bonus. You can see how that would make
more sense from reading that. You get an understanding of what
this particular method does for us. So you’re free to use hard coded numbers, literal values that I just
had there previously. Or you can define variables,
if you like, and use the variable name. And what happens is, when the method
is called, if you’re typing, if you’re using variable
names as arguments. The case of of gameOver, what happens is
the calculateScore method gets called. Boolean gameOver, it looks at the value of
the gameOver, in this case it’ll be set to true, and that’s what the Boolean
gameOver parameter gets set to. And of course,
that then matches with this in the method. So either way will actually work. Now, that’s pretty good in it’s own right,
the fact that we can actually call a method and get it to do something and
to make our code look a lot cleaner. But, it does actually get even cooler
than that, because what we can also do is we can get our method to do some
calculations much like it’s doing now. But we can send back the result of
that calculation or that processing, whatever we’re doing, back to the code
that it was executing that actually had called the method in the first place. So, we can get the two of
them to talk together, so we can calculate something and send the
value back to the code that was actually calling the method in the first place. And it would probably be easier if I show
you rather than try and explain anymore. So to do that, this makes use
returning a value it’s called, makes use of this void keyword. So what void means is
don’t send any value back. So if you’re creating a method and you don’t want to return any information,
you use the word void. Void means nothing, either empty,
don’t return anything. But if we do wanna return something, we
need to change the word void to the type of data, the data type of the information
that we’ll wanna send back. So in this case, let’s actually
return what the final score was, return that as a score that we
can use back in its method here. So, in other words, right here,
when we call this calculateScore method, we don’t know what this
calculation ends up being. We only see that it’s
displayed on the screen. But let’s actually get that number that
was calculated here returned back to us. So, what we need to do is
change this void first. We wanna say we want to return some
data that is of data type int. Immediately IntelliJ says,
you’ve got an error. And the error is that we’ve
defined it as returning data but we haven’t actually
told it to do that yet. So what we need to do is we to add
an additional line of code to tell it to return that information. So how do we do that? We come down here and
we put return finalScore. What that actually does is it sends
back the finalScore back to this part of the program. But the thing is,
we’ve still got an error. So why have we got an error? Well, when you’re sending
some data back with a method, you’ve gotta make sure no matter
what that some value gets sent back. It’s not okay to just if gameOver
is set to true to return a value. We also have to send a value back
even if gameOver isn’t true. So in other words, all the program
variations have to be accounted for and we’ve got to return something every time if we specify that we
are gonna be returning data. So a quick challenge for you,
how do you think we would change the code to return a -1 if
gameOver was equal to false? Pause the video, see if you can
figure that out, and come back and I’ll show you how to do that. Okay, how did you go? There’s two ways of doing that. We could actually put an else here,
else, and we could just put return -1. That then removes the error, so you can see there’s now no longer
a problem as far as Java’s concerned. Because if gameOver is set to true,
it’s gonna return something. Else, in other words the else here is no
matter what else happens, return a -1. So that’s gonna work. But we could also have done it this way. We could also have put a return -1 here. So what happens there
is the same deal here. The return gets executed here. Soon as the return keyword is hit,
soon as it processes that line, it doesn’t go any further. It immediately goes back to wherever
the call code was that actually called the method in the first place. So consequently, we’ll only get to this line here if
this previous line hadn’t been executed. And therefore Java is happy that
we’ve covered our bases and we’ve returned something no
matter what the program flow was. now one final point if you’re wondering why we’re returning negative one here in programming terms negative one is conventionally used to indicate an error and in searching algorithms negative 1 indicates an invalid value or a value not found so that’s the reason using negative one here Okay, this video is starting to drag on. So what I’m going to do now
is pause this video and we’ll continue on with
methods in the next video.

Leave a Reply

Your email address will not be published. Required fields are marked *