How to Create Methods in Java
FOLLOW US
How to Create Methods in Java
BY JEROME DAVIDSONPUBLISHED JUL 11, 2021
Knowing how to create methods in Java is a great way to simplify workflows. This article walks you though the process.
Methods are the behavior of objects in object-oriented programming. They define what actions you can take on a given object.
Methods are similar to functions in structured programming. The difference (which is their advantage) is that methods allow for code reuse & program modularity.
In Java, you can either have library methods or user-defined methods. Library methods come with your Java installation. Follow through this article to see how to create user-defined methods.
Declaring a Method
To use a method, you must have declared it. Use the syntax below to do so:
return_type methodName( param1, param2, paramN){// statements}
In its simplest form, a method takes on the above format.
The return_type describes the data type which the method is expected to return after execution. This value can take on a data type such as int, String, or double and more.
There's also a special type called void that this field can take. Using void means that you don't want your method to return anything after execution.
Use the keyword return in your method block, so as to indicate the value you will be returning:
int deposit (int value){// statementsreturn balance;}
You will get a compilation error if you leave out what you are returning in your method body and yet your method header shows that you expect to return something.
The method body is the part of the method which begins from the left brace, { to the right brace, }. The method header is the part of your method declaration which excludes the braces, {}.
return_type methodName( param1, param2, paramN) // method header
methodName is an identifier used to name a method. By convention, it uses lower camelCase. That is, the first word is lowercase, and if it's a two-part word, then the first letter of the second word is also capitalized.
It is also important to note that you can not use any of the reserved Java words as a method name.
The round brackets of the method header are used to define the parameter list. A parameter list defines a list of parameters separated by commas. A parameter is a two-part value consisting of a data type followed by a variable name.
It is also possible not to include any parameters in your parameter list. In this case, the compiler will just run the method block with no parameter expectation.
int balance (){//statementsreturn amount;}
A method can also have two other fields, preceding the return_type in the method header. See the example below:
public static void main(){}
The keyword public is a visibility modifier and you can apply it to any method you define so as to limit its accessibility. Public means that the method can be accessed by all classes in all packages.
There are also other visibility modifiers like protected, private, and default. An in-depth discussion of visibility modifiers is given in the related link:
RELATED: The Different Java Access Modifiers Explained
The keyword static indicates that a method has a class scope. This means that the method is not an instance method and is therefore run whenever the program is loaded into memory without the need for instantiation. The importance of having a static method is to enable the compiler to know which method to start with during execution.
Generally, your program will have one static method (called main()) from which you can call other methods.
Calling a Method
In order for your declared method to perform an action on an object, it needs to be "called."
To call a method, use the syntax:
ObjectName.methodName(arguments)
An argument is a value that you pass on in the field where you declared a parameter. Ensure that the argument type matches that declared in the method header. Otherwise, you will get a compilation error.
RELATED: What Is A Recursive Function, And How Do You Create One In Java?
Below is a fully working sample code that shows how to apply what you've learned. It uses methods to apply an interest rate to a deposited amount and to also display a bank message.
public class Account{double deposit(double amount){amount = amount*1.05; // apply 5% interest rate to amountreturn amount;}void getMessage(){System.out.println("Thank you for banking with us!");}public static void main(String[] args){Account myAccount = new Account();double newBalance = myAccount.deposit(500); // method callSystem.out.println("Your new balance in 4 months will be "+ newBalance);myAccount.getMessage(); // method call}}
Now You Know How to Create Methods in Java
Knowing how to create methods in Java is essential for anyone looking to become more serious about programming. And now you know how to do so, you'll save plenty of time while working.
Once you've mastered this skill, why not take a look at other Java-related tips and tricks?
What Is a Constructor in Java and How Do You Use It?
RELATED TOPICS
ABOUT THE AUTHORJerome Davidson (22 Articles Published)
Jerome is a Staff Writer at MakeUseOf. He covers articles on Programming and Linux. He's also a crypto enthusiast and is always keeps tabs on the crypto industry.
SUBSCRIBE TO OUR NEWSLETTER
Join our newsletter for tech tips, reviews, free ebooks, and exclusive deals!
CLICK HERE TO SUBSCRIBE
ON THE WIRE