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;
}
}
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