Array Error  
Author Message
mike





PostPosted: 2004-9-2 3:36:00 Top

java-programmer, Array Error
I'm getting two errrors with the simple code below:

For line 5 I get " <identifier> expected "
For line 6 I get " ']' expected" and also " <identifier> expected "

What gives?

Thanks

------------------------------------------

1 package com.dlm.testing;

2 import java.util.Arrays;

3 public class Test1 {

4 public String[] names;
5 names = new String[50];

6 names[0]="Jones";

7 }
 
John C. Bollinger





PostPosted: 2004-9-2 7:07:00 Top

java-programmer >> Array Error Mike wrote:

> I'm getting two errrors with the simple code below:
>
> For line 5 I get " <identifier> expected "
> For line 6 I get " ']' expected" and also " <identifier> expected "
>
> What gives?
>
> Thanks
>
> ------------------------------------------
>
> 1 package com.dlm.testing;
>
> 2 import java.util.Arrays;
>
> 3 public class Test1 {
>
> 4 public String[] names;
> 5 names = new String[50];
>
> 6 names[0]="Jones";
>
> 7 }

Lines 5 and 6 are not part of any method (nor of an instance
initializer, but you don't need to worry about those just yet). Try this:

package com.dlm.testing;

import java.util.Arrays;

public class Test1 {

public String[] names = new String[50];

public Test1() {
names[0]="Jones";
}

}

Note the two different ways to initialize an instance variable (or its
members): in the variable's declaration, or in a constructor. You
cannot place bare code in the body of a class definition. (Under what
circumstances would it ever run?)


John Bollinger
email***@***.com