What Is Java Methods ?

Definition :

- A Java method is a collection of statements that are grouped together to perform an operation.

- A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name.

Creating a Method :

Each method has its own name. When that name is encountered in a program, the execution of the program branches to the body of that method. When the method is finished, execution returns to the area of the program code from which it was called, and the program continues on to the next line of code.

Method Syntax :

modifier returnValueType methodName(list of parameters)
{
// Method body;
}

Modifiers : The modifier, which is optional, tells the compiler how to call the method. This defines the access type of the method.

Return Type : A method may return a value. The returnValueType is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void.

Method Name : This is the actual name of the method. The method name and the parameter list together constitute the method signature.

Parameters : A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.

Method Body : The method body contains a collection of statements that define what the method does.

Example :
// Simple Method Example
public void test()
{
System.out.println("this is a simple method example");
}

This is how Methods are created in java and you can know how to access Methods using Objects from what are objects and how to create object in java . we will learn different types of methods in the later tutorials of java methods.

No comments:

Post a Comment