Java User Defined Methods

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:

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:

 

 

 

After that you have defined a user defined method, you can call it in your program using the following syntax:

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

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

Java User Defined Methods
Java User Defined Methods

 

 

Learn More

Leave a Comment