JAVA METHODS

Methods in Java are the set of executable Statements that perform some specific actions. In other programs, methods are also known as procedures, functions, subprograms, etc. We as a programmer decide what specific actions have to be performed and what kind of objects should perform them

Table of Contents

[hide]
  • What is a Method in Java
  • Java Method Definition
  • Types of Java methods
  • Accessing a Method
  • Actual and Formal Parameters

What is a Method in Java

Method in Java is a sequence of some declarative statements or executable statements. We generally used methods for the three main reasons :

  • 1. To encourage us to tackle complex problems
  • 2. To reuse piece of code which saves a great deal of time.
  • 3. Hide low level details which would otherwise be confusing and obscure.

To Tackle Complexity

When working with a large application, our codebase becomes more and more complex. One of the most popular techniques to cope up with complexity is "divide and conquer" that's says to divide a complex task into smaller tasks. In Java, these smaller, easily understood tasks are implemented as methods.

Once the method is defined, we can use this method is our application and we need not concern ourselves with the details any longer.

To Reuse Piece Of Code

Reuse is a central concept in object-oriented programming language such as Java. The practice is sometimes called "Write once, use many". The idea is to re-use a method that already serves the purpose instead of creating another method that gives you the same result.

The method is used to be accessed from anywhere in the program. It can even be called more than once, and it can also be called from other programs.

Example : You have created a method to remove duplicates from the array. Now, once this method has been created, it can be used anywhere in the application where different inputs are provided and the method returns unique values, saving a lot of time.

Hide Low Level Details

Once we have defined a method, it can be treated as a "black box" i.e. when we use it, we don't need to worry about how the method task is performed. We 're just going to get the task done through methods.

In fact, when we use a method we assign the task of solving a low level problem to a method. It could become time consuming and frustrating to solve by ourselves.

Thus method can be viewed as a black box, because we accept the result without the information being concerned. Now we will learn how to define simple methods in Java.

Java Method Definition

A Java method must be defined before it can be used anywhere in the program. A method in general can include six components : -

A method in general can include six components : -

Access Specifier

These Keywords are used to determine the type of access to a function. It can be either public,protected or private. We will learn about access specifiers in later modules.

Modifier

It can be final,native,volatile,synchronized etc. A final method means that you can never change the functionality defined inside the method.

return_type

Specifies the type of value that the function returns,which may be of any valid data type. If no value is returned,then it should be void

Method name

It should be a valid Java Identifier,should be meaningful,should start with a letter in the lower case,the name of the method will typically start with a verb followed by one or more nouns. Example: calculateInterest.

Parameter List

It is a comma-separated list of a method's variables,may also be refrerated to as arguments or parameters. A method may be without any parameter,in which case the list of parameters is empty.

Method body

It is a part of the declaration of method. It includes all the actions that have to be carried out. It's limited to the pair of curly braces.

Java Method Prototype : It consists of the number and type of arguments with the method return type. Using method Prototype, the compiler compares the number and types of arguments at compile-time and any reported incorrect number or type of arguments helps the compiler to easily point out an error.

javaobject

Java Method Signature : It is a part of Method Prototype, that refers to the number and type of the arguement. Method Signature and return type of a method make Method Prototype. We will learn more about Java Method Signature in the next tutorial.

Example : int minimum (int x, int y)

Types of Java methods

Java Methods can be defined by the user and also can be used from pre-existing standard library. Based on this, Java Method has two types :

  • 1. Standard Library Methods(Predefined Methods)
  • 2. User-defined Methods

Standard Library Methods(Predefined Methods)

Standard library methods are built-in methods in Java, and are always available for use. Such libraries come with the Java Class Library (JCL) in a.jar file with Java Virtual Machine and Java Runtime Environment.

Example :

  • max( ) is a method that returns the greatest of the two int values. It is a method of the math class.

  • print() is a method that prints the values inside the quotes " ". It is a method of java.io.PrintSteam.

We can use these method anywhere in the program by just calling it, we dont have to worry about the internal working of it, since the series of codes related to the method runs in the background that is already stored in the libarary.

copyimage
//Java Program to demonstrate Standard Library Methods in Java
class CodeBator {
    public static void main(String args[]){   
        System.out.print(Math.max(20, 30) + " "); // max() method of Math class
        System.out.print(Math.min(20, 30)); // min() method of Math class
   }
}

OUTPUT :

 3020

User-defined Methods

Unlike Predefined methods, User-defined methods must be explicitly defined by the user. These Method can be modified according to the need of the project or program.

How to create a user defined method ?

copyimage
//Java Program to demonstrate User Defined Methods in Java
      public static int sum(int  x, int y){  // x and y formal parameters
      int result;
      result = x + y;
      return result;
  }

The above written code is a user-defined method that we have written to calculate the sum of two int numbers. The return type of the method is of int Data Type. Now we will learn how to call this method in the next module.

Accessing a Method

The method is invoked or executed by specifying the name of the method followed by the parameters sent in the parenthesis.

Example : int sum ( int x, int y).

The method call Statement for the given method can be shown as : y = sum (x, y).

copyimage
//Java Program to demonstrate How to Access a Method in Java
import java.util.*;
class CodeBator {
      public static void main(String args[]){  
      System.out.println("Enter two numbers");
      Scanner sc=new Scanner(System.in);
      int a = sc.nextInt();
      int b = sc.nextInt();
      int y = sum(a,b);// accessing a method where a and b are parameters being passed
      System.out.println("Sum of two number is"+ " "+ y);
  }
      public static int sum(int  x, int y){  // x and y formal parameters
      int result;
      result = x + y;
      return result;
  }
}

OUTPUT :

Enter two numbers4456Sum of two number is 100

In the above program we are calling a method name sum where a and b are the parameters which have been taken as input from the user. Dont know how to take input from the user kindly follow Java User Input.

The parameters a and b correspond to the respective values x and y. The variable result stores the sum of these two values x and y and thus return it.

The Method returns the value which is now stored in the variable name y which is then printed on the screen.

For practice just try out more examples like calculate the factorial by calling a method. We have already discussed the factorial problem at couple of places with the dry run in this Java tutorial.

Actual and Formal Parameters in Java

There are parameters passed in the method definition and in the Statement that invokes the method. The parameters that are passed in method definition are known as formal parameters and the parameters that appear in method call statement are known as actual parameters.

Let us take the same example as above to find out what are the formal and actual parameters

Example : Actual and Formal Parameter

copyimage
//Java Program to demonstrate How to Access a Method in Java
import java.util.*;
class CodeBator {
      public static void main(String args[]){  
      System.out.println("Enter two numbers");
      Scanner sc=new Scanner(System.in);
      int a = sc.nextInt();
      int b = sc.nextInt();
      // Method call statement
      int y = sum(a,b);  // a and b are actual parameters
      System.out.println("Sum of two number is"+ " "+ y);
  }

      // Method Definition
      public static int sum(int  x, int y){  // x and y formal parameters
      int result;
      result = x + y;
      return result;
   }
}

We use the formal parameters in the method definition, hence can be considered as formal. Actual parameters refer to the method call, which is called as actual because they specify the actual values that are sent to the method.