Articles

What are Methods in Java

Share

A method is a set of statements that collectively perform a specific task and can be invoked any number of times by using its name. In other words, these lines of code are grouped together to form a method and this defined method can be used any number of time. It reduces the length of the code and improves readability.

Syntax:

return_type method (parameter/ Argument)
{
// set of statements or body
}

Explanation:

return_type: It means what type of value would a method be returned.  It can be Boolean, integer, floating, char and even objects. If the method name is followed by void, then it would return nothing.

method_name: It is basically an identifier which represents the name of the method.

parameter or argument: These are nothing but a set of inputs where each input is separated by a comma and defined with a datatype preceded with the identifier.

Java program to define a method

class square{
int area;
int area(int side){
area = side*side;
return area;
}
void display(int area)
{
System.out.println(" Area of the Square = "+area);
}
}
public class Box {

public static void main(String[] args) {
square obj = new square();
int output;
output= obj.area(5);
obj.display(output);
}

}

Output:

This post was last modified on September 14, 2019

Sandeep Verma

Published by
Sandeep Verma
Tags: defination java methods