Learning the Basics: Methods in Java
Learn everything you need to know about methods in Java.
Join the DZone community and get the full member experience.
Join For FreeIf you’ve used Java at all, chances are you’ve already used a method. Look no further than the public static void main(String[] args) at the beginning of every Java program.
Yes, that is actually a method.
You may also like: Four Techniques for Writing Better Java
Methods are sections of code that can be run on-demand by other sections of code. Methods help to save time when programming, improve the readability of your code, and can even allow another programmer to interact and use code you have written from their own code.
Methods can take data as input and return some data as an output. You may know them as “functions” in other programming languages.
Declaring a Method in Java
To declare a method in your class, you will have to type something like the following:
public void testMethod(int x) {
}
Make sure you are placing the method within the braces for the class that you want to contain it. In Java, unlike some other languages, methods cannot exist outside of a class.
Let’s walk through the declaration itself:
Public
refers to the method’s access modifier. Public
means that any code that has an instance of this class (or code within the class itself) can access this method.
If you want this method to only be accessible to its own class, then you would replace this with private
.
If you want this method to be accessible to this class, as well as any classes that “inherits” from it, then you would replace this with “protected.”
With no access modifier, the method will be accessible to anything within the package that contains this class.
“void
” refers to the method’s return type. The return type is the type in which this method will return.
In this case, the method will not return anything. However, if you want your method to return an int, for example, you would change this to “int” and so on and so forth. This may be any type, whether it is primitive or an object.
“int x
” refers to the method’s parameters. This is the list of inputs that your method will take. You can have any number of parameters as long as they are separated by a comma like the following:
xxxxxxxxxx
testMethod(int x, double y, float z);
These can be named whatever you like.
Defining a Method in Java
Let’s look at the following code:
xxxxxxxxxx
class TestClass {
int number = 10;
double number2 = 45.0;
public void testMethod(int x, double y) {
int localVar = x * 2;
this.number += localVar;
this.number2 = y;
}
}
It can be a bit confusing at first to know exactly what this code does. Let’s walk through the area inside the braces of our simple “testMethod
” to figure it out. We already know what the declaration does, but how does everything inside work?
On the first line, we are declaring a new local variable called “localVar
” and set it equal to the value of x multiplied by two.
This is of course very simple code that you might already be familiar with, but it should be noted that this variable “localVar
” only exists within our method.
Its value will be lost after the method’s code is run completely and is not accessible from anywhere else.
However, what if we want to method some of our class’ data members?
To do this, we use the “this
” name. The “this
” keyword refers to the method’s own instance.
We can use “this” to modify data members for the particular instance of TestClass
that testMethod
was called for.
Static Methods in Java
What if we want to have methods that don’t require an instance of some object, for example, to be used in our Main class?
To do this, you will want to add the keyword “static
” to your method declaration, like so:
xxxxxxxxxx
public static void testMethod(int x, double y) {}
This will allow you to call the method from any other static methods, but you will not be able to access any non-static data members or methods of the method’s class.
This means that “this
” is not available within the context of a static method.
Return Values in Java Methods
I mentioned earlier that functions can “return” data as an output.
This is very simple.
To do so, make sure that the return type is set to the type of the value you want to return, then type “return” in front of the value you want your method to return.
Note that after your method returns, it effectively will exit, and no more code will be run — even if you have written some code below the “return” statement.
Here is a simple example using everything we have learned so far:
xxxxxxxxxx
public static int doubleNum(int num) {
return num * 2;
}
Here, we take some input as “num
” and return the value of “num
” multiplied by two.
Your method can have any number of lines and may return any type as long as you have set the “return type” in the declaration to reflect this type.
Calling a Method in Java
You might be asking; how does one actually use a method?
Chances are, you’ve likely also already called or used methods before.
To use our “doubleNum
” method from above, see the following code:
xxxxxxxxxx
int result = doubleNum(10);
If our method had multiple parameters, you would just separate your inputs (known as arguments when inside the function call) with commas.
If you want to call a “void
” function, then you do not need to set it to any value. For our non-static method, you would have some code that looks like the following:
xxxxxxxxxx
TestClass tc = new TestClass();
tc.testMethod(22, 9.33);
Conclusion
You now know how to use methods in Java!
This is by no means an exhaustive overview of all the things you can do with methods, but it should be more than enough to get you started with applying the things you have learned here to your application, or just using them to play around to discover things you previously thought were impossible.
Good luck!
This article was originally published on AOProgrammer.
Further Reading
Four Techniques for Writing Better Java
Published at DZone with permission of An Eng. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Postgres JSON Functions With Hibernate 5
-
Java String Templates Today
-
What Is Retesting?
-
Beginner Intro to Real-Time Debugging for Mobile Apps: Tools and Techniques
Comments