Page 1 of 1

Intialisation of default vals

Posted: Fri May 29, 2020 4:12 am
by saregg

Code: Select all

public class Test 
	{ 
		public static void main(String[] args) 
			{
				 Boolean [] arr = new Boolean[ 2 ]; 
				 List<Boolean> list = new ArrayList<>(); 
				 list.add(arr[ 0 ]); 
				 list.add(arr[ 1 ]);
				 }
		}
The above code adds null to list as default value for Boolean is null and as its a reference and so the def vals are assigned, but the local variables shouldnot be initialised with default vals ? how it happens here ?

Re: Intialisation of default vals

Posted: Fri May 29, 2020 5:18 am
by admin
This code is not initializing any local variable with default values. The variable arr is being explicitly assigned an array object.

Whenever you create an array object, its elements are always initialized with default values. Just like fields of an instance of any class.