Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array compilation question

 
M Marsden
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21126
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ambi Avatar
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic