A method in Java is a group of code defined with a name, so instead of repeatedly writing that same group of code everywhere , we can execute that group of code by just calling the name of the method.
This helps in reuse of the code and also it helps to organize and simplify coding.
What a method consists of ?
As shown in the above figure every method in Java consist of modifiers, then a return value type, the method name and a list of parameters that are consumed by the method.The list of parameters are the input to the method,it can be more than one parameters or none, while the return value type is the output data type the method provides us back, sometimes the method do some task but does not return anything, in this situation we use void as return type otherwise specify which type of output a method returns.The modifiers specify the visibility of this method so whether it can be accessed by everybody or only can be accessed by the containing class and whether it is static etc, so for that we use modifiers such as public, private, static etc. Then comes the method body inside two curly braces.
Example of a method in action:
1 2 3 4 5 6 7 8 | public static void printMe(String myName,int age) { System.out.println("My name is "+myName+" and age is "+age); //public and static are modifiers //void - return type //printMe - method name //myName, age - parameters } |
How a method is invoked or called in a program?
eg: printMe("Sujith",25);
Example code in action:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class Sample{ public static void main(String[] args) { printMe("Sujith",25); //Invoking or calling the method. //Sujith is the first parameter as a String. //25 is the second parameter as an integer. } public static void printMe(String myName,int age) { System.out.println("My name is "+myName+" and age is "+age); //public and static are modifiers //void - return type //printMe - method name //myName, age - parameters } } |
Now to access a method in another class with the creation of an object we use the form
ObjectName.methodName(Parameters);
Object should be initialized otherwise NullPointerException will occur.
And to access a static method we use the form
ClassName.methodName(parameters);
The values passed to the method is called arguments.
For primitive data types the method will use a copy of the arguments passed thus it will not affect the original values, while if we pass an object then making changes to the object will affect the original one passed to it.So be careful about it.
Also note variables declared inside a method will be local means it will be available inside that method only.
0 comments:
Post a Comment