Reputation: 997
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
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
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