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

I get the java.lang.NullPointerException and i don't understand why

public class Array
{
    public int dimensione;
    public int[] arr;
    
    /*
     * n: array dimension
     */
    public Array(int n)
    {
        dimensione = n;
        int max = 10;
        int min = 1;
        
        int[] arr = new int[n];
        
        //put random number between 1 and 10 in the array
        for(int i = 0; i < n; i++)
        {
            arr[i] = (int)(Math.random() * ((max - min) + 1) + min);
        }
    }
    
    public String toString()
    {
        String arrayToString = "";
        
        for(int i = 0; i < dimensione; i++)
        {
            arrayToString = arrayToString + arr[i] + " ";
        }
        
        return arrayToString;
    }
}

I have this code and i get the error but i don’t understand why. Is the array not being filled correctly and it stays null so when i try to write it as a string it finds a null array? if yes, why is not working? how do i solve it?

>Solution :

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

In the constructor, you declare a local variable arr which shadows the class’s arr field, which remains null. That causes a NullPointerException when you call toString (which you apparently do somewhere).

Change

int[] arr = new int[n];

to

arr = new int[n];
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