Methods in Java

A method is a collection of statements that perform some specific task and return result to the caller.

  • In Java, every method must be part of some class which is different from languages like C, C++ and Python.
  • Methods allow us to reuse the code without retyping the code.
  • When the method is called, the set of instructions within the method is executed.
  • A method is a group of Java statements that perform some operation on some data, and may or may not return a result.
  • Java methods are similar to what is called functions or procedures in other programming languages (e.g. Pascal or JavaScript).

Method Declaration

In Java, method declaration contains below six components.

1. Modifier:

  • public: accessible in all class in your application.
  • protected: accessible within the class in which it is defined and in its subclass(es)
  • private: accessible only within the class in which it is defined.
  • default (declared/defined without using any modifier) : accessible within same class and package within which its class is defined.

2. Return type:  The data type of the value returned by the the method or void if does not return a value.

3. Method Name:  the rules for field names apply to method names as well, but the convention is a little different.

4. Parameters: Comma separated list of the input parameters are defined, preceded with their data type, within the enclosed parenthesis. If there are no parameters, you must use empty parentheses ().

5. Exception: The exceptions you expect by the method can throw, you can specify these exception(s).

6. Method body:  it is enclosed between braces. The code you need to be executed to perform your intended operations.