Home >>Java Tutorial >Java methods

Java methods

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.

Define a Method

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:

  • The name of the method in this example is myMethod()
  • Static in this example points that the method generally belongs to the MyClass class and is not an object of the MyClass class. In further chapters of these tutorial users will learn more about objects and process to access methods through the objects.
  • 'Void' in this example simply means that this method does not possess a return value.

Call a Method

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();
  }
}
Output :This is my first method in Java

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();
  }
}
Output :
This is my first method in Java
This is my first method in Java
This is my first method in Java

Popular Tutorials