Joseph
Joseph

Reputation: 2736

Java Array in different method

I think I am making a really basic mistake but after playing around for an hour I cant work this out. I create an array in one method and try and call it in the main method, however I keep getting a null pointer exception when referencing the array from the main method. My class is:

public class test {

    public static String[][] Data;

     public static void createArray() {
            System.out.println("Test 2");

            String[][] Data = new String[2][4];

             Data[0][0] = "13CG43"; //CD ID
             Data[0][1] = "POP"; //Type
             Data[0][2] = "12.99"; //Price
             Data[0][3] = "5"; //Stock

             //Second row
             Data[1][0] = "293DD3"; //CD ID
             Data[1][1] = "HIP"; //Type
             Data[1][2] = "14.99"; //Price
             Data[1][3] = "2"; //Stock

        }


    public static void main(String[] args) {

        try {
            System.out.println("Test1");
            createArray();
            System.out.print("Test3 " + Data[0][0]);

            } catch(Exception e) {
                System.out.println("Error");
            }


    }
}

Thanks,

Upvotes: 0

Views: 1775

Answers (2)

Heisenbug
Heisenbug

Reputation: 39204

That's because the array declaration its inside your function call. Put it only outside and data will be still available after createArray function will be returned.

Change:

String[][] Data = new String[2][4];

with

Data = new String[2][4];

You were redeclaring Data array inside the createArray function scope. So there were 2 Data array in your program. One global and one local to your function, hiding the global one. The latest, which was the array you were initializing, will be destroyed after the createArray function is returned.

Upvotes: 4

msarchet
msarchet

Reputation: 15242

  public static void createArray() {
            System.out.println("Test 2");

            Data = new String[2][4];

             Data[0][0] = "13CG43"; //CD ID
             Data[0][1] = "POP"; //Type
             Data[0][2] = "12.99"; //Price
             Data[0][3] = "5"; //Stock

             //Second row
             Data[1][0] = "293DD3"; //CD ID
             Data[1][1] = "HIP"; //Type
             Data[1][2] = "14.99"; //Price
             Data[1][3] = "2"; //Stock

        }

You were declaring a new local variable inside the method instead of modifying the global one.

Upvotes: 7

Related Questions