New in classes | Sololearn: Learn to code for FREE!


New in classes

Hi array primitive data types are crated like: Scores= new double[10]; If we create my class and definition as array Must this create each individual in for like? For(int i=0; myclass.length; i++) Myclass[i]=new myclass();

4/11/2021 6:48:30 AM


5 Answers

New Answer


First, your example is not complete. Array creation involves two steps: declaration and initialization. Declaration: you specify the type and the variable name double[] scores; Initialization: you specify the size of the array scores = new double[10]; At this point, the values of a primitive array are also initialized as 0 (or in this case, 0.0 because it is double type) And of course you can combine declare+init in a single step: double[] scores = new double[10]; When you use classes, it is exactly the same, only the initial values of each element is null. Then, you can use a for loop to create a new instance at each array element. Person[] people = new Person[10];


Hadi Yes like this


Hi Tibor so in primitive data is not necessary to create a new instance at each array element? why?


Primitives are not objects in Java. You cannot instantiate them. They are just values. They don't have any methods. And they cannot be null - so the default value of a primitive type is 0.