EoRaptor013 EoRaptor013 - 1 year ago 60
Java Question

How many dimensions in an array with no value

I'm a little lost (still working with Ron Jeffries's book). Here's a simple class:

public class Model{
private String[] lines;

public void myMethod(){
String[] newLines = new String[lines.length + 2];
for (i = 0, i <= lines.length, i++) {
newLines[i] = lines[i];

I have another class that initializes
, and an empty array, by setting
myModel = new String[0]
. When I invoke
, I get a subscript out of range error. Looking at the debugger, what I see is that
has zero dimensions and zero length. Shouldn't it have a dimension and length of 1? Granted the value of
, but the array itself shouldn't be, should it?

Any thoughts truly appreciated.


Answer Source

I think your example is probably not the same as your actual code based on your description. I think the problem is that arrays are zero-based and thus an array initialized as:

string[] lines = new string[0];

has no elements.

You need to change your loop so that you check that the index is strictly less than the length of the array. As others have indicated you also need to make sure that the array itself is not null before trying to reference it.

My take on your code:

public class Model{
    private String[] lines = new string[0];

    public Model( string[] lines ) {
        this.lines = lines;

    public void myMethod(){
        int len = 2;
        if (lines != null) {
            len = len + lines.length;
        String[] newLines = new String[len];
        for (i = 0, i < lines.length, i++) {
            newLines[i] = lines[i];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download