Method
A method is
a block of code which only runs when it called to perform certain action, and
they are also called as function
Methods are
used to achieve code modularity.
Advantages of method:
- Easy bugs fixing : these help us to identify bug easily.
- Code reusability
- Easy code modification
· Syntax for design method:
Class className
{
[access
modifier][modifier][return type] methodname (formal argument)
{
}
}
Note:
- Programmer can design and create his own methods. that method can be used by himself or others
- Programmer can use method which is all designed by other(builtin).
z
Method name:
It is an
identifier which is used to identify and call a method follow the conditions to
provide method name.
Formal argument:
The variable
declared in the method declaration
statement is called formal argument. Formal argument is required if method has
to accept any data.
Return type:
o
Specifies either the type of value return or
nothing return after the execution of method.
o
The return type can either void or specific data
type.
o
If a method returns nothing the return should be
void.
o
If the method wants to return something, return
type is data type ( it may be primitive, non-primitive data type or void)
Modifiers:
Modifiers are
the keywords which modify the behaviour of variable and methods. Example:
public, private, protect, default, static, find, abstract, synchronize
Call a Method
To call a
method in Java, write the method's name followed by two parentheses () and
a semicolon;
A method
can be call any number of times.
Example:
Class Main
{
Public Static
void main(String [] args)
{
myMethod();
myMethod();
}
Public Static
void myMethod()
{
System.out.println(“
I am here”);
}
}
Parameters and Arguments
Information
can be passed to methods as a parameter. Parameters act as variables inside the
method.
Parameters
are specified after the method name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma.
Example:
Class Main
{
Public Static
void main(String [] args)
{
myMethod(“Sanket”);
myMethod(“Shyam”);
}
Public Static
void myMethod( String name)
{
System.out.println(name);
}
}
Return Values
If you want
the method to return a value, you can use a primitive data type (such as int, char,
etc.) instead of void, and use the return keyword inside the
method:
Example:
Class Main
{
Public Static
void main(String [] args)
{
System.out.println(myMethod(5));
}
Public Static
void myMethod(int x)
{
return 5 +
x ;
}
}
Output: 10