Java Methods
A method is a block of code which is executed only when it is called. The data are passed to the function which is known as parameters. The methods are used to perform certain actions and they are known as functions. By using Methods, we are able to re-use the code which means write once and use it many times.
Create a Method
All methods in Java should be declared within a class. The method is defined with the specific name along with the parameters, which is enclosed with the parentheses (). Java itself has many pre-defined methods, one such method is System.out.println(). We can also create our own functions, to perform certain actions.
Example
public class MyClass { static void MyMethod(){ // Block of code to be executed when function has called } }
From the above example,
Call a Method
To call a Method in Java, we use a Method name to call the function which is followed by two parentheses () and a semicolon (;)
In the following example, the function myMethod() is used to print a text, when it is called.
Example
public class MethodExample { static void myMethod(){ System.out.println("Method called"); } public static void main (String args[]){ myMethod(); } }
Output
Method called
The method can be called multiple times. Hence, the method can be re-used multiple times.
Example
public class MethodExample { static void myMethod(){ System.out.println("Method called"); } public static void main (String args[]){ myMethod(); myMethod(); myMethod(); } }
Output
Method called Method called Method called
In the above example, the method is called thrice in the main function.