Gary
Gary

Reputation: 997

Arrays.fill() only allowed in method?

I'm using a book to self-study Java. One of my exercises needs an array with boolean values. When I try to use Arrays.fill(myArray, false) as indicated below I get a compiler errors. Plus the IDE complains.

...\ArrayFill.java:6: <identifier> expected
...\ArrayFill.java:6: <identifier> expected
...\ArrayFill.java:6: illegal start of type

Here's the code:

import java.util.Arrays;

public class ArrayFill {

boolean[] myArray = new boolean[4];   // Declaration OK.
Arrays.fill( myArray, false);         // Not OK.

//    boolean[] myArray = {false, false, false, false }; // Manually OK.

public void makeReservation(){
    Arrays.fill(myArray, false);      // In a method, OK.
}

}

It seems like it has something to do with the fact that Arrays.fill is a static method but I can't find the answer why. Am I close?

Upvotes: 2

Views: 1495

Answers (2)

Code-Apprentice
Code-Apprentice

Reputation: 83527

The only code that can be directly inside a class is declarations and static initializers. Note that Arrays.fill(myArray, false); is neither of these, so it must be inside another block of code, specifically a constructor, method, or static initializer.

Upvotes: 2

SLaks
SLaks

Reputation: 887365

You cannot run arbitrary statements outside a method body.

You need to put your code in a constructor, initializer block, or main method.

Upvotes: 9

Related Questions