Java is basically a pass-by-value language. But I wrote some code, and found that in that case Java actually passed the reference of an array rather than just its value, because when I changed the values in the array in another method of another class, the original array was changed.
What I did was I created a constructor and passed an array as the argument of that constructor. That constructor then called a method which did some operations on the said array. But, when I checked for the values in that array in my main() method, from which the constructor was called, I found that the values were changed.
If Java was supposed so pass a copy of the array, this shouldn't have happened. Can anyone please help?
Here is the code I'm talking about. The actual code is different but I wrote an example of what I am talking about for the sake of simplicity.
public class Test
{
public static void main(String[] args)
{
int[] matrix = {1, 2, 3, 4};
dump(matrix);
Changer changer = new Changer(matrix);
dump(matrix);
}
static void dump(int[] matrix)
{
for(int i = 0; i<matrix.length; i++)
{
System.out.print(matrix[i]);
}
System.out.println();
}
}
class Changer
{
Changer(int[] matrix)
{
change(matrix);
}
void change(int[] matrix)
{
for(int i = 0; i < 4; i++)
{
matrix[i] += 1;
}
}
}
Any help is appreciated
EDIT:
Because this question was marked as duplicate, I want to clarify.
I accept that Java is pass-by-value. But I pointed to a situation where the value was not passed, and the reference/original variable was passed. I want some confirmation about Java's behavior