What are Methods in Java3 min read

In this article you will learn about Java methods. You will look at what is a method, how to create methods in a Java class, how to call a method, how to return a value from a method and more.

Method: A method is a piece of code to solve a particular task. A method is analogous to functions in C and C++. Methods are defined inside a class. The syntax for creating a method is as shown below:

The return_type specifies the type of value that will be returned by the method. The name of the method is specified by method_name. Every parameter in the parameters list follows the below syntax:

datatype parameter_name

The parameters count can be zero or more based upon your requirements. The body of the method is represented using the braces { and }. Body of the method is also known as the method definition

If a method does not return any value, its return type must be void. A method can return a single value back by using the return statement. Syntax for using return statement is as shown below:

return value;

As an example, let’s create a method which takes side of a square as parameter and prints out the area of the square. The method is shown below:

In the above method, s is a parameter and the return of the method is void as the method is not returning back any value.

Let’s create another method which returns back the perimeter of the square. The method is shown below:

In the above method, there are no parameters. The variable side is an instance variable of the class (see below). The method perimeter returns back an integer value using the return keyword. So the return type of the method is int.

A method in a class can be called by creating an object to that class and then use the dot operator followed by the method name and arguments if any. Syntax for a method call is as shown below:


Now, let’s look at the entire Java program which contains the class Sqaurealong with the above methods for computing area, perimeter and some other code:

Output for the above program is:

Area of the square is: 100
Perimeter of the square is: 40
Length of the side is: 10

A well written Java program is one which contains a set of classes that hides their fields (instance variables) from direct access and allows them to be accessed only through methods.

The values passed in a method call are known as arguments and the variables declared in the method to receive the values from the method call are known as parameters.

Take your time to comment on this article.

Leave a Comment