Hi @ayman, basically, there are two forms of datatypes one is primitive, and the other one is non-primitive datatype. In JAVA, if we pass a parameter of primitive datatype to a function, at the time of call, a copy of that variable is passed to that function, not an original one is passed, so any changes made in that variable are not reflected in the original one.
Here is the code for primitive datatypes like int, double,float
class ArrayToMethod {
public static void main(String args[]) {
int x=10;
System.out.println(“The Value of X before calling the method is:”);
System.out.print(x);
System.out.println();
multiply(x); //nothing is being returned
System.out.println(“The Value of X after calling the method is:”);
System.out.print(x);
} //end of main()
static void multiply(int x) {
x=1; //will not change the value of original X
//Not returning anything
}
}
On the other hand, non-primitive data types are passed by reference, so any changes made in the calling method will change the original values of non-primitive data types. As the array is a non-primitive data type so its values will be changed if there are any changes in the called method., here is the code for your understanding you can check by yourself.
class ArrayToMethod {
public static void main(String args[]) {
int[] arr = {
1,
2,
3,
4,
5
}; //initialize
System.out.println(“The Values before calling the method are:”);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " "); //printing the array before calling method
}
int[] returnedArr = multiply(arr, 3); //storing the returned array
System.out.println();
System.out.println("The Values from the returned Array are:");
for (int i = 0; i < arr.length; i++) {
System.out.print(returnedArr[i] + " "); //printing the returned array
}
} //end of main()
static int[] multiply(int[] arr, int num) {
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] * num;
}
return arr; //returning Array
}
}