Hi I'm having problem with initialization in java, following code give me compile error called : expected instanceInt = 100; but already I have declared it. If these things relate with stack and heap stuff please explain with simple terms and I'm newbie to java and I have no advanced knowledge on those area
public class Init {
int instanceInt;
instanceInt = 100;
public static void main(String[] args) {
int localInt;
u = 9000;
}
}
According to the Java Language Specification:
However, the statement
is none of those things, therefore it is not allowed as part of a class body. What you need to do is this:
This is allowed because it is a field declaration that includes a variable initializer.
Put it in an initializer block.
Or simply initialize while declaring it:
References:
You need to do :
If it was
static
you could initialize in astatic
block.You can not have a separate statement to assign values to class members in the declaration area. You have to do this from a function, typically a class method.
For your case, consider doing the assignment as soon as you declare.
You can't use statements in the middle of your class. It have to be either in a block or in the same line as your declaration.
The usual ways to do what you want are those :
The initialization during the declaration
Usually it's a good idea if you want to define the default value for your field.
The initialization in the constructor block
This block can be used if you want to have some logic (if/loops) during the initialization of your field. The problem with it is that either your constructors will call one each other, or they'll all have basically the same content.
In your case I think this is the best way to go.
The initialization in a method block
It's not really an initialization but you can set your value whenever you want.
The initialization in an instance initializer block
This way is used when the constructor isn't enough (see comments on the constructor block) but usually developers tend to avoid this form.
Resources :
On the same topic :
Bonus :
What does this code ?
The answer