placement of code gives error...

erm... I'm new to Java and i was wondering why the following piece of code won't compile...

public class test {

int i;

i = 1;//This gives a compiler error... It says and <identifier> is expected...

public test() {

System.out.println( i );

}

... //add public void static main(..) and stuff...

}

However, if i write it this way...

public class test {

int i;

public test() {

i = 1; //when i initialize the variable 'i' here, it works fine...

System.out.println( i );

}

...

it works if i write it this why... can anyone tell me why the former is not accepted? Many thanks in advance...

[705 byte] By [frozttalea] at [2007-9-30 2:23:16]
# 1

You can't just insert statements at the class definition level (it's a syntax thingie). There's one exception

to this rule -- you can insert a statement block at this level -- public class Test {

int i;

// here's the (initialization) block

{ i= 1; }

// etc.

Alternatively, as you already figured out, you can stick the initialization part in the constructor -- public class Test {

int i;

// the ctor take care of initialization

public Test() { i= 1; }

// etc.

kind regards,

Jos

JosHorsmeiera at 2007-7-16 13:32:36 > top of Java-index,Archived Forums,New To Java Technology Archive...
# 2

Oops, I forgot a third alternative -- use an initialization expression -- public class Test {

// intialize the member

int i= 1;

// etc.

kind regards,

Jos

JosHorsmeiera at 2007-7-16 13:32:36 > top of Java-index,Archived Forums,New To Java Technology Archive...