Arrays not initialized

Asked

Viewed 34 times

0

After the statement

int[ ] a;

what is stored in the variable a? null or an undefined value, where a cannot be used until something is assigned to it?

  • 2

    If it’s an object field, it’s null. If it is variable, it is undefined and will generate an error trying to use a before it receives deterministically some value

  • Related (Java behaves the same way in this respect): https://answall.com/q/217862/64969

  • @Jeffersonquesado mesmo o array sendo de tipo primitivo?

1 answer

0

It depends on where this statement was made. If it is an attribute, the value is null. Attributes in java receive a default boot value. Any attribute that type is a class will be initialized as null. Primitive types will be initialized with a default value that is defined by java, for example, int variables will be initialized with 0.

However, if this statement is made in a method, in that case the variable will be in an uninitialized state. If you try to use the variable then the compiler will complain that the variable was not initialized.

  • But I have an array [] not initialized. How can I have null if it is an array of integers?

  • @find83 Arrays in java are also objects. The elements you can put into the array that are integers. The array itself is an object. The reference to this object is null. Once the array is instantiated, you can add integers to it.

Browser other questions tagged

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