Exercise:
Write a Java Program to pass methods as arguments to other methods.
Click Here to View the Solution!
public class PassMethod {
public int add(int a, int b) {
int sum = a + b;
return sum;
}
public void square(int num) {
int result = num * num;
System.out.println(result);
}
public static void main(String[] args) {
PassMethod obj = new PassMethod ();
// calling the square() method
// passing add() as parameter
obj.square(obj.add(8, 1));
}
}
Click Here to View the Output!
81
Click Here to View the Explanation!
- In this program, first a class called
PassMethod
is created. - Then two methods called
add
andsquare
are created which return the sum of two numbers and display a number’s square respectively. - Next, in the
main method
of the class, an objectobj
of Main class is created. - The
square()
method is called with another methodadd()
passed as its parameter. The add method has two numbers passed as its parameters. Thus, a method is passed as a parameter in another method.