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]);
2

3 Answers 3

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);
        }
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Why [5][10] ? :) :) :)
1

You need to initialize in following way

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

where size = size of the string array you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.