I have defined created array arr in Class Main as follows:
class Main {
public static Scanner scanner=new Scanner(System.in);
public static int[] arr;
Then in next line I have called two functions through main() function
public static void main(String[] args) {
InsertElements(arr);
PrintUnsortedArray(arr);
}
public static void InsertElements(int[] barr){
int size=scanner.nextInt();
barr=new int[size];
for(int i=0;i<barr.length;i++){
barr[i]=scanner.nextInt();
}
}
Finally I have displayed the array
public static void PrintUnsortedArray(int[] arr){
System.out.println("The unsorted array is:"+Arrays.toString(arr));
}
/*The Output is:
Enter the size of array:
5
Enter the array elements:
1 34 67 90 67
The unsorted array is:null*/
However,this code works fine:
public static void main(String[] args) {
System.out.println("Enter the size of array:");
int size=scanner.nextInt();
arr=new int[size];
InsertElements(arr);
PrintUnsortedArray(arr);
}
public static void InsertElements(int[] barr){
System.out.println("Enter the array elements:");
for(int i=0;i<barr.length;i++){
barr[i]=scanner.nextInt();
}
}
Why?
Can someone explain
>Solution :
In this line:
barr=new int[size];
You are reassigning barr so it no longer points to the original array. You must create an array and pass that reference to your methods. Do not reassign the array with new in the methods.
int[] arr = new int[size];
InsertElements(arr);
PrintUnsortedArray(arr);
public static void InsertElements(int[] barr){
//int size=scanner.nextInt(); REMOVE
//barr=new int[size]; REMOVE
//rest can stay the same
for(int i=0;i<barr.length;i++){
barr[i]=scanner.nextInt();
}
}