Signup/Sign In

How to Call a Method in Java

In this tutorial, we will learn how to call a method in Java. Methods in java are a group of a specific task that works on define once call multiple times. These methods can be:

  • Inbuilt Methods
  • User-Defined Methods

enlightened To call static methods we do not need to create an object it can be directly called by using the method name.

How to call an inbuilt method in Java

In this example, Math.sqrt() is an inbuilt method that takes a number as a parameter and returns its square root. Here we pass the number and it will return the square root of that number. We assigned this calling to a variable ans because when the method will return a number there should be a variable to accept that value.

public class StudyTonight 
{
	public static void main(String[] args)
	{
		double num=16;
		double ans = Math.sqrt(num);
		System.out.println("Square Root of "+num+" = "+ans);
	}
}


Square Root of 16.0 = 4.0

How to call user-defined methods in Java

In the given code, we invoked two methods Show() which is a static method so there is no need for creating an object. On the other hand, Hello() is a user-defined non-static method and to invoke such a method object must be created.

public class StudyTonight 
{
	public void Hello()
	{
		System.out.println("Hello");
	}

	public static void Show()
	{
		System.out.println("Show is Called");
	}
	public static void main(String[] args)
	{
		//calling static method
		Show();
		//calling method of other class
		StudyTonight obj = new StudyTonight();
		obj.Hello();
	}
}


Show is Called
Hello

Conclusion:

Java methods can be user-defined or inbuilt both methods are the same, solitary only difference is programmers explicitly define user-defined methods for custom logic. Both methods we call in the same way. While calling these methods we need to take care of parameters and return value.



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.