madan
madan

Reputation: 171

Why doesn't java allow to declare and initialize a class-level variable in two different steps

Can anyone explain me,

  1. Why doesn't java allow to declare and initialize a class-level variable in two different steps.
  2. Why can't I declare a public variable in public method.
public class Class10 {
    public String i=" ";
    public String j;
    j=" "; //Does-Not work

    public void method(String[] args){ 
        public String k=" "; // Does-not work  
        j=" ";
    }
}

Upvotes: 0

Views: 203

Answers (1)

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31225

1) It is possible with the right syntax (but discouraged) :

public class Class10 {
  public String i=" ";
  public String j;
  {j=" ";} //This is called an "Instance initialization block"
  //It would be better to do it in a constructor.

2) It does not make sense :

  • If you want it to be visible to others methods, it should be an attribute.
  • If you want it to be local to the methods, it should be a variable.

Upvotes: 4

Related Questions