Methods
A Java method is a collection of statements that are combined together to
perform an action. For example when
System.out.println() method is called, the system actually executes several
statements in order to display a message on the console.
·
A method is a group of code, which only
runs when it is called.
·
You can pass data, known as
parameters, into the method.
·
Methods are used to perform certain operations, and they are known as functions.
·
Why use methods? To reuse
code: define the code once, and use it many times.
Now we will learn how to create our own methods with or without return values,
invoke a method with or without parameters, and apply method abstraction in the
program design.
Method definition consists of a method header and a method body. The same is
shown in the following syntax −
Syntax
modifier returnType method-name (Parameter List) {
// method body
}
-
modifier − It defines the access
type of the method and it is optional to use.
-
returnType − Method may return a
value.
-
method-name − This is the method name. The method
signature consists of the method name and the parameter list.
-
Parameter List − The list of
parameters, it is the type, order, and number of parameters of a method. These
are optional, method may contain zero parameters.
-
method body − The method body
defines what the method does with the statements.
Creating Method
Considering the following example to explain the syntax of a method −
Syntax
public static int methodName(float x, float y) {
// method body
}
Here,
|