aspose file tools*
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
Author

Array compilation question

M Marsden
Greenhorn

Joined: Jun 18, 2008
Posts: 18
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
author
Sheriff

Joined: Sep 28, 2004
Posts: 18709
    
  40

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.

Henry


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

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
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Hi,

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: http://aspose.com/file-tools
 
subject: Array compilation question