Y
Y
Ytsu Ytsuevich2014-12-19 13:32:51
Java
Ytsu Ytsuevich, 2014-12-19 13:32:51

Java. What is the value of the variable after the declaration?

static int staticVar;
void someMethod() {
    int locVar;
    // мое мнение таково
    // и в staticVar и в locVar
    // значения 0
}

Am I thinking right?
Perhaps not so, because in C ++ by default in the "garbage" variable, the remnants of the RAM cells (if I'm wrong, let me know).
But in a static variable, I can pull out the value, but the compiler does not give it with a local one.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nikolai Pavlov, 2014-12-19
@gurinderu

In the case of a static variable, it will be 0. In the case of the second, there will be a compilation error when accessing this variable. As you have written locVar will not be formally defined at all.

B
bimeg, 2014-12-19
@bimeg

Once upon a time, someone decided that an uninitialized local variable is a probable bug in the program. And they were forbidden to use them without explicit initialization.
All default values ​​of fields are explicitly written in the spec (for int it is 0).

L
lo-fi, 2014-12-19
@hrls

If my memory serves me, then only the fields of the class (heap) are initialized to zero, but not the variables in the method (stack). Those. in the example above, the static variable will be initialized to zero, unlike the local variable, because static variable - the essence is a field in a class instance.
Well, it is clear that it is impossible to find out the value of a local variable without initialization - the compiler will not miss it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question