Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the array output null ? I am trying to input numbers and display array

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
   }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading