Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring array variables [closed]

Tags:

java

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`

like image 863
user228390 Avatar asked Nov 22 '25 04:11

user228390


2 Answers

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.
like image 125
João Silva Avatar answered Nov 23 '25 18:11

João Silva


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
like image 42
Chandra Patni Avatar answered Nov 23 '25 20:11

Chandra Patni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!