Question

I'm working my way (slowly, but surely) through a book:

Introduction to Java Programming, 10th edition, Comprehensive, by J. Liang (ISBN10: 0133761312)

It explains the idea of a reference variable in a way that I understand. However, the idea doesn't seem intuitive to me. This makes me think that I'm missing something in my understanding:

"The declaration of an array variable does not allocate any space in memory for the array. It creates only a storage location for the reference to an array."

However, if I do:

double[] MyList;

Have I not created a variable MyList of size double? When I do that, my understanding is that space in memory of size double is created, the same way that of a primitive data type (which, from my understanding, should be different).

Another thing I am having trouble with:

"You cannot assign elements to an array unless it has already been created"

Why is there an option of declaring an array, instead of creating it at once? To both create and declare an array I have to do:

double[] myList = new double[10]'

Why can't it be like:

double[10] myList;

Why do I have to use 'new'? Why do I have to tell Java, again, that it is a type double when I have already specified it? I don't see this boondoggle in C++, Python.

One more thing:

"An array variable that appears to hold an array actually contains a reference to that array"

What is the distinction between the two? Why does it have to be that way? I've never encountered this in other languages. Everything else is clear except this small section.

Was it helpful?

Solution

Have I not created a variable MyList of size double?

With double[] MyList;, you've merely created a variable that can later refer to an array of doubles. You haven't created any doubles. It's essentially a pointer.

Why is there an option of declaring an array, instead of creating it at once?

Sometimes you won't want to create it at once. For example, if you create a class where the constructor accepts an array and refers to it with a variable, you won't want to create it, since it's already created.

Why do I have to use 'new'?

Because new is the way to create an object.

Why do I have to tell Java, again, that it is a type double when I have already specified it?

Because that's what's required with new. The syntactical sugar could have been added, but it wasn't.

What is the distinction between the two? Why does it have to be that way? I've never encountered this in other languages.

That's strange. You mention C++ as something you've experienced, yet you don't seem to have dealt with pointers, which are essentially what nonprimitive Java variables are.

Licensed under: CC-BY-SA with attribution
scroll top