Home >>Java Tutorial >Java methods
Java Methods are basically a block of code that only runs or performs whenever it is called. The programmers can generally pass data into a method and that data is known as parameters.
Methods are used In order to perform certain actions, the methods are used and sometimes that are also called as functions.
The main purpose of using the methods is to reuse the code that simply elaborates to using a code for a multiple number of times after defining it for one time.
Now, we will learn the procedure of creating the methods. A method should be declared within the class as the name of the method followed by parentheses ().
There are some predefined methods that are provided by the Java language like System.out.println (). But that doesn’t bind the programmers to create their own methods in order to perform certain actions.
Here is an example that will describe you the process of creating a method inside MyClass:
public class MyClass { static void myMethod() { // code that is to be executed } }
Here is the explanation of the example that is mentioned above:
In order to call a method in the Java language, the programmers have to write the method's name that will be followed by two parentheses () and a semicolon;.
Here is an example that is depicting the use of myMethod() to print a text , whenever it is called:
public class DemoClass { static void DemoMethod() { System.out.println("This is my first method in Java"); } public static void main(String[] args) { DemoMethod(); } }
Please note that a method in Java can be called multiple times.
Here is an example of the same that is depicting that a method can be called multiple times:
public class DemoClass { static void DemoMethod() { System.out.println("This is my first Method"); } public static void main(String[] args) { DemoMethod(); DemoMethod(); DemoMethod(); } }