Java Methods:

  • One method is a collection of certain duties and gives results to the caller.
  • Any java methods can work without any returning work.
  • Ways allow us to reuse code without having to type the code again.
  • In Java, each method should be part of some class that is different from languages ​​like C, C ++ and Python.
  • Ways to save time and help us to reuse code without typing the code.
  • The method is a set of statements that are created to perform some actions or operations when your Java code is called it by the main method.
  • The code written in the inside methods can not be executed by itself.
  • In order to execute that method code block, you must call that method within the main java methods block.

Syntax:

Understanding Method Declaration:

 

Modifier:

  • Defines access type of the method i.e. from here.

                                Types of Modifiers:

                                1. Public: Accessible in all categories in your application.

                                2. Protected: Accessible within the class in its sub-sections.

                                3. Private: Only accessible within the class in which it defined.

                                4. Default: accessible within the same class and package.

The return type:

  • The data type of the value returned by the method or void if does not return a value in method.

Method Name:

  1. The rules for field names apply to method names as well, but the convention is a little different in java methods.

Parameter list:

  • A comma-separated list of input parameters is defined, that is, before their data type, within the attached brackets. If there are no criteria, then you should use empty parentheses ().

Exception list:

  • The exceptions you expect by the method can throw, you can specify these exception’s.

Method body:

  • It is enclosed between braces. The code you need to be executed to perform your intended operations in Method.

 

Method Example:

Output: 

We can say that Test1() method is executed but Test2() method is not executed because It Is not called from main method.

 

Static or non static method:

  • The method may be static or non-static.
  • If you want to keep your method in the form of static, then you must use the static keyword with the method.
  • If you want to create non-static method, do not write static keywords with the method.

Example:

Input Parameters To Method:

  • We can pass the input parameter in any way. Need to write parameters with your data type

Example: