What are methods in Java?

Overview

In Java, a method is a collection of statements that perform some specific task and returns the result to the caller. A method can take zero or more parameters. Methods are defined within a class.

Usage of the methods

Methods perform specific tasks. For example, the println() method prints a string to the console. The calculateArea() method calculates the area of a rectangle. Methods can be called from other methods or from within the main() method.

Declare a method

To declare a method, we use the return type, followed by the method’s name, and the parameters. Here's an example:

public int calculateArea(int width, int height) {
// Statements go here.
}
Declare a method in Java

In the example above, the calculateArea() method has the int return type, which means it returns an integer value. The method takes two parameters, width and height. Both these parameters are also of the int type.

Call a method

When we call a method, we use the method's name, followed by its parameters. Here's an example:

calculateArea(10, 20);
Call a method in Java

In the example above, the calculateArea() method is called with two parameters, 10 and 20. These values are passed to the width and height parameters of the calculateArea() method.

Code

The println() method is a built-in method that prints a string to the console. To print a string, we use the println() method, followed by the string we want to print. Here's an example:

class HelloWorld {
public static void main( String args[] ) {
System.out.println( "Welcome to Educative Answers!" );
}
}

This prints the "Welcome to Educative Answers!" string to the console.

Free Resources