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 compilation question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array compilation question" Watch "Array compilation question" New topic

Array compilation question

M Marsden

Joined: Jun 18, 2008
Posts: 21
Just wondering why the first array below doesn't compile:

public class InitError {
int[] a = new int[5];
a[3] = 2; // this line won't compile

public void init() {
int [] x = new int[4];
x[3] = 2; // this line is just fine!

// Any ideas? Thanks!
Henry Wong

Joined: Sep 28, 2004
Posts: 20517

Java only allows limited code outside of initialiers, constructors, and methods. The only code is the initialization of class and instance variables. The first case violates this. It is not in an initializer, constructor, method, or declaration of a class or instance variable.

The second case is fine because it is in a method.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ambi Avatar

Joined: Jun 27, 2008
Posts: 2
Hi Henry,
Can you please explain more about your expalanation.
In Standalone program where can we write public void init() method.
How this method can be called, or JVM will by itself calls this method.

"The second case is fine because it is in a method."
First method is also in a method.

Please confirm,
waiting for your valuable reply.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199


Welcome to JavaRanch!

Originally posted by Ambi Avatar:

First method is also in a method.

No, it's not. The line

a[3] = 2;

isn't inside a method, it's just inside the class body, and it's not legal there. The line

x[3] = 2;

on the other hand, is inside the method init(), and there it's totally fine.

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