0

So I have a string[][] where I want to save some information from my database. Eclipse told me I needed to initialize my string[][], so i said string[]][] = null. Now I get a null pointer exception, but I'm not sure what I'm doing wrong.

try {
            Statement st = con.createStatement();
            String systems[][] = null;
            int firstcounter = 0;

            String item = "SELECT ram, cpu, mainboard, cases, gfx FROM computer_system";

            ResultSet rs = st.executeQuery(item);
            while (rs.next()){
                systems[firstcounter][0] = rs.getString("ram");
                systems[firstcounter][1] = rs.getString("cpu");
                systems[firstcounter][2] = rs.getString("mainboard");
                systems[firstcounter][3] = rs.getString("cases");
                systems[firstcounter][4] = rs.getString("gfx");
                firstcounter++;
            }
            System.out.println(systems[0][0]);
Eran
  • 387,369
  • 54
  • 702
  • 768
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Andy Turner Mar 18 '15 at 13:44
  • How can I dynamically add items to a Java array: http://stackoverflow.com/q/5061721/1023562 – Ivan Jovović Mar 18 '15 at 14:06

3 Answers3

5

You are supposed to initialize the array to a non null value in order do use it :

String systems[][] = new String[n][5];

where n is the max capacity of the array.

If you don't know in advance how many rows your array should contain, you can use an ArrayList<String[]> instead, since the capacity of an ArrayList can grow.

For example:

        Statement st = con.createStatement();
        List<String[]> systems = new ArrayList<String[]>();
        String item = "SELECT ram, cpu, mainboard, cases, gfx FROM computer_system";
        ResultSet rs = st.executeQuery(item);
        while (rs.next()){
            String[] row = new String[5];
            row[0] = rs.getString("ram");
            row[1] = rs.getString("cpu");
            row[2] = rs.getString("mainboard");
            row[3] = rs.getString("cases");
            row[4] = rs.getString("gfx");
            systems.add(row);
        }
Eran
  • 387,369
  • 54
  • 702
  • 768
2

That's because, you initialize the systems[][] as null.

Try String systems[][] = new String[x][y]; instead, where x and y is the dimensions of your matrix.

But we do not like arrays in Java code, use Lists instead. Lists can expand dinamically, while your matrix can't, and Lists provide compile time type check, so it is more safe to use. For more info see Item 25 from Joshua Bloch's Effective Java, which says:

Item 25: Prefer lists to arrays

Nagy Vilmos
  • 1,878
  • 22
  • 46
1

You need to initialize in following way

String systems[][] = new String[size][size];

where size = size of the string array you want.

apgp88
  • 955
  • 7
  • 14