Methods in Java

Methods in Java

In this article, I am going to discuss Methods in Java with Examples. Please read our previous article, where we discussed Branching Statements in Java with examples. As part of this article, you will understand what are Methods and its type and how to create and call methods in java with examples.

What are Methods in Java?

In the Java programming language, a method is a section of the program that contains a set of instructions or code. A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method’s name. Think of a method as a subprogram that acts on data and often returns a value. Each method has its own name.

A method is a collection of statements that perform some specific task and return the result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code. Methods are basically referred to as time savers, which means that they allow you to have the repetition of sections of code without having to retype the code.

Types of Methods in Java:

Basically, there are two types of methods in Java:

  1. Standard Library Methods or build-in functions
  2. User-Defined Methods

Types of Methods in Java

Standard Library Methods in Java:

The Standard library methods are built-in methods in Java that are readily available for use. These standard libraries come along with the Java Class Library that is present in a Java archive (*.jar) file with JVM and JRE. Some of the examples of Standard Library Methods areas follows:

  • print(): This method comes under java.io.PrintSteam which helps in printing the string that is written within the quotation.
  • dsqrt(): This is a method of Math class that returns the square root of that specific number.
User-Defined Methods:

User-defined methods are created by you, the programmer. These method take-on names that you assign to them and perform tasks that you create. A method must be declared within a specific class. It is defined with the name of the method, followed by parentheses “()”.

How to Create a User-Defined Method in Java?

Method definition consists of a method header and a method body. The same is shown in the following syntax :

How to Create a User-Defined Method in Java?

Here,

  1. Modifier: It defines the type of access to the method. It is optional to use.
  2. Return type: It defines the return type of value of the method.
  3. MethodName: It defines the name of the method. The method signature consists of the method name and parameter list.
  4. Parameter List: It defines the list of parameters. It is the type, order, and the number of parameters of the methods. The method may contain zero parameters also.
  5. Method Body: The body of the method defines the code or list of statements you need to be executed. It is enclosed within braces.
Example :

Methods in Java

In the above example,

public: modifier
int: return type
max: Method Name
(int x, int y): Parameters list

What is the method signature?

In the Java programming language, a method signature is the method name and the number, type, and order of its parameters. Return types and thrown exceptions are not considered to be a part of the method signature.

Method Name:

A method name is typically a single word that should be a verb in lowercase or multi-word, that begins with a verb in lowercase followed by an adjective, noun….. After the first word, the first letter of each word should be capitalized. For example, calculateSum.

Method Parameter:

These are values passed to a method. We can pass any number of arguments to a method but just separate them with a comma. Parameters are specified after the method name in a class, inside parentheses. Data can be passed to functions as a parameter. Actually, parameters act as variables inside the method.

Java methods have parameters or data that are inputted or passed into the method. The method uses these parameter values to do the necessary data manipulation and processing. The method then usually returns the final value after all the necessary data processing is successfully performed.

Example :

What is method signature?

How to call a method in Java?

When a method is invoked (called), a request is made to perform some action, such as setting a value, printing statements, returning an answer, etc. The code to invoke the method contains the name of the method to be executed and any needed data that the receiving method requires. The required data for a method is specified in the method’s parameter list.

When a program invokes a method, the program control gets transferred to the called method. This called method then returns control to the caller in two conditions, when −

  • The return statement is executed.
  • It reaches the method ending closing brace.
  • It throws an exception.
Sample Program for Method Invocation :
package Demo;

public class MethodCall {
  static void myMethod() {
       System.out.println("Hello World!");
         }

         public static void main(String[] args) {
       myMethod();
         }
}

Output:

How to call a method in Java?

Memory Allocation for Method Calls:

Methods calls are implemented through the stack. Whenever a method is called a stack frame is created within the stack area. Then the arguments are passed to and the local variables and value to be returned by this called method are stored in this stack frame. And when the execution of the called method is finished, the allocated stack frame would be deleted. There is a stack pointer register that tracks the top of the stack which is adjusted accordingly.

How to return a value from a method in java?

By using the parameters that are passed into the method, the method generates a new product or result. The result returned by the method is also available for use by the Java program to which this method belongs.

Sample Program of a Method Returning a Value:
package Demo;

public class ReturnValue {
   public static void main(String[] args) {
         int result;

         // call the method and store returned value
         result = square(); 
         System.out.println("Squared value of 10 is: " + result);
     }

     public static int square() {
         // return statement
         return 10 * 10;
     }
}

Output:

How to return a value from a method in java?

Method Overloading in Java:

When two or more methods within the same class share the same name with a different parameter list, it is known as Method Overloading. The overloaded method must differ in types and number of parameters. The overloaded method may have different return types. There are two ways to overload the method in java

  1. By changing the number of arguments
  2. By changing the data type
Sample Program for Method Overloading:
package Demo;

public class MethodOverloading {
   private String startMethod = "Dog";

     public void start(){
         System.out.println(startMethod + " is an Animal.");
     }

     public void start(String method){
         this.startMethod = method;
         System.out.println(startMethod + " is an Animal.");
     }
 
     public static void main(String[] arg){
     	MethodOverloading animal = new MethodOverloading();
     	animal.start();
     	animal.start("Cat"); 
     }
}

Output :

Method Overloading in Java

Method Recursion

Recursion is the calling of a method within the same method. Yes, we can call a method inside another method. It makes the code compact but complex to understand.

Sample program to Find Factorial of a number by using Method Recursion
package Demo;

import java.util.*;
class Fact{

public static int factorial( int a ) /* method */
{
  if( a == 0 || a == 1)
  {
    return 1;
  }
  else
  {
    return a*factorial(a-1);
  }
}

public static void main(String[] args)
{
  Scanner s = new Scanner(System.in);
  int n;

  System.out.print("Enter number\n");
  n = s.nextInt();

  int fact = factorial(n);

  System.out.println("Factorial of "+n+" is "+fact);
}
}

Output:

Method Recursion

Advantages of using Methods in Java:
  1. Code Reusability: We can write a method once, and use it multiple times. We do not have to rewrite the entire code each time.
  2. Readable and Easier: Methods make code more readable and easier to debug.

In the next article, I am going to discuss Java User Input and Output with examples. Here, in this article, I try to explain Methods in Java with examples and I hope you like this Methods in Java with examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *