3.5.1 Method
3.5.1 Method
5 METHODS
3.5.1 INTRODUCTION TO JAVA METHOD
Learning Outcomes
• At the end of this topic, you should be able to:
• Explain the meaning and the use of methods.
• Explain types of method:
i. Standard library
ii. User-defined
• Explain the general structure of A user-defined method (method name, type, parameters)
• Explain method return types based on return values.
METHODS : MEANING
• A method is a component of a
program / small program
written to perform a specific
task.
Content Description
Modifier It defines the access type of the method and it is
optional to use.(public static or private static)
Return value Method may return a value.
type
Method Name This is the method name. The method signature
consists of the method name and the parameter list.
Method task : To calculate the area of a Method task : To calculate the volume of a
circle cylinder
2. Method name {
// Method-body
3. Parameters
}
METHOD DEFINITIONS
Returntype Methodname (parameters)
1. Return Type
{
// Method-body
• Return Type is based on the type of value returned by the method
}
• From previous slide
// Method-body
2. Method name
}
• The name of the method is an identifier.
• You can give any name to a method. However, Method task : To calculate the area of a
it is more conventional to name it after the
circle
tasks it performs. Usually represents the task
performed by the method. int Area (int radius)
{
• For example: int value;
• Comparenumbers, Computeprice, value = 3.14 * radius * radius;
Calculatearea, and Findminimum. return value;
}
METHOD DEFINITIONS Returntype Methodname (parameters)
// Method-body
}
3. Parameters
• Parameters are the variables in the Method task : To calculate the area of a
method definition circle
Definition Details
CLASSNAME the program class name
OBJECTNAME the instance of the class (object for the class name),
METHODNAME the method defined in the same class,
(ARGUMENTS) the value(s) we pass to a method
EXAMPLE NON-STATIC METHOD : RETURN VALUE METHOD
public class Callingthemethod {
public static void main (String [ ] args)
{
int x = 10, area;
Callingthemethod m = new Callingthemethod( ); //declare object m
area = m.Square (x); Content Description
System.out.println(area); Object m
area = m.Square (5);
Method Name square
System.out.println(area);
area = m.Square (x + 5 % 2); Argument (x) , (5) , (x + 5 % 2);
System.out.println(area); Return type int
} Method Name square
int Square (int num) Parameters (int num)
{
return num * num;
Method call
}
} Method definition
Note: The number and data type of the parameters passed in the method call should match with the number and data type of the
parameters in the method definition
EXAMPLE NON-STATIC METHOD CALLS