Creating Method: Eelo University Faculty of Computer Science Class: DIT
Creating Method: Eelo University Faculty of Computer Science Class: DIT
Now you will learn how to create your own methods with or without return
values, invoke a method with or without parameters, and apply method
abstraction in the program design.
Creating Method
Considering the following example to explain the syntax of a method −
Syntax
public static int methodName(int a, int b) {
// body
}
Here,
a, b − formal parameters
Syntax
modifier returnType nameOfMethod (Parameter List) {
// method body
}
modifier − It defines the access type of the method and it is optional to use.
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.
Example
Here is the source code of the above defined method called min(). This
method takes two parameters num1 and num2 and returns the maximum
between the two −
return a + b;
return a - b;
Method Calling
For using a method, it should be called. There are two ways in which a method
is called i.e., method returns a value or returning nothing (no return value).
System.out.println("This is tutorialspoint.com!");
Example
Live Demo
Return a + b
{
Return a - b
Output
Minimum value = 6
Example
Live Demo
methodRankPoints(255.7);
System.out.println("Rank:A1");
System.out.println("Rank:A2");
}else {
System.out.println("Rank:A3");
}
}
Output
Rank:A1
Example