Initialization of variables in Java

Asked

Viewed 32 times

2

Good night Folks!

I’m learning java, and if you can help me with that question,...

I saw it in a course that I’m doing, in a book that I’m reading, and on websites where I researched this assuming the same statement, which is more or less this: "Primitive type instance variables are initialized by default, variables of byte, char, short, int, long, float and double types are initialized as 0" - Devmedia(https://www.devmedia.com.br/tipos-de-dados-por-valor-e-por-referencia-em-java/25293)

However, this code shows me an error:

int a;
System.out.println("Valor de a: " + a);

In the case of the eclipse, he accuses this error:

The local variable a may not have been initialized

If the default value of numeric primitive types is zero, why do I need to explicitly initialize a variable of this type? In the case of this example:

int a = 0;

Pure javac also accuses this same error. You know why the compiler behaves this way ?

  • The compiler thus behaves in compliance with the express determination of the Java specifications, which determine that For each access to a local variable x, x must have been initialized before access, otherwise a build error will occur [my translation, adapted]. Source: https://docs.oracle.com/javase/specs/jls/se7/html/jls-16.html

1 answer

2


As in the very description you posted, just the instance variables, also called attributes, have default values.

Instance variables would be variables defined at class level, not at the scope of a function. For example:

class Saldo {
    public int reais;    // <-- atributo, possui valor padrão
    public int centavos; // <-- atributo, possui valor padrão
}

If I create an instance of that class var saldo = new Saldo(), i don’t need to manually initialize these attributes reais and centavos, they will have the default value 0.

However for a variable declared in a local scope of a function, it needs to be initialized before being accessed, as in its own example:

public static void main() {
    int i = 0; // <-- variável local, não possui valor padrão.
}
  • Um I got it, really. I did the test here and that’s the way it goes. Thank you very much friend!

Browser other questions tagged

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