views:

93

answers:

5

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`

+1  A: 

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.

rossoft
+10  A: 
public Person[] people = new Person[100];
  • public is an access modifier;
  • Person[] is an array of type Person;
  • people is the name of the variable that holds a reference to the aforementioned array;
  • new Person[100] allocates a new array of type Person that is capable of storing up to 100 Persons.
JG
+2  A: 

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
Chandra Patni
+1  A: 

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.

Michael Petrotta
+1  A: 
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 {

}
Dolph