Practical-16
Write a java program which shows the Nesting of Methods.
Introdution
Writing a Java program which shows the nesting of methods is a way of highlighting the importance of the function in a program. It also makes debugging simpler and easier. Nesting is basically the concept of using the same method inside the same class of code. This allows a programmer to use the same set of instructions multiple times and ensure the same set of instructions is being used across the code. This also makes code more readable and easier to modify or maintain.
Code
public class Methods {
public static void main(String[] args) {
int value1 = 20;
int value2 = 40;
int value3 = sum(value1, value2); //calling the sum method
System.out.println("Sum of the two numbers: " + value3);
int value4 = 30;
int value5 = 50;
int value6 = sum(value4, value5); //calling the sum method
System.out.println("Sum of the two numbers: " + value6);
}
//method nesting
public static int sum(int a,int b ){
return a + b;
}
}
Output
Sum of the two numbers: 60
Sum of the two numbers: 80
::: tip Explanation The code is demonstrating the concept of method nesting. This code has two methods, the main method and the sum method. The main method is calling the sum method twice and passing two numbers as arguments which are being added together and the result is being printed out by the println statement. :::