For those who would know, Java methods work almost identically to C++ functions, minus a bit of gory detail that I will spare here. Don't worry if you don't know what I'm talking about. As we'll be going over the basics of what they are.
In a lot of high level programming languages, there exists the concept of the subroutine. A subroutine is just a fancy name for a piece of code that can be used to do something over and over again. Usually this code exists outside of where the rest of the code is being written. Java calls these subroutines methods, and we're going to look at how to write basic Java methods that we can use with our programs that we create inside of the main method.
Do you remember our very first program when we created:
This is not a Java method, but this is a call to a method. More on that in a bit.
I keep mentioning the main method. Yes, main is a Java method. Let's see what main looks like again:
This is how you create Java methods. Main just happens to be a method that your main program needs in order to run. Let's break it down into components to see what everything stands for.
public static are just special keywords that Java uses to determine the type of method. They must always be in all lower case letters. I am not going to explain what these keywords mean in this tutorial, but please note that all methods we will be creating for these examples will have the words public static in front of them.
Void is called the return type of the method. A void return type means that the method does not return anything. What does it mean to return something? I'll explain that in a moment. For now I think the best example of this would be with the Scanner we've used in the past. Remember Scanner? And particularly remember this line of code?
nextLine() is a method. This method returns a String. We did not code Scanner so I cannot show you the code for it, but basically the reason we can store whatever we get from nextLine() into a String variable is because the method gives us back, or returns a String variable to work with.
The program sees that line, then realizes it has to go into the code for Scanner. Specifically, it needs to go to the nextLine() method that was written inside the Scanner class. When it is done, that method returns a String, so that means when the program comes back from the Scanner class it brings a String with it. In this case, it brings back the String that the user typed.
Lastly, main has String args inside parenthesis. In Java, variables that you need to give to the method in order to work go in there as a comma separated list. These variables are called parameters. Each parameter is added by giving the type and then a name for that variable that you will use in that method only. Main HAS to have the String args parameter in order for programs to work, so we don't touch it. However, our own methods could have no parameters (nextLine() has no parameters) or many parameters, depending on what we need.
The best way to figure out the way Java methods work is to see one in action. For this example, we're going to create a whole new Java class, so go ahead and do so. I'm going to call mine MainExample. You can call yours as you please. Your code, when you're ready to begin, should look like this:
Now let's have the program output something. Add this line of code into the main method:
This is all stuff you have done before or should have done before. There's nothing new yet.
Now we're going to introduce a new method. To do this, we're going to have to write code outside of the main method. You still need to write your code inside of the MethodExample class curly brackets, though. Add this code under the main method (outside of the main method closing bracket):
We've now created a new method called sayHello(). You'll notice that we have the same prefixes public and static in the front, and we've made the return type of the method void. This means the method will not return anything back. Last, we have no parameters because we wont need any for the operations it will perform. Let's have our method do something. Let's make it print out Hello world!
Add this line inside of your new method:
Your program should now look like this:
The last thing we need to do is to use our new method. You can do that by adding this line of code under where you print out "Method Example":
That line of code will make a method call and execute any code inside of that method. Because it returns nothing, we're not setting a variable equal to it. Go ahead and run the code to see what it does.
You should have seen both lines of text displayed. If you did not, make sure you don't have any errors and that you didn't miss a step.
As you can see methods have the ability to make your code a lot easier to read and shorter by putting a lot of lines of code that you may use over and over again over in a separate area of the code. I can now use sayHello() whereever I want to make my code print out Hello world! You can of course make the method perform more complicated tasks, such as looping through values.
Before we tackle a slightly more complicated programming task, we need to go over one last detail, the return type. Remember how I said that a method might return some data depending on the return type? Consider this method:
This method returns an integer variable. A method can return one and only one variable, and this time it happens to be an int. A method with a return type must have a return statement at the very end of the method. There can be more placed throughout the method, but in generally one needs to exist at the very bottom of the method. In this case, we are returning num, so this method will return the integer value 5. What can we do with that value? Lots of things. Here's an example of storing the returned value:
Do not be confused by me using the same variable twice. This num is different from the num used in the method. A variable created inside of a Java method only exist inside of that method. They do not exist anywhere else. Here the num is storing the value that the method five() is returning. So now this other num variable will be equal to 5.
In this coding exercise we will use Java methods to have the computer output count from 1 to 5, and we will make it do this 5 times. We're also going to make sure to use a method in order to do this, but keep in mind that you don't necessarily need a method in order to accomplish this task.
Create a new Java class and call it FiveCounter. We're going to create our new method first, and it will take care of counting from 1 to 5. Call this new method counter(), and make its return type void.
Your code should look like this at this point:
Now let's add the code inside our new method to do the counting. Remember how to write a loop? That will be very useful for creating code that counts from 1 to 5, so go review it if you must.
Add a for loop inside your counter() method that goes from 1 to 5. Inside the for loop make sure to print out the counter variable. Your code should look similar to this:
In this case we're printing on one line at a time, but you can use System.out.print(x + " "); if you want to print the numbers out on the same line.
There, that part of the code is done. Now to tie this method back into the main method. Remember in main we want to be able to count from 1 to 5, but 5 times. Looks like we'll need another loop doesn't it?
Add this code to your main method:
(or you can just use the same conditions for your for loop as in your new method, it doesn't matter.)
Inside the for loop you just made add this line of code so we can use our new method:
Also add a System.out.println(); right after that line of code so that the outputs are spaced out a bit. Okay, go ahead and run your program, and you should see that the computer has counted from 1 to 5, 5 times. The new method was executed 5 times because of the main method's for loop, and the numbers 1 to 5 were counted because of the for loop inside of the counter() method.
That's all there is for this basic introduction of Java methods! I hope you can learn to apply methods to as many parts of your code as possible. For those creating big programs, this should help a lot in making your code smaller and easier to read. Remember there are still many, many details being left out, but this hopefully should let you get started into using Java methods.
If you're having trouble with this Java methods tutorial, please use the contact form below to ask questions. I will respond as soon as possible. This is the hardest beginner tutorial, and this is one of the hardest part of Java to initially grasp. It's why I made this only an introduction and not a full blown tutorial on methods. With your questions I am better able to enhance this tutorial so it's even easier to understand.
This concludes the Java beginner tutorials! You now have a basic knowledge of programming and Java syntax, and now you may begin writing your own programs if you haven't already done so. I highly recommend sitting down and writing a few programs to get a better feel for the language. I hope you've learned plenty with these tutorials and hope to see you continue on your Java learning adventure!
If you have any questions, comments, or concerns, feel free to contact us.
Leave Intro To Java Methods and return to Beginner Java Tutorials