2

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?

1
  • It has nothing whatsoever to do with Arrays.fill specifically. Commented Jan 11, 2013 at 1:42

2 Answers 2

9

You cannot run arbitrary statements outside a method body.

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Thank-you. Odd to me that I've never run into before but you are right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.