In this Java article we want to learn about Java User Defined Methods, in Java methods are the building blocks of any program. they are a set of instructions that can be reused over and over again. Java provides both built-in methods and user defined methods. in this article we want to explore user-defined methods in Java.
What are User-Defined Methods ?
User defined methods are methods that are created by the user. they are not builtin to Java, but are instead defined by the programmer to solve specific problems. these methods can be used in a program just like builtin methods.
The syntax for creating a user defined method is as follows:
1 2 3 |
access_modifier return_type method_name (parameter_list) { // code block } |
Here’s what each of these components means:
- access_modifier: this specifies the access level of the method. it can be public, private or protected.
- return_type: this specifies the data type that method will return. it can be any valid Java data type, or void if the method does not return anything.
- method_name: this is the name of the method. it must be a valid Java identifier.
- parameter_list: this is a list of parameters that are passed to the method. it can be empty if the method does not require any parameters.
- code block: this is the set of instructions that are executed when the method is called.
This is an example of user defined method that takes two integers as parameters and returns their sum:
1 2 3 |
public int sum(int a, int b) { return a + b; } |
After that you have defined a user defined method, you can call it in your program using the following syntax:
1 |
return_type variable_name = method_name(argument_list); |
These are what each of these components means:
- return_type: this is the data type that the method returns.
- variable_name: this is the name of the variable that will hold the return value of the method.
- method_name: this is the name of the method you want to call.
- argument_list: this is a list of arguments that are passed to the method.
This is the complete code for java user defined method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.Arrays; public class Example { //user defined method that takes two integers and returns their sum public static int sum(int a, int b) { return a + b; } // main method that calls the user defined method public static void main(String[] args) { // Call the sum method and store the result in a variable int result = sum(6, 8); // Print the result to the console System.out.println("The sum of 2 and 3 is: " + result); } } |
In the above example, we have defined user defined method called sum that takes two integers as parameters and returns their sum. after that we call this method in the main method of our program, and we pass two integers as arguments. the result of the method call is stored in a variable called result, and at the end we print the result.
This will be the result