Declaring array variables [closed]
Hey guys, got a problem with a question.
Question : Write a declaration for a variable people that could be used to refer to an Array of objects of type Person
My answer:
public people[];
people = new Person [100];
But I am getting an error saying it is wrong. What am I doing wrong?
PS. I also tried public people[] = new Person [100]
The error that I am receiving is this:
Main.java:5: <identifier> expected
public people[];
^
Main.java:6: <identifier> expected
people = new Person [100];
^
2 errors
The output should have been: If it wasn't correct it won't have compiled
This is what was actually produced: Exception in thread "main" java.lang.NoClassDefFoundError: Main`
public Person[] people = new Person[100];
public
is an access modifier;Person[]
is an array of typePerson
;people
is the name of the variable that holds a reference to the aforementioned array;new Person[100]
allocates a new array of typePerson
that is capable of storing up to 100Person
s.
All java variable must have their type specified.
Person[] people = new Person [100];
You can specify qualifier to the variable. Such as:
final Person[] people = new Person [100]; //applies to fields and variables
private Person[] people = new Person [100]; //applies to fields only
private static volatile Person[] people = new Person [100]; //applies to fields only
The actual declaration must declare the name of the variable, and its type.
Person[] people;
(The variable is named "people", and its type is "array of Person objects". Make sure you have Person
defined somewhere!)
The array creation (not declaration) actually creates an array of a given size:
people = new Person[100];
I think you may have been thrown off by the repetitive nature of the combined expression:
Person[] people = new Person[100];
... where you're specifying the type twice.
I think the sentence should be:
Person people[];
people = new Person[100];
.OR.
Person people[] = new Person[100];
since your people variable is of the type Person, you should declare it that way.
Person [] people;
people = new Person[100];
Your code is almost correct (you just forgot to provide the type of the array, as shown above), but be sure you also defined a class called Person. You can add a new class to your project and just leave it empty (which is enough to compile your test code).
public class Person {
}
精彩评论