I am trying to pass an array without using a reference, but directly with the values :
public static void main(String[] args){
int[] result = insertionSort({10,3,4,12,2});
}
public static int[] insertionSort(int[] arr){
return arr;
}
but it returns the following exception :
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token(s), misplaced construct(s)
Syntax error on token ")", delete this token
When I try the following code , it works , can anybody please explain the reason ?
public static void main(String[] args){
int[] arr = {10,3,4,12,2};
int[] result = insertionSort(arr);
}
public static int[] insertionSort(int[] arr){
return arr;
}
Arrays are Objects, yes, but nothing in Java is passed by reference. All parameter passing is by value. In the case of an Object, what gets passed is a reference to the Object (i.e. a pointer), by value. Passing a reference by value is not the same as pass by reference.
Because arrays are already pointers, there is usually no reason to pass an array explicitly by reference. For example, parameter A of procedure zero above has type int*, not int*&. The only reason for passing an array explicitly by reference is so that you can change the pointer to point to a different array.
Like all Java objects, arrays are passed by value ... but the value is the reference to the array. Real passing by reference involves passing the address of a variable so that the variable can be updated. This is NOT what happens when you pass an array in Java.
Object references are passed by value The reason is that Java object variables are simply references that point to real objects in the memory heap. Therefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed.
It has to be
int[] result = insertionSort(new int[]{10,3,4,12,2});
{10,3,4,12,2}
is a syntactic sugar for array initialization, which must go with the declaration statement like the one in the following -
int[] arr = {10,3,4,12,2};
Something as follows is not allowed too -
int[] arr; // already declared here but not initialized yet
arr = {10,3,4,12,2}; // not a declaration statement so not allowed
insertionSort({10,3,4,12,2})
is not valid java because you don't specify a type in your method call. The JVM does not know what type of array this is. Is it an array with double values or with int values?
What you can do is insertionSort(new int[]{10, 3 ,4 12, 2});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With