Java Method


Introducting Methods

Classes usually consist of two things: instance variables and methods. The topic of methods is a large one because Java gives them so much power and flexibility. However, there are some fundamentals that you need to learn now so that you can begin to add methods to your classes.

This is the general form of a method:

type name(parameter-list)
{
  //body of method
}

Here, the type method determines what type of data the method will return. It can be any valid type, including the type of class you created. If the method does not return any value, its return type must be canceled and void returned. The name of the method is indicated by "Name". We can put anything in a method but it would be more effective to give any meaningful name to this method. This may be a legal identifier other than the one already used by other items in the current scope. We can separate the parameter lists from each other by commas (,). The parameters are basically variables when the method is called to take the value of the argument passed in the method. If the method does not contain any parameters then its parameter list will be empty ().


Here are some examples:

Adding parameters to the method

Program
public class Main
{
    public int Sum(int a,int b)
    {
        return a+b;
    }
  public static void main (String[]args)
  {
    Main obj = new Main();
    int sum = obj.Sum(10,20);
    System.out.println(sum);
  }
}
Run

In the example above, a method is created inside the "Main" class. The name of this method is "Sum" and the two parameters named a, b are given whose data type integer. This method returns the sum of a and b. The return of this method is given as "int" because a and b are integer numbers and when two integer numbers are added then the sum is integer. When you want to call it, you have to call the method by inserting the (.) Operator with the object of the class and send the value you want to send in place of the parameter list of the method (obj.Sum (10,20)).


The method is returning the value

Program
public class Main
{
    public void Sum(int a,int b)
    {
        int sum = a+b;
        System.out.println(sum);
    }
  public static void main (String[]args)
  {
    Main obj = new Main();
    obj.Sum(20,20);
  }
}
Run

In the above example a method has been created but no value has been returned so void is written in its return type.

We will learn more about the method in the next tutorials.