Java arrays and complex data types?

int[ ] i = new int[5];

=> I have declared a reference variable i that points to an object (an array). The object (array) contains five int variables.

String[ ] s = new String[5];

=> … declares a reference variable s that points to an object (array). The object (array) contains 5 string variables.

a) Do I understand this correctly?

So now I have written a class myself

public class MyClass…

Well

MyClass[ ] myC = new MyClass[5];

=> I have created 5 reference variables

myC = new MyClass( );

I reserve memory for the 5 objects that I can reference using myC[…].

b) Why do I have to go this route if I wrote the class myself? Why is it not sufficient in this case to simply

MyClass[ ] myC = new MyClass[5]; to write?

1 vote, average: 1.00 out of 1 (1 rating, 1 votes, rated)
You need to be a registered member to rate this.
Loading...
Subscribe
Notify of
2 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
orochi02
1 year ago

(a)

first so far correctly

second almost . you confuse variables and references.

reference = abstraction of a pointer on objects (can sometimes be used synonymously to objects)

Pointer = shows the address of a specific storage region (in java case objects)

variable = in the code quasi a box where the programmer references stores or primitive data types (numbers, truthful, letters). you can access by name

so if you start a string array, it does not contain reference variables but references. Furthermore, these are set to the NULL reference because the array does not contain any correct strings. int array is not the case because primitive data cannot be set to NULL and instead set to a default value (in your case 0)

(b)

no idea what you want, but your supplement is true. in your example a mistake would have occurred

Tyldu
1 year ago

(a)

 String[] s = new String[5];

s is not an array of strings but an array of reference variables, which in turn shows on instances of string classes.

(b)

I don't understand what you mean. between string arrays and arrays of own objects, there is actually no big difference, even if the string class has its peculiarities.