Java – Introduction to Methods

Java – Introduction to Methods 2017-08-09T10:11:02+00:00

Java Methods :

As we all know that, classes usually consist of two things instance variables and methods.

Here we are going to explain some fundamentals about methods.

So we can begin to add methods to our classes.

Methods are defined as follows

§  Return type

§  Name of the method

§  A list of parameters

§  Body of the method.

Syntax:

return type method name (list of parameters)
{
                Body of the method
}

return type specifies the type of data returned by the method. This can be any valid data type including class types that you create.

If the method does not return a value, its return type must be void, Means you can say that void means no return.

Methods that have a return type other than void return a value to the calling routine using the following form of the return statement:

return value;

Here, value is the value returned.

The method name is any legal identifier.

The list of parameter is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called.

If the method has no parameters, then the parameter list will be empty.

Let us look at one example of class which have methods and data members both.


 


Output:
Enter Box Width : 15

Enter Box Height : 20

Enter Box Depth : 10

Volume is : 3000.00

Here width, height and depth are data members of class Box and void volume() is method of class Box.

Here method has no parameter and no return value.

Now let us look at same program but in different way.


 


Output:

Enter Box Width : 15

Enter Box Height : 20

Enter Box Depth : 10

Volume is : 3000.00

Here in above program volume() method has return type double so we took one vol variable. It is a local variable of class BoxDemo and it catch the returned value by volume method of class Box.

One thing must keep in mind that the data type of vol and return type of volume() method always be same.


 


Output:
Enter Box Width : 15

Enter Box Height : 20

Enter Box Depth : 10

Volume is : 3000.00

 

Here in above program volume() method has three parameters as well as double return type.

Here we took three extra local variables in class BoxDemo and pass them in function calling.

One thing must keep in mind that in defining and calling of method, the sequence of data type of parameter must be same in both.

Prev Next