Click here to Skip to main content
15,890,506 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello CodeProject community,

I'm trying to instantiate a matrix of an element. But when I call a certain element in the matrix, it would return a Null (or a NullPointerException when calling a method). Here's a simplified version of my code which still returns Null. I wonder what causes this problem. Thank you!

Best regards

What I have tried:

Java
public class MyProgram extends ConsoleProgram
{

    public void run()
    {
        someClass[][] sc = new someClass[1][2];
        System.out.println(sc[0][0].getX());
    }
    
}

public class someClass
{
    
    private int x = 0;
    public someClass()
    {
 
    }
    
    public int getX()
    {
        return x;
    }
}
Posted
Updated 23-Jan-18 15:40pm

1 solution

your problem is with function run

This is what you have done
Java
public void run()
{
       someClass[][] sc = new someClass[1][2]; // you have allocated some space for the array itself;
       System.out.println(sc[0][0].getX()); // accessing here is a violation
       // since you have not initialize space for each object; hence before you start accessing you need to initialize.
}

in other word
Java
sc[0][0] = new someClass();


When you declare an array of primitive variables, java set default value for that variable. And for all classes and String default is null. Follow the example to understand better
Java
public class Klass {
    public int x=10;
    public static void main(String []args) {
        int []i = new int[2];
        char []c=new char[2];
        Klass []k=new Klass[2];
        String s[] = new String[2];
        System.out.println(i[0] + " " + i[1]);
        System.out.println(c[0] + " " + c[1]); // in this case c is set to zero
        System.out.println(s[0] + " " + s[1]);
        System.out.println(k[0] + " " + k[1]);
        try {
          System.out.println(k[0].x); // since k is null it will thow exception
        } catch(NullPointerException e) {
            e.printStackTrace();
        }
        k[0] = new Klass();
        System.out.println(k[0].x); // You will see some result
    }
}
 
Share this answer
 
v2
Comments
Yuxi Long 23-Jan-18 22:25pm    
Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900