Ashesh Shrestha Ashesh Shrestha - 16 days ago 6
Java Question

Why should I define a method as another variable for integers but not for array in java?

The following code:

public static void main(String[] args) {
int first = 1;
int second = 2;
sum(first,second);
System.out.println(sum);
}
public static int sum(int a, int b){
int sum = a+b;
return sum;
}}


will return error and I need to write

int x = sum(first,second);
System.out.println(sum);


and define that method as integer x and print x.

But for array,

public static ArrayList<String> removeLast(ArrayList<String> list) {
//code
return list;
}


public static void main(String[] args) {
//code
removeLast(persons);

System.out.println(persons);
}


will print the returned value of array without defining as another array as the was with the previous one.

I am sorry if the question has already been asked as I couldn't find it. And I am just learning Java.

Answer

Arrays are passed by (value of) reference, therefore, any change that happens to the array inside the method, will actually change the array passed in to it. On the other hand ints are passed by value. Change an int inside a method, and it won't change the int passed into the method.

For this reason, the return statement in your array method is completely unnecessary. Your code will still change the array, even if you omit the return statement.

But there's another misconception that needs to be pointed out: when you sum two ints, you are creating a new value in memory, which exists as long as the method is executed. When the sum method is done, the sum int doesn't exist anymore. To retain its value, you need to return it from within the method, and assign it to a variable where you call the code.

Comments