Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

PLEASE WRITE IN JAVA (Comments are greatly appreciated) Write an object class wi

ID: 3911502 • Letter: P

Question

PLEASE WRITE IN JAVA (Comments are greatly appreciated) Write an object class with just one instance variable, an integer array. Your constructor should take an integer array as its only parameter. Write all the accessors, mutators, toString and equals methods. Also write an additional RECURSIVE method that returns the sum of all the elements in the array (your method should have an array as it's argument and should have the recursive call in its return for the general case). Write a client class to test all your methods and especially your recursive method.

Explanation / Answer

ArraySum.java

import java.util.Arrays;

public class ArraySum {

//Declaring instance variables

private int size;

private int arr[];

//Parameterized constructor

public ArraySum(int[] arr) {

this.arr = arr;

}

//Setter and getters

public int getSize() {

return size;

}

public void setSize(int size) {

this.size = size;

}

public int[] getArr() {

return arr;

}

public void setArr(int[] arr) {

this.arr = arr;

}

@Override

public String toString() {

return "ArraySum [size=" + size + ", arr=" + Arrays.toString(arr) + "]";

}

@Override

public boolean equals(Object obj) {

if (this == obj)

return true;

if (obj == null)

return false;

if (getClass() != obj.getClass())

return false;

ArraySum other = (ArraySum) obj;

if (!Arrays.equals(arr, other.arr))

return false;

if (size != other.size)

return false;

return true;

}

//This method will calculates the array sum

public int arraySum(int arr[]) {

if (1 == arr.length) {

return arr[arr.length - 1];

}

return arr[0] + arraySum(Arrays.copyOfRange(arr, 1, arr.length));

}

}

_______________

Test.java

public class Test {

public static void main(String[] args) {

  

int arr[]={1,2,3,4,5,6,7,8,9,10};

int size=10;

ArraySum as=new ArraySum(arr);

as.setArr(arr);

as.setSize(size);

System.out.println("Sum of Array Elements :"+as.arraySum(arr));

}

}

______________

Output:

Sum of Array Elements :55

__________Thank You

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote