+ 3

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();

11th Apr 2021, 6:48 AM
Hadi
Hadi - avatar
6 odpowiedzi
+ 5
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];
11th Apr 2021, 7:37 AM
Tibor Santa
Tibor Santa - avatar
11th Apr 2021, 7:25 AM
A͢J
A͢J - avatar
+ 1
Hi Tibor so in primitive data is not necessary to create a new instance at each array element? why?
13th Apr 2021, 4:47 AM
Hadi
Hadi - avatar
+ 1
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.
13th Apr 2021, 5:15 AM
Tibor Santa
Tibor Santa - avatar
0
Nice!
15th Sep 2021, 8:25 PM
PARMEZAN
0
Thanks for sharing such a helpful instruction
26th Aug 2023, 9:39 AM
goorin