What is the output for the following program Please explain
Solution
Please follow the code and comments for description :
CODE :
class Sum { // class that sums the data passed
 private int sum = 5; // private variable for the class
 public int method (int start, int end) { // method that sums the data for hte given two variables
 int sum = 0; // local variable for the method
 for(int i = start; i <= end; i++){ // iterating over the loop for th egiven passed variables
 sum = sum + i; // incrementing the sum value
 }
 return sum; // returning the sum value when called
 }
 }
 public class Test { // class that tests the code
 public static void main(String[] args) { // driver method
 int upper = 5; // required initialisations
 Sum sumObject = new Sum(); // creating an object for the class
 int sum = sumObject.method(1, upper); // calling the method in the parent class
 System.out.println(\"The Sum of \"+upper+\" numbers is : \"+sum); // printing the output
 }
 }
OUTPUT :
The Sum of 5 numbers is : 15
 Description :
The output was 15 as when the clas with the method to calculate the sum is called then the method needs to have two parameters which in this case we passed the values 1 and 5 (upper). Now when the method is called the trigger goes to the method in the respecive class, and inside the method we have a local variable initialised with a value of 0. Now from iterating over the loop for the given parameters of the low and high values, the sum gets incremented over the loop incrementing. So thus from the local variable value we have the sum as 0, starting the iteration with the value we get the values at the end of each iteration as :
Iteration 1 : 1
 Iteration 2 : 3
 Iteration 3 : 6
 Iteration 4 : 10
 Iteration 5 : 15
So the resultant value 15 is resturned as the result and that is saved in the main method variable that is called.
 Hope this is helpful.

