Search code examples
javaarraysstringindexoutofboundsexception

array index out of bound


I want to create a combobox which takes names from database at runtime. So i created a empty string array but it throws an exception that arrayindexoutofbound. I think there's a mistake in initialization.....

            String s[]=new String[0];
            {
                 try
                {
                  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                  Connection con =DriverManager.getConnection("jdbc:odbc:project","sa","123456");
                  Statement stmt= con.createStatement();
                  ResultSet rs=stmt.executeQuery("SELECT Name FROM company");
                  i=0;
                  while(rs.next()) {        
                        s[i]=rs.getString(1);
                        i++;
                  }
                }
                catch(Exception ex)
                {
                    JOptionPane.showConfirmDialog(f,ex);
                }
                cb=new JComboBox(s);
            }

Solution

  • An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You are creating an array to hold 0 elements .

    String s[]=new String[0]; //<< intialized with length 0
    

    It will throw ArrayindexoutOfBoundsException when you try to access its 1st element s[0].

    Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

    Size the size of your array is 0 , hence Exception is thrown while accessing index 0.

    Below a basic diagram of an array for understanding.

    enter image description here

    It is an array of length 10 , indexed from 0 to 9.

    Since you don't know the number of elements your data structure needs to store while declaring the array itself. It is better to use a dynamic Collection in your case , probably any one of the implementation of List , like an ArrayList.

    List<String> s = new ArrayList<String>();
    while(rs.next())
    {
       s.add(rs.getString("NAME")); // using column name instead of index "1" here
    }
    

    Suggested Reading:

    1. Oracle's tutorial on Java arrays
    2. Lists vs Arrays - when to use what