How to Call a Method

JavaJavaBeginner
Practice Now

Introduction

Methods in Java are a group of tasks that perform a specific action. In this lab, we will learn how to call these methods in Java. As part of this lab, you will learn how to call inbuilt and user-defined methods in Java.

Creating and calling an inbuilt method

To call an inbuilt method in Java, we can directly use the method name. In this step, we will call the Math.sqrt() method that returns the square root of a number.

  • Create a new Java file with the name CallMethod.java in the ~/project directory.

  • Add the following code in the file:

    public class CallMethod {
        public static void main(String[] args) {
            double num = 16;
            double ans = Math.sqrt(num); // calling the inbuilt method
            System.out.println("Square Root of "+num+" = "+ans); // printing the result
        }
    }
  • Save the file and close it.

  • To run the above code, open your terminal and navigate to the ~/project directory.

  • Compile the file using the javac command:

    javac CallMethod.java
  • Run the file using the java command:

    java CallMethod
  • After running the file you should see the output as follows:

    Square Root of 16.0 = 4.0

Creating and calling a user-defined method

To call a user-defined method in Java, we need to create an object of the class in which the method is defined. In this step, we will call a user-defined method hello().

  • Open the CallMethod.java file that we created in the previous step.

  • Add the following code below the main() method to define a user-defined method called hello():

    public void hello() {
        System.out.println("Hello World!");
    }
  • Modify the main() method to create an object of the CallMethod class and call the hello() method:

    public static void main(String[] args) {
        double num = 16;
        double ans = Math.sqrt(num);
        System.out.println("Square Root of "+num+" = "+ans);
        CallMethod obj = new CallMethod(); // creating object of CallMethod class
        obj.hello(); // calling user-defined method
    }
  • Save the file and close it.

  • To run the above code, open your terminal and navigate to the ~/project directory.

  • Compile the file using the javac command:

    javac CallMethod.java
  • Run the file using the java command:

    java CallMethod
  • After running the file you should see the output as follows:

    Square Root of 16.0 = 4.0
    Hello World!

Summary

In this lab, we have learned how to call both inbuilt and user-defined methods in Java. We can directly call inbuilt methods by their name, whereas to call user-defined methods, we need to create an object of the class in which the method is defined.

Other Java Tutorials you may like