Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating an array in a class

Tags:

java

arrays

I have a compilation problem in a Java program:

class FigureEditor {
   int[] a;             ----- Syntax error on token ";", , expected
   a = new int[5];
}

What am I doing wrong?

like image 775
tr3quart1sta Avatar asked Oct 21 '11 13:10

tr3quart1sta


People also ask

How do you create an array in class?

Before creating an array of objects, we must create an instance of the class by using the new keyword. We can use any of the following statements to create an array of objects. Syntax: ClassName obj[]=new ClassName[array_length]; //declare and instantiate an array of objects.

Can you put an array in a class?

Yes, since objects are also considered as datatypes (reference) in Java, you can create an array of the type of a particular class and, populate it with instances of that class.

How do you define an array inside a class?

Arrays can be declared as the members of a class. The arrays can be declared as private, public or protected members of the class. To understand the concept of arrays as members of a class, consider this example.

How do you declare an array inside a class in C++?

An example of class with an array member with value initialisation: struct foo { int member[10] = {}; };


1 Answers

You can't have "floating" statements in the class body.

Either initialize it directly:

int[] a = new int[5];

Or use an initializer block:

int[] a;
{
a = new int[5];
}
like image 183
Bozho Avatar answered Oct 05 '22 13:10

Bozho