1
0

Methods in Java

A method is much like a function or procedure in other programming languages. It lets you create a block of code that can be called from outside the object, take arguments, and optionally return a value.

The basic syntax for a method is as follows:

<MethodModifiers> <ReturnType> <methodName>(<arguments>)

{
    // Method Body
}

This syntax looks more complicated than it is. The MethodModifiers field is an optional field that enables you to state how restrictive the access to the method should be. Many options are available for this field, and you will learn them in the coming lessons. By that time just remember:

(1) By not putting anything in the field, you let any classes declared in the same file (actually the same package, which is discussed later) have access to the method.

(2) By declaring the method public, you allow any class to access the method, regardless of what file it is contained in.

If this method is used only within the same file or program it is being defined in, stick with the default by leaving the field blank. If you think the object will be reused, make the method public.

You then specify what type of value will be returned by the method. This type can be any of the basic types (like integer, float, and so on) or another class type. If the method does not return a value, use the void keyword.

The Vehicle class should have two methods for each instance variable: one to set the value of the variable, and one to get the value of the variable. To add these methods to the Vehicle class, use the following code:

Class to demonstrate get-set methods

class Vehicle
{
    int weight;
    int speed;
    public void set_weight(int new_weight)
    {
        weight = new_weight;
    }
    public int get_weight()
    {
        return weight;
    }
    public void set_speed(int new_speed)
    {
        speed = new_speed;
    }
    public int get_speed()
    {
        return speed;
    }
}

Note that the methods that need to return a variable use the keyword return. Make sure that the value that is being returned is of the same type as specified in the method declaration.

Methods declared inside a class have complete access to all the instance variables defined within that class and can access them as if they were defined inside the method. For example, in the set_weight() method, the variable weight specified is the same as the instance variable weight declared at the start of the class with the int weight; statement.

Calling methods

To call a method in some another method we use method invocation statement. Depending upon the return type of method two different forms of method invocation statement are used. When the return type of called method is void then in calling function we use the statement as:

    object.methodName(actual parameters);

OR

    className.methodName(actual parameters); //for static methods

The instance methods are called using dot operator with object-name and class-methods (static methods) are using dot operator with class name.

If the return type of method is not void and it returns some value then the form of invocation statement is:

    varName=object.methodName(actual parameters);

OR

    varName=className.methodName(actual parameters);

Here method invocation statement is clubbed with assignment statement to assign the returned value to variable on left side. The type of variable must be compatible with the returned type of called method.

The actual parameter can be passed by value or by reference. In Java all primitive type variables are passed by value and all objects are passed by reference. So like C/C++ no special symbol is required to distinguish between parameter passing by value and by reference.

Program to demonstrate method calling

class ComplexNumber
{
    double rl;
    double img;
    ComplexNumber()
    {
        rl=0;img=0;
    }
    ComplexNumber(double x, double y) // passing primitive type
    {
        rl=x;img=y;
    }
    double retReal()
    {
        return rl;
    }
    double retImaginary()
    {
        return img;
    }
    ComplexNumber addComplex(ComplexNumber x) //function returning object &
    {    // receiving object as parameter
        ComplexNumber c=new ComplexNumber();
        c.rl=rl+x.rl;
        c.img=img+x.img;
        return c;
    }
    void displayComplex()
    {
        if(img>0)
            System.out.println("Number="+rl+"+"+img+"i");
        else
            System.out.println("Number="+rl+img+"i");
    }
}

class ComplexMain
{
    public static void main(String args[])
    {
        ComplexNumber c1=new ComplexNumber(12,-15);
        ComplexNumber c2=new ComplexNumber(10,11);
        ComplexNumber c3=new ComplexNumber();
        
        c3=c1.addComplex(c2);
        c1.displayComplex();
        c2.displayComplex();
        c3.displayComplex();
    }
}

Output

Number=12.0-15.0i
Number=10.0+11.0i
Number=22.0-4.0i

Recursion

In Java Methods can be implemented using recursion. When we write program then any method can call any number of methods. It is also possible for a method to call itself. If a method call itself within it then it is called a recursive call and this process of calling a method within itself is called recursion. If method1 call method2, which in turn can call method1 then this is also a form of recursion and is called indirect recursion.

Program to calculate factorial of number using recursion

class Factorial
{
    int factorial(int n)  // recursive method
    {
        if(n==0) return 1;
        else return n*factorial(n-1);  // recursive call to factorial
    }
}
class RecFact
{
    public static void main(String args[])
    {
        Factorial f=new Factorial();
        int n=5;
        int fact;
        fact=f.factorial(n);
        System.out.println("Factorial of "+n+" is: "+fact);
    }
}

Output:

Factorial of 5 is: 120

Leave a Reply