Last Updated:

Java Methods: How to call method in java

Java Methods

We know that a program or code is a set of instructions given to a computer. These instructions begin with some action and are therefore also called executable instructions. In Java, programs (executable instructions) are defined using methods or functions. A method is defined as a sequence of some declaration and execution statements. These statements are collected together to perform a specific task.

This article helps you learn how to declare, define, and call a Java method in classes with syntax and examples. Let's start by discussing methods or functions in Java. But first, shouldn't we know why we use or need methods in Java? So let's start with the need to use methods in a Java program.

Why Java Methods?

There are three reasons why we use Java methods they are as follows:

 

To cope with the complexity:

 

When programs become more and more complex, that is, when they increase in size, they become chaotic to process. One of the most powerful methods of reducing this complexity is "Divide and Conquer," which is to take a complex task and divide it into smaller and easier to understand tasks. In Java, we perform this technique using methods.

Hide low-level details:

Another significant application of the methods is the creation of "blackboxes". At the method usage level, we don't have to worry about how the method's task is executed. In fact, we view the method as a black box because we accept the result without caring about its details.

Code reuse:

Once the task is packaged into a method, that method is available anywhere in the program. The method can be reused, meaning we can call it multiple times in the program as well as from other programs.

Once we've learned about the need for functions, let's learn how to write/define methods in Java.

Methods in Java

In Java, a function or method must be defined before it can be used anywhere in the program. The general form of the function/method is given below:

[open-descriptor] [modifier] typereturn function name (parameter list)
{
function/method body;

}

We will discuss each of these elements in detail:

Access Specifier

The access specifier is used to determine the type of access to a method. It can be either public, protected, private, or by default. You do not have to use an access specifier when defining a method. Dive a little deeper into the Access Specifier in Java to learn its types in detail.

Modifier

It can be static, final, synchronized, transient, or changeable. A static method means that it is called through an instance or object of a class, but rather through the class itself. The final method means that the functionality defined within that method can never be changed. The use of a modifier is optional.

Return Type

It defines the type of value that the return statement of the function returns. This can be any valid Java data type. If no value is returned, we use the return type as void.

Function Name

The function name must be a valid Java identifier. The naming conventions commonly used for method names are as follows:

  • It should make sense.
  • It should begin with a lowercase letter. For names that have multiple names, we use the camelCase naming convention.

For example:

printReportCardgetMarks

The name of the method should usually begin with a verb followed by one or more nouns.

For example:

ReadDatafindFile
calculateInterestAmount

Parameter list

A parameter list is a comma-separated list of function variables called arguments or parameters. The function can be without any parameters, in which case the list of parameters is empty.

Body of the method

The body of the Java method must be enclosed in curly braces{}. The entire code of the method is written in its body in parentheses. All operations and tasks are performed inside a Java method. Here are some examples of features:

public static intMaxNumber( int a, int b)
{
//method
body }
voidprintStars()
{
System.out.println( " * * * * " );

}

A code snippet for writing a method that returns at least two numbers:

public static intminFunction(int num1, int num2)
{
int min;
if (n1 > n2)
min = n2;
more
min = n1;
return mines;

}

Function prototype and signature

The first line of the function definition is the prototype of the function. A function prototype provides the compiler with a description of the function by providing information such as the number and type of parameters and the type of the function's return value. Prototypes of the above functions are:

publicstaticintMaxNumber( int a, int b)
voidprintStars()
public static intminFunction(int num1, int num2)

Function signature mainly refers to the number and types of arguments. This is part of the prototype function. The function signatures of the above functions are:

( int a, int b)
(int num1, int num2)

Java methods live in classes

Methods live within classes. To exist in a Java program, a method must exist inside a class. A Java program can have many classes, and each class can have multiple methods. And one class in each program contains a main() method. The main() method is crucial because it tells the program where to start. It is a general rule to have one main() method within only one class.

Calling a Method/Function in Java

 

To access the method or use it, we need to call it. A function is called (or called, or executed) by specifying a function name followed by parameters enclosed in parentheses. When a program calls any method, control of the program automatically goes to the function, the operators in the body of the function are executed, and then the control returns to the calling code again in any of 3 situations:

  • It completes all statements in the method.
  • It reaches the return method operator.
  • The method throws an exception.

Code to illustrate declaring and accessing methods:

packagecom.techvidvan.methods;
public class MethodDemo
{
//A program for finding a cube of a number using method/function
//Defining the function
public static double getCube(double num)
{
double result = num * num * num;
returnresult;
}
public static void main(String args[])
{
double number= 7.5, cube =0;
// instantiating the MethodDemo
MethodDemodemo class = new MethodDemo();
// calling the getCube method using the instance created in the previous step
cube = demo.getCube(number); //Control is passed to
the function definition System.out.println ("cube" +number + "makes:" +cube);

}
}

Exit:

Cube 7.5 equal: 421.875

Overloading a Method in Java

When a class has two or more methods with the same name but different parameters, this is called a method overload. Java allows a function to have the same name if it can distinguish them by the number and type of arguments. For example, the following features are different in Java:

floatdivide(int a, int b){...}
float divide( float x, float y){...}
float divide (float a, int b) {...}

That is, the divide () function, which takes two int arguments, is different from divide (), which takes two float arguments, and from divide (), which takes both int and float arguments. This is called function overloading.

Take the example discussed earlier to find the minimum numbers of integer types. Suppose we want to find the minimum number of double types. Then we can use the concept of method overload. We'll create two or more methods with the same name but different parameters. Code to illustrate method/function overload:

packagecom.techvidvan.methods;
public class MethodOverloading
{
public static void main(String[] args)
{
int intVar1 = 15;
int intVar2 = 7;
double doubleVar1 = 14,5;
double doubleVar2 = 18,3;
int result1 = minFunction(intVar1, intVar2);
// same function name with different
parameters double result2 = minFunction(doubleVar1, doubleVar2);
System.out.println("Minimum Integer Type=" + result1);
System.out.println("Minimum value of double types =" + result2);
}
// for integer
public static intminFunction(int n1, int n2)
{
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double minfunction(double n1, double n2)
{
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;

}
}

Exit:

Minimum Value of Integer Types = 7
Minimum Value of Double Types = 14.5

Note: Overloading functions not only implements polymorphism, but also reduces the number of comparisons in the program and thereby speeds up its work.

Conclusion

We can perform any task or operation using methods. The techniques are useful when reusing code and reducing the complexity of programs. As we come to the end of this article, we learned how to declare, define, and call accessors in Java, as well as how many ways we can pass arguments to a Java method. We also introduced the concept of method overload. This information will surely help you to understand the methods in Java very easily and correctly.

Thank you for reading our article. If you have any questions or suggestions related to Java methods, please write comments.