Java Reference
In-Depth Information
Array s are probably the simplest of these piles of data. Array s are mostly used
when you have a small list of values that you want to create directly in code
and then use. Array s are fixed length —you can't grow or shrink them. They
aren't as useful if you need to add, delete, and move things around a lot in
the list (for that, we'll use an ArrayList , which is up next).
You'll usually employ an Array when you want to access its values by an index,
or run through all the values and do something to them with a for loop.
You can declare an Array using square brackets, and load it up with values
using braces. Here's an example of a list of String s:
String[] grades = { "A" , "B" , "C" , "D" , "F" , "Inc" };
You can access individual elements from the list using brackets:
String yourGrade = grades[2];
In this case, yourGrade will be a C. Hey, wait a minute—why is that a C, and
not a B? That's because Java, like the C language and its predecessors, starts
counting at 0. The first element in any list is 0. The second is 1. The third is
2, and so on. You'll get used to it. Think of accessing the first element as
adding 0 to the start of the list, and the second element as adding 1 to the
start of the list.
That's exactly how an Array is stored in memory in the computer: just a bunch
of values all in row. Since the first entry in the Array is right at the start of the
memory, it has no offset. The second value is one over from the start, the
third is two over from the start, and up you go.
You can tell the length of an Array by looking at its length field (note this is not
a function call; there are no parentheses):
int numGrades = grades.length;
numGrades will be set to 6. That means that each of the six values will be
numbered 0 to 5. The index of the last element is always length-1 (in this case,
6-1, or 5).
Instead of sticking in all the values hard-coded as we did, you could make
an Array that's a fixed size, then stuff some values into it. Here's what that
looks like with a list of int values:
int[] quizScores = new int [5];
quizScores[0] = 85;
quizScores[1] = 92;
quizScores[2] = 63;
 
 
Search WWH ::




Custom Search