Write output for the following programSolutionThe output of

Write output for the following program

Solution

The output of the program is :

The result of the first instance is: 15
The sum is 15
The result of the second instance is: 55
The sum is 55

Program with explanation :

class Sum { // Class declaration for Sum
  

//Instance variables for the class
       private int start;   
       private int end;
       static int sum;   

// Constructor for the class sum. This initializes the instance variable start and end with the parameter values.
   Sum(int start, int end)

       {
           this.start = start;
           this.end = end;
       }
      
   // method1 returns the value of the variable sum
       public int method1()
       {
           return sum;
       }
      
   // method2 - for loop for looping from start value to end value during which time the sum is incremented with the current value.
       public void method2()
       {
           for(int i=start; i<=end; i++)
           {
               sum = sum + i;
           }
       }
      
}

// main class for main function

public class Test {

public static void main(String[] args)
       {
   // creating an object for Sum class and calling the constructor which will store the values as ,
   // start = 1, end = 5
           Sum sumObject1 = new Sum(1,5);

           sumObject1.method2(); // function call to method2 which will add the values to sum variable

           System.out.println(\"The result of the first instance is: \" + sumObject1.method1()); // Prints the sum value on the screen which will be returned by the method1() function

           System.out.println(\"The sum is \" + Sum.sum); // directly accessing the sum value using the class name. This is possible because sum variable is static. hence it is accessible by just using the class name
          
// The same happens here but the value would be start = 6 and end = 10
   Sum sumObject2 = new Sum(6,10);
           sumObject2.method2();
           System.out.println(\"The result of the second instance is: \" + sumObject2.method1());
           System.out.println(\"The sum is \" + Sum.sum);
       }
}

The first object method, sumObject1.method2() call will do the following,

sum = 1 + 2 + 3 + 4 + 5 = 15

The second object method, sumObject2.method2() call will do the following,

sum = 6 + 7 + 8 + 9 + 10 = 55

Write output for the following programSolutionThe output of the program is : The result of the first instance is: 15 The sum is 15 The result of the second inst
Write output for the following programSolutionThe output of the program is : The result of the first instance is: 15 The sum is 15 The result of the second inst

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site