Method


Method

Methods are similar to the functions that are used to perform various operations and represent behavior of an object. They are the lines of code that performs a specific function in a program. They can either return a value or not return anything. The main reason why methods are used in a program is because of it’s code reusability.

Syntax:

access_modifier return_type method_name(parameter_list)
{
//code
}

The java method is a piece of code that only executes when it is called. We can pass the data, called parameters, into a method. The methods are practised to do specific actions, and they are also called functions. This method also gives the simple modification and better readability of code by adding or removing a piece of code.

Why use methods in Java?

To reuse a piece of code: Specify the code once, and use it several times. Then, there is no need to write the code again and again.

How to Create a Method in Java

The method needs to be declared within a class. It is specified with the name of the method, accompanied by parentheses (). The Java method gives some predefined methods, like System.out.println(); however, users can also generate their methods to do specific tasks.

How to Call a Method in Java

To call a method in Java, you have to write the method's name accompanied by two parentheses () and one semicolon.

The two types of method are:

  • Predefined Method
  • User-defined Method

Example No.1:

Com.knowledge2life public class Main { static void Method() { System.out.println("Knowledge2life!"); } public static void main(String[] args) { Method(); } }

OUTPUT:

Knowledge2life!

Example No.2:

Com.knowledge2life public class Main { public static void main(String[] args) { Method1(); } static void Method1() { System.out.println("Knowledge2life"); } }

OUTPUT:

Knowledge2life