A method is a set of statements that perform aparticular task and return the result/outcome to the caller. A method can also perform some specific task without returning anything to the caller. Methods enable us to reuse the code without the code being retyped. In Java language, every method must be part of some class.
Methods are time savers and assist us to reuse the code without the code being retyped.
Method signature: The signature includes the method name and parameter list (no. of parameters, type of the parameters and order of the parameters). Return type and exceptions are not considered to be part of the signature.
Method naming convention: A method name is typically a single word that should be a low-case or multi-word verb, starting with a lower-case verb followed by an adjective, noun, etc. The first letter of every word should be capitalized after the first word. For example, findSum,getMax, setY and getY.
Generally speaking,a method has a unique name within the class in which it is defined, but sometimes a method may have the same name as another method name within the same class as Java allows method overloading.
Defined method needs to be called by other methods to use its functionality.
A method returns to the code that invoked it when:
Parameters in java methods:
All primitive data types such as long, char, short, etc are passed by value; however, all non-primitives such as List/String/Objects are always passed by references or copy of references.
Recursion
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithms, certain problems can be solved quite easily.
returntypemethodname(){
//code to be executed
methodname();//calling same method
}
Factorial Example:
public class Recursion { static int factorial(int n){ if (n == 1) return 1; else return(n * factorial(n-1)); } public static void main(String[] args) { System.out.println("Factorial of 8 is: "+factorial(8)); } }
Keep sharing blogs like this one; they are quite good. You have given everyone in this blog access to a wealth of information.
Thank you for your valuable information.
Thank you for this wonderful article!
This article was really helpful to me, thank you!
super article!
Leave a Reply
Your email address will not be published. Required fields are marked *