Java programming for beginners - Lesson 7 - Methods
Introduction
Hello everyone, welcome to the eighth lesson in my Java programming for beginners tutorials series. The seventh lesson(lesson - 6) - While/Do While loops can be found at - https://steemit.com/programming/@robertlyon/java-programming-for-beginners-lesson-6-while-do-while-loops
In this lesson I am going to be covering something called Methods, methods are a programming construct that helps to break your code up into more manageable chunks. It can also help with code re-use, for example, if you wanted to perform an action that required multiple lines of code. You could put that action into a method then you only need write 1 statement each time you want to run that specific action.
By the end of the lesson, you should be familiar with the syntax for setting up a method and be able to create your own.
Methods
What are they?
Methods are a way for you to break up your code into manageable chunks. For example, if you are creating a program that has a lot of different actions you could create a method for each of these actions. If you think of a bank account. I could create a method for debiting money, a method for crediting money and a method for checking the balance. This will mean I only have to write the code for each of these actions once and whenever I want to perform this action all I have to do is call the method.
Have a look at the code examples and explanations below and hopefully this bank account analogy will become more apparent.
Code examples
Example 1
public class Method {
public static void main(String[] args)
{
time(19, 25, 55);
}
public static void time(int hours, int minutes, int seconds)
{
System.out.println(hours + ":" + minutes + ":" + seconds);
}
}
Code Explanation
So as you can see above I have included two examples of a method, these methods both perform different actions and have been created to show different aspects of methods. I will go through example 1 first, then I will compare it with example 2 to highlight some subtle differences.
Example 1
So in example 1 you can see our main method as always, you can see that inside this method there is a statement and we will come back to this statement at the end of the explanation.
The first thing to notice about this program is the second method we have declared called "time". We will ignore the public and static keywords, for now, I will come on to them when I start to cover the topic of classes. The first word that we need to be concerned about is the word "void". void means that this method returns nothing, (returning things will become apparent soon).
After the keyword void, we have the name of the method "time". The convention for naming methods is the same as it is for variables(starts with a lowercase letter and uses camelCase). This name will be used to call the method when we need it.
After the name, we have the parameters of the method. A method parameter is a value that is passed to the method when the user calls the method. This means when we wish to use this method we have to give the method 3 int values, one that represents hours, one for minutes and one for seconds. An important thing to note here is that when you are giving your method parameters you must declare which type of value you expect to receive(int, double, String, etc..).
The entire line public static void time(int hours, int minutes, int seconds)
is known as the method header, although the keywords/parameters/name will change this is a rough idea of what method headers look like.
So the next part of the method is the body. This is the part of the method that gets executed when the method is called. In this method, the body contains a simple print statement. Note that the variables that are used in the statement are the variables that are passed in through the parameters.
Now we come back to the statement inside of the main method time(19, 25, 55);
. This is what is called a method call. When you want to use a method it is said that you call that method.
The first part of the statement is the name of the method that you have created, in this case, the method is named "time". The next part inside the parentheses are the arguments. When you create a method you give it parameters and when you call the method you pass it arguments.
The values inside the parentheses correspond to the parameters that we set in the method, this means that the parameter hours will hold the value 19, the parameter minutes will hold the value 25 and the parameter seconds will hold the value 55. When the method is called and the parameters now hold this value, the method body is executed which in turn executes the print statement which prints its contents to the console.
We will now have a look at example 2 which is similar but with a few slight differences.
Example 2
public class Method {
public static void main(String[] args)
{
System.out.println(addingMachine(2, 2));
}
public static int addingMachine(int num1, int num2)
{
return num1 + num2;
}
}
So in example 2 you can see that there is a method call in the main method. From the last example, you should be able to work out that the method name is addingMachine and it takes 2 integer parameters that are both passed the argument 2. Note that the method call is inside of a print statement, we will find out how this works when I cover the return keyword in the method body.
Looking at the addingMachine method header we can see that there are 3 differences. Instead of "void" the keyword is now "int". This means that the method returns an int value. The second difference is that the name of the method is different and the third difference is that the there is only two parameters instead of three.
The main difference between the methods is their purpose. The last method printed out the time whereas this method finds the sum of two values that are passed to it.
The keyword "int" that we used in the header is known as the return type of the method, becuse we declared that this method returns an int by using this statement that means that we MUST return an int value. The way we do this is by using the return keyword. What the return keyword does is when the method ends whatever comes after the return keyword is returned to the place in the program it was called. So in this example the return keyword returns the value of 2 + 2 to the print statement in the main method. This causes the value of 4 to be printed to the console.
Code Challenge
I have prepared a 2 part coding challenge for you to complete so that you can work with methods a little and get your hands dirty in some code.
I will provide a solution for both parts of the challenge as they build ontop of each other, so if you are stuggling to get the first part maybe you can use my solution to get the second part.
Part 1
Goal: Modify the addingMachine program so that it takes 2 doubles as parameters and it returns a double value.
Use the addingMachine code below as a starting point
public class Method {
public static void main(String[] args)
{
System.out.println(addingMachine(2, 2));
}
public static int addingMachine(int num1, int num2)
{
return num1 + num2;
}
}
Below is the solution to this part, the output can be seen in the image.
Solution part 1
public class Method {
public static void main(String[] args)
{
System.out.println(addingMachine(2, 2));
}
public static double addingMachine(double num1, double num2)
{
return num1 + num2;
}
}
Part2
Goal: change the method so that it multiplies the 2 numbers together instead of adding them(change the name to reflect this). Also change the arguments that are passed when the method is called.
Use the solution from above or your own solution to carry out this task.
Solution for part 2 can be found below.
Part 2 Solution
public class Method {
public static void main(String[] args)
{
System.out.println(multiplyingMachine(9, 9));
}
public static double multiplyingMachine(double num1, double num2)
{
return num1 * num2;
}
}
Extra reading
Unfortunately, I could not cover any more of the topic of methods without this post becoming too large and unwieldy. There is definitely more to cover on methods and it is likely that I will add another post at some point in the future but if you require any more reading on methods here are some source which can help you.
Java official Oracle tutorial
https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Conclusion
In this lesson we looked at the basics of creating an calling methods, this was quite a long lesson and we have covered alot of new information. To digest this information fully i suggest you play around with methods using all of the programming techniques that we have covered so far to see what you can create. In my next lesson i will be covering arrays. After the arrays lesson i will be moving on to some in depth analysis of simple programs where we can look at the concepts i have covered so far and see them in action to gain a better understanding.
If there is anything in this lesson that confuses you or there is anything programming related that you need help with then please comment below and I will try my best to help you.
As always if there are any improvements you think I can make to this post then please leave a comment and I will consider adding it.
Thank you for reading and I hope that someone will get some use out of these tutorials.
Message to readers
Thanks for taking the time to read my post, if you are interested in Science, Technology or Computer Science then check out my blog, content is a little sparse at the moment but I am making an effort to provide good quality original content to the Steemit community.
Sir I am very thank full to you for ur post they are really awesome , now i am also able to write my own codes . There is a request please provide some more videos with example . Sir u have done a outstanding job.
Hi, I'm glad you are getting some use out of my lessons. It makes it worthwhile hearing that people are learning from them. I do have a video course in the works but just looking at my options for releasing it on certain platforms
Great post, thanks @robertlyon
Thanks, you are welcome :)
Despite that fact that I dislike Java (its a long story); I find your lessons to be fairly comprehensive.
I've resteem and up voted (though unfortunately, i don't have much steem power.)
Thanks, I used to dislike Java as well but when I was forced to learn it at University I began to like the language and now use it more than I use C++ which was the first language I learned.
Thanks for the resteem/upvote. I did the same for your last post :)
Thank you @robertlyon
You are welcome :)
I dont know much about programing but I can learn from you.
Of course, if you have any questions about programming then just leave a comment and i'll get back to you
Thanks man you are very helpful. And sure I will do.
This post has received a 7.57 % upvote from @buildawhale thanks to: @robertlyon. Send at least 1 SBD to @buildawhale with a post link in the memo field for a portion of the next vote.
To support our daily curation initiative, please vote on my owner, @themarkymark, as a Steem Witness
resteemed