Java-Method with Parameters

Method with Parameters

The parameter list appears between the parentheses following the method name. Each parameter must have a unique name and a defined data type. The general form is:

Parameters allow a method to be generalized. That is, a parameterized method can operate on a variety of data and/or be used in a number of slightly different situations. To illustrate this point, let’s use a very simple example.

Here is a method that returns the square of the number 10. While this method does, indeed, return the value of 10 squared, its use is vary limited. However, if you modify the method so that it takes a parameter, as shown next, then you can make getSquare( ) much more useful.

Now, getSquare( ) will return the square of whatever value it is called with. That is, getSquare( ) is now a general-purpose method that can compute the square of any integer value. rather than just 10. Here is an example :

In the first call to getSquare( ), the value 10 will be passed into parameter ‘i‘. In the second call, ‘i‘ will receive the value 5. The third invocation passes the value of ‘y‘, which is 4 in this example. As these examples show, getSquare( ) is able to return the square of whatever data it is passed. It is important to keep the two terms parameter and argument straight.

1. A parameter is a variable defined by a method that receives a value when the method is called. For example, in getSquare(), ‘i‘ is a parameter.
2. An argument is a value that is passed to a method when it is invoked. For example, getSquare(100) passes 100 as an argument. Inside getSquare( ), the parameter ‘i‘ receives that value.

Program

Program Source

class StudentData{
   
    void printData(int num,int age, float hei)
    {
        System.out.println("Student Roll Number : "+num);
        System.out.println("Student Age         : "+age);
        System.out.println("Student Height      : "+hei);
    }
}

public class Javaapp {

    public static void main(String[] args) {
       
        StudentData sobj = new StudentData();        
        sobj.printData(1001,20,5.5f);        
        sobj.printData(1002,21,5.7f);       
        sobj.printData(1003,22,5.9f);
    }
}

Leave a Comment