Student: Professor, I’m unsatisfied with what we’ve learned. I feel like you’re not telling the whole story.
Prof: Oh? In what way?
Student: Well, we talk about records for storing students, but not a whole list of them. Surely things like TSS don’t have a different definition for every student. And there was an example with a
ShoppingItem or something like that, but it only had one item in it. When you shop online your cart is a whole bunch of different items. And a lot of pictures you might want to make have lots of little pieces, like a lot of stripes or something like that. I don’t see at all how you’d do that with what you’ve shown me.Prof: Ah, you want to create collections or sequences of values of the same type!
Student: Uh, yeah? Sure, I guess, that sounds kind of right.
Prof: There are a lot of ways to do that in Java, but arrays are one really common tool. Here’s an array in Java, and how to access its pieces:
Student: OK, so the array itself is stored in
names, and you can use the [] to look it up? And indexes start at 0?Prof: That’s right. We call
array[i] array indexing, and i has to be an int that is between 0 and the size of the array minus 1Student: Why minus 1?
Prof: Well, how many elements are in that array (we call each value in an array an element)?
Student: Six…
Prof: And what’s the index of the last one?
Student: You made a definition for it, it was 5… oh! I see.
Practice
Here is an array of doubles:
double[] temps = { 72.5, 68.0, 75.2, 80.1 };Which of these are valid ways to index temps? Select all that apply.
temps[0]temps[3]temps[4]tempshas 4 elements, so the last index is3.temps[-1]Indexes start at0; there is nothing before it.temps[1.0]An index has to be anint, even when the elements aredoubles.