Java Lesson 8: Arrays

Hello everybody,

It’s Michael, and today’s Java post will be about arrays. But what exactly do arrays do in Java?

Arrays are basically a list of variables that are referred to by a common name. Here’s an example:

Florida Ohio Georgia Mississippi Texas Montana

This is an array of states, which I will call states.

You can make arrays for variables of any Java type, including:

  • int
    • And any numerical type for that matter (i.e. double, float)
  • char
  • boolean
  • String

However, you cannot have several variable types in an array (so no mixing String elements with int elements). For instance, if you wanted to include 737 Down Over ABQ in your array, the 737 would have to be a String in order to make the array work (assuming Down Over ABQ are all String).

Now let me demonstrate a simple array program:

package javalessons;

public class JavaLessons
{

public static void main(String[] args)
{
String [] stateCaps = {“Helena”, “Salem”, “Tallahassee”, “Atlanta”, “St.Paul”, “Pierre”, “Columbus”, “Providence”};
System.out.println(stateCaps[4]);
}
}

And here are two sample outputs (using a different index for each array):

run:
Tallahassee
BUILD SUCCESSFUL (total time: 0 seconds)

run:
St.Paul
BUILD SUCCESSFUL (total time: 0 seconds)

The first thing I did in the program is to create my array declaration-String [] stateCaps = {"Helena", "Salem", "Tallahassee", "Atlanta", "St.Paul", "Pierre", "Columbus", "Providence"}. The point of the array declaration is to create an array and POSSIBLY fill it with elements.

I say POSSIBLY because there are three ways I can go about create my array and filling it with elements. Here are some possibilities:

  • Do what I did in the aforementioned program, which is to create the array and the elements in the same line of code (separated by an equals sign)
  • Create the array and allocate space to the array in the same line, which would mean I would have written String [] stateCaps = new String [8] to create a String array with 8 values. Meanwhile, I would have added elements in 8 separate lines of code, starting with stateCaps[0]="Helena" and continuing on until I fill the array.
  • Create a for loop. More on that later in this post.

OK, here’s something I want to mention about that second bullet point. Each element in an array is called an index (plural: indices). However, the first index in an array is [0] not [1] since array indices are counted starting from 0, not 1. So the first index in an array is [0], the second index is [1], the third index is [2], and so on.

In each of my outputs, I chose a different index, and thus got a different output each time. The first output-Tallahassee-corresponds to index 2-or the third element in the array, which is “Tallahassee”. The second output-St.Paul-corresponds to index 4-or the fifth element in the array, which is “St.Paul”.

Next, remember how I mentioned that you could use a random number generator in arrays in my previous post? Here’s how you can do that (using a different array):

package javalessons;
import java.util.Random;

public class JavaLessons
{

public static void main(String[] args)
{
String [] cartoons = {“Family Guy”, “Spongebob”, “Simpsons”, “South Park”,
“Archer”, “Daniel Tiger’s Neighborhood”, “Arthur”, “Looney Tunes”,
“Big Mouth”, “Rick & Morty”};
Random gen = new Random ();
int index = gen.nextInt(9);

System.out.println(cartoons[index]);
}
}

And here are two sample outputs:

run:
Big Mouth
BUILD SUCCESSFUL (total time: 0 seconds)

run:
Spongebob
BUILD SUCCESSFUL (total time: 2 seconds)

In this program, I first imported java.util.Random, which is what you need to do if you plan on using a random number generator in your program. I also remembered to create Random and int variables, which you need to do in order to have a random number generator handy and, in the case of the int variable, set the upper limit for the random number generator. In this case, the upper limit for my generator is 9, since there are 10 elements in my array (remember array elements start counting from 0). Had I used 10 as the upper limit, there is a chance I would have gotten an error message since there is no index 10. I then created an array-cartoons-and filled it with 10 elements (10 American cartoons).

For my output, I asked the program to print out a random element each time I run the program. In my first sample output, index 8 was displayed (corresponding to Big Mouth) while in my second output, index 1 was displayed (corresponding to Spongebob).

Now let me show you how to fill in an array using a for loop:

package javalessons;

public class JavaLessons
{

public static void main(String[] args)
{
int [] multiples = new int [15];

for (int i = 0; i <= 14; i++)
{
multiples[i]=i*8;
}

System.out.println (multiples[3]);
}
}

And here are two sample outputs (each using a different index):

run:
24
BUILD SUCCESSFUL (total time: 1 second)

run:
48
BUILD SUCCESSFUL (total time: 0 seconds)

This program demonstrates a very simple way to fill in an array using a for loop. I used my for loop to fill in my array with multiples of 8, hence the I*8. I first created my array in the line directly above the for loop, then I created the for loop to fill my array with elements. In my for loop, I started my counter at 0 (remember that array indices start from 0), asked it to stop at 14 (since I will have 15 elements in my array), and asked it to increment by 1 after each iteration.

  • I’ll admit that the new int [15] may seem redundant since I already determined that my loop will have 15 iterations (and thus 15 elements).

My sample outputs printed indexes 3 and 6 (the 4th and 7th elements respectively), which correspond to the numbers 24 and 48. Remember that since I started this loop with 0, the first element will be 0, since 0 times 8 is 0.

Last but not least, I will introduce the concept of two dimensional arrays using a combination of a for loop and a random number generator. Here’s a sample program:

package javalessons;
import java.util.Random;

public class JavaLessons
{

public static void main(String[] args)
{
int [] [] twoDim = new int [6][6];
Random gen = new Random ();
int boundary = gen.nextInt(35);

for (int i = 0; i <= 5; i++)
{
for (int j = 0; j <= 5; j++)
{
twoDim [i][j] = boundary;
}
}

System.out.println (twoDim[2][3]);
}
}

And here are two sample outputs:

run:
24
BUILD SUCCESSFUL (total time: 0 seconds)

run:
1
BUILD SUCCESSFUL (total time: 1 second)\

The process of working with two-dimensional arrays (or other multidimensional arrays for that matter) is a little different than the process of working with one dimensional arrays. First of all, you would need a nested for loop (or a for loop within a for loop) to traverse through (and possibly fill in) your array. Second, you would need two squares [] [] to initialize the array as opposed to just one [].

  • You don’t always need a nested for loop to fill in a two dimensional array. Plus if you are dealing with non-numerical elements like String, a loop isn’t very practical to use.
  • Here’s another way to fill in a 2-dimensional array, using String elements:
    • Let’s say our array is 3 by 3.
    • This is another way to fill in elements:
      • String [][] cities = {{"Fort Collins", "Mentor", "Miami"}, {"Bozeman", "Annapolis", "Pittsburgh"}, {"Boston", "Omaha", "Manhattan"}}
      • Since this array is 3 by 3, we would have 3 groups of 3 elements each.
  • Here’s a handy rule when it comes to two dimensional arrays:
    • For an array with dimensions of [x][y], create x groups of y elements each.

The “indexes start at 0” rule applies here. Here’s the index structure for the 6 by 6 array I created above:

Screen Shot 2019-04-25 at 4.21.52 PM

The first index would be [0][0] while the final index would be [5][5]. If you wanted to select the element on the second row and fourth column, that would correspond to [1][3].  Remember that the row always comes first, followed by the column.

In my sample outputs,  I selected indexes [2][3] and [3][0], which printed out 24 and 1, respectively. Keep in mind that even if you use the same indexes, you might get a different output each time due to the use of the random number generator in this program. However, I set the upper limit to 35, which means the number printed will always be between 0 and 35.

One last thing I want to address is that you can create arrays that are more than two dimensions. For instance, if you wanted to make a 4-dimensional array, you would include 4 squares-[][][][]. As to how many elements an array like this can hold, just find the product of all of the numbers in the dimension brackets (which would be to the right of the equals sign). For instance, if you have a 4-dimensional array like this-String [][][][] names = new String [3][9][2][4]-multiply the numbers in the dimension brackets to see how many elements this array will hold (3*9*2*4=216; this array will hold 216 elements).

Thanks for reading,

Michael

 

Leave a Reply