Ch3 User-defined Methods
What is a method in Java?
• A method is a block of code or collection of statements or a set of code
grouped together to perform a certain task or operation.
• It is used to achieve the reusability of code.
• It also provides the easy modification and readability of code, just by
adding or removing a chunk of code.
• The method is executed only when we call or invoke it.
• The most important method in Java is the main() method.
Why Functions/Methods?
• To cope with complexity
• Hiding details
• Reuse
Naming a Method
• Single-word method name: sum(), area()
• Multi-word method name: areaOfCircle(), stringComparision()
• It is also possible that a method has the same name as another method
name in the same class, it is known as method overloading.
1
Types of Methods
There are two types of methods in Java:
• Predefined Method
eg. Math.pow(), Math.sqrt()
• User-defined Method
Types of Method Parameters
• Actual parameters appears in the method call
• Formal parameters appears in the method defination
2
Method Overloading
• In Java, two or more methods can have same name but if they differ in
parameters (different number of parameters, different types of
parameters, or both).
1. Overloading by changing the number of arguments
2. By changing the datatype of parameters
3
• Pure functions does not modify the object
public static boolean after(Time t1,Time t2)
{
boolean result;
result=(t1.hour>t2.hour)?true:false;
return result;
}
• Impure functions modifies the object
public static void increment(Time t1)
{
t1.hour+=1;
}