This week's giveaway is in the Java/Jakarta EE forum.
We're giving away four copies of Java EE 8 High Performance and have Romain Manni-Bucau on-line!
See welcome thread
Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Array Decleration  RSS feed

Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author and iconoclast
Posts: 24217
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
Those are the largest trousers in the world! Especially when next to this ad:
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!