Why do local variables not receive default values from the Java compiler or JVM?

Asked

Viewed 142 times

5

Why the compiler assigns values default for attributes but not for local variables?

public class Teste{            
    int a;

    public void metodo() {
        int b;
        System.out.println(a);
        System.out.println(b);
   }
}

1 answer

6


First, what you call an attribute is actually a field.

The simplest answer is that the creators of language decided this way and they don’t have to justify why they did it. We can try to think of motivations.

I imagine you understand that it’s safer to give a standard value to a field so you don’t run the risk of picking up junk in your memory. They could have done the same with local variables, and in a way they did.

Try declaring the variable and not using. Try assigning a separate value after declaring no value. The real problem is to use a variable without giving a specific value. In those cases there would be a needless boot, unless the compiler did an optimization, which I think it should do, but perhaps they only realized the usefulness of it later and did not want to risk changing the semantics and breaking some existing code or confusing the programmer.

It was considered that it is almost always a logic error not to initialize the variable so they always preferred to consider an error. I think it should be at most one Warning. I find it undesirable but not mandatory. This choice probably decreases the amount of bugs in a code, so it seemed an interesting decision.

Probably they should have chosen not to require in all cases, including instance variables, but then the field would have to be initialized in the constructor obligatorily, which would be a little weird, and in many cases would require a constructor that today is not required.

With this habit of people using getters and setters may not want to put in the builder (is wrong, and I won’t even mention that they use these methods in exaggeration), which would happen if access to the field happened before using the Setter? It would be too complicated, or impossible for the compiler to guarantee that this would not occur, then it could give error or it would have to decrease flexibility. In local code it is much simpler to determine if the variable was used without initializing. Algorithm has clear and defined order, data structure has no.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.