Defining functions with a return type

 

Whenever we can define a function with a return data type, then we should not close the function without returning the value of the return data type. So a blind rule we follow is to declare a variable of the return data type as the first statement inside the procedure and assign the value to be returned to that variables and then return that variables.

 

Example:

The following program illustrate the above concept

Class Odemo B

{

Int     I, j;

Int function 1(int i)

{

Int j=0;

J=i*I;

Return (j);

}

}

Class test

{

Public static void main (string args [ ])

{

O demo B d1 = new O demo B ();

d1. function1 (9);

int x = d1. function1 (4);

System. Out. Prinln (x);   \\ x=16

Or

System. Out. Prinln (int x = d1. function1 (4));  \\ 16 is printed

System. Out. Prinln (x+6);   \\ 22 is printed

Or

System. Out. Prinln (d1. function1 (4) +6);   \\ 22 is printed

} // end main

} // end class

 

Explanation:

In the above statement  d1.function1 (9), we are not handling the value of the return data type i.e.  d1. function1 (9) hold the value 81 and this value is not assigned to any variable in the main. In the statement int x = d1. function1 (4), we are handling the value of the return data type i.e. the value returned by the function is assigned to the variable x. the last statement in the program illustrates that we can even pass expressions as arguments to the functions

 

Note:

As we can design functions to return x primitive data type, we can design functions to return an object of a class.

 

Defining Functions Homework Help

Tutorspoint.com offers live java programming homework help to university students in America & Australia countries