File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Array Decleration Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array Decleration" Watch "Array Decleration" New topic

Array Decleration

Patrick Cicero

Joined: Nov 06, 2002
Posts: 17
In reading some books on Java Array declaring then writting small files to try and compile I did found that if I declare an Array reference outside of a method, then try to create the array using the array ref = new array_type[size], the program will not compile, but if I do the same inside a method it works
Example (file named
class Arraytest{
int[] scores = new int[5]; // NOT in method declare and create on 1 line

int[] scores2;
scores2 = new int[5]; // This will NOT compile
public anyMethod(){
int[] scores3;
scores3 = new int[5]; //This will compile
Why is this??? I have a feeling it has to do with no variables are created until the class is created, but then why if you do it on 1 line it compiles fine.
All the books I that talk about arrays use code snipets
and explain that doing declaring and creating array on two different lines is find.
FYI running Java 1.3
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

The line

is a declaration with an initializer. The line

is a declaration without an initializer. Both are fine at the class level; they declare, and optionally initialize, an array variable. The initializer is understood to be executed when an instance of the class is created, before the the class's constructor is invoked.

is an executable statement. You can't have executable statements at class scope. If you have code you want executed when an object is created, it belongs either in an initializer, in a constructor, or, rarely, in an instance initialization block (which is so rare I won't go into it here.) That's just how the language works. There's no rule that specifies when and how such lines of code would be executed. In your case, it's easy to imagine that the compiler should know what you mean; but in the general case of statements at class scope, it would be a giant mess. Executable statements need to be in a function.
Note for nitpickers: instance initializers get compiled into a function.
Make sense?

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: Array Decleration
It's not a secret anymore!