Page 1 of 1

Array default values for Instance Variables Vs Local Variables

Posted: Sun Oct 10, 2021 12:29 am
by abashdesh
Are the array default values for local variables same as those for instance variables?
Asking this as generally Instance Variables get default values whereas Local Variables need to be explicitly initialised.
Hence was curious if the same is true for Array values or Array values would be an exception to this?

Re: Array default values for Instance Variables Vs Local Variables

Posted: Sun Oct 10, 2021 1:02 am
by admin
If by "array values", you mean the contents of an array object then there is no difference between an instance and local array object. It is like any other Java object. It doesn't matter where you create an object, the fields of an object are always initialized (as per default values/instance blocks/constructor). So, all elements of an array object will always be initialized to their default values.

The array variable is also just like any other variable. The rules of initialization of local and instance variables apply to array variables as well. So, a local array variable will not be initialized automatically.

You should write a sample test program and check it out.