 Introduction to Arrays

 A Series of Similar Items

 Introduction

Imagine you want to create a program that would use a series of numbers. In algebra, we represent such a series as follows: X1, X2, X3, X4, X5. You can also represent a list of names as follows:

 Alex Gaston Hermine Jerry

So far, to use a series of items, we were declaring a variable for each of them. If the list was made of numbers, we would declare variables for such numbers as follows:

```public class Exercise {
public static void main(String[] args) {
double number1 = 12.44;
double number2 = 525.38;
double number3 = 6.28;
double number4 = 2448.32;
double number5 = 632.04;
}
}```

Instead of using individual variables that share the same characteristics, you can group them in an entity like a regular variable. This group is called an array. Therefore, an array is a series of items of the same kind. It could be a group of numbers, a group of cars, a group of words, etc but all items of the array must be of the same type. Practical Learning: Introducing Arrays
1. Start NetBeans
2. Create a Java Application named VideoCollection1
 Array Creation

Before creating an array, you must first decide about the type its items will be made of. This information allows the compiler to know how much space each item of the group will require. This is because each item of the group will occupy its own memory space, just like any of the variables we have used so far.

After deciding about the type of data of each item that makes up the series, you must use a common name to identify them. The name is simply the same type of name you would use for a variable as we have used so far. The name allows you and the compiler to identify the area in memory where the items are located.

Thirdly, you must specify the number of items that will constitute the group. For the compiler to be able to allocate an adequate amount of space for the items of the list, once it knows how much space each item will require, it needs to know the number of items so an appropriate and large enough amount of space can be reserved. The number of items of an array is included in square brackets, as in .

An array is considered a reference type. Therefore, an array requests its memory using the new operator. Based on this, to declare an array is, you can use the following formula:

`DataType[] VariableName = new DataType[Number];`

or:

`DataType VariableName[] = new DataType[Number];`

In these formulas, the DataType factor can be one of the types we have used so far (char, int, float, double, String, etc). It can also be the name of a class as we will learn. Like a normal variable, an array must have a name, represented in our formula as VariableName. The square brackets on both side of the assignment operator are used to let the compiler know that you are declaring an array instead of a regular variable. The new operator allows the compiler to reserve memory. The Number factor is used to specify the number of items of the list.

Based on the above formula, here is an example of an array variable:

```public class Exercise {
public static void main(String[] args) {
double[] numbers = new double;
}
}```

As seen in our second formula, in the Java language (unlike many other languages, including C/C++ or C#), you can place the left square brackets either after the data type or after the name of the variable. Therefore, both of the following declarations are correct:

```public class Exercise {
public static void main(String[] args) {
double[] firstNumbers = new double;
double secondNumbers[] = new double;
}
}``` Practical Learning: Creating an Array
1. To create arrays, change the Main.java file as follows:

 ```package videocollection1; public class Main { public static void main(String[] args) { long[] shelfNumbers = new long; String[] titles = new String; String[] directors = new String; int[] lengths = new int; String[] ratings = new String; double[] prices = new double; } }```
2. Save the file
 The Array Class

To provide extensive support for arrays, the Java language is equipped with a class named Array, which is defined in the java.util package. Whenever you create an array, it automatically becomes an object of type Array. Consequently, any array you create inherits the fields and methods of the Array class and you can directly use them on your array variable.

Because there are so many members in the Array class, we will review each as its becomes necessary.

 The Length of an Array

In most operations that involve an array, you will need to know the number of the components in the series. To provide this information, the Array class is equipped with a field named length, which is of type int.

 Initializing an Array

 Introduction

When creating an array, you can specify the number of items that make up its list. Each item of the series is referred to as a component of the array. Once the array has been created, each one of its components is initialized with a 0 value. Most, if not all, of the time, you will need to change the value of each component to a value of your choice. This is referred to as initializing the array.

An array is primarily a variable; it is simply meant to carry more than one value. Like every other variable, an array can be initialized. There are two main techniques you can use to initialize an array. If you have declared an array as done above, to initialize it, you can access each one of its members and assign it a desired but appropriate value.

In algebra, if you create a series of values as X1, X2, X3, X4, and X5, each member of this series can be identified by its subscript number. In this case the subscripts are 1, 2, 3, 4, and 5. This subscript number is also called an index. In the case of an array also, each member can be referred to by an incremental number called an index. A Java (like most C-based languages including C++ and C#) array is zero-based. This means that the first member of the array has an index of 0, the second has an index of 1, and so on. In algebra, the series would be represented as X0, X1, X2, X3, and X4.

In Java, the index of a member of an array is written in its own square brackets. This is the notation you would use to locate each member. One of the actions you can take would consist of assigning it a value. Here is an example:

```public class Exercise {
public static void main(String[] args) {
double[] numbers = new double;

numbers = 12.44;
numbers = 525.38;
numbers = 6.28;
numbers = 2448.32;
numbers = 632.04;
}
}```

Besides this technique, you can also initialize the array as a whole when declaring it. To do this, remove the dimension in the square brackets. Then, on the right side of the declaration, before the closing semi-colon, type the values of the array members between curly brackets and separated by a comma. Here is an example:

```public class Exercise {
public static void main(String[] args) {
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
}
}```

Although the second square brackets are empty, the compiler can figure out the number of items. Practical Learning: Initializing Some Arrays
1. To initialize the arrays, change the file as follows:

 ```package videocollection1; public class Main { public static void main(String[] args) { long[] shelfNumbers = new long[] { 2985, 8024, 5170, 1304, 9187, 1193, 3082, 8632, 4633, 9623 }; String[] titles = new String[] { "The Distinguished Gentleman", "A Perfect Murder", "Chalte Chalte", "Ransom", "Not Another Teen Movie", "Madhubaala", "Get Shorty", "Sneakers", "Born Invincible", "Hush" }; String[] directors = new String[] { "Jonathan Lynn", "Andrew Davis", "Aziz Mirza", "Ron Howard", "Joel Gallen", "Shivram Yadav", "Barry Sonnenfeld", "Paul Alden Robinson", "Unknown", "Jonathan Darby" }; int[] lengths = new int[] { 112, 108, 145, 121, 100, 0, 105, 126, 90, 96 }; String[] ratings = new String[] { "R", "R", "N/R", "R", "Unrated", "N/R", "R", "PG-13", "N/R", "PG-13" }; double[] prices = new double[] { 14.95D, 19.95D, 22.45D, 14.95D, 9.95D, 17.50D, 9.95D, 9.95D, 5.95D, 8.75D }; } }```
2. Save the file
 Other Techniques of Initializing an Array

We have initialized our arrays so far with values we specified directly in the curly brackets. If you have declared and initialized some variables of the same type, you can use them to initialize an array. Here is an example:

```public class Exercise {
public static void main(String[] args) {
double Area = 97394.2204D;
double Distance = 982.84D;
double Level = 27D;
double Quantity = 237957.704D;

double[] measures = new double[] { Area, Distance, Level, Quantity };
}
}```

The values can also come from constant variables. Here is an example:

```public class Exercise {
public static void main(String[] args) {
final double PI = 3.141592653;
double squreRootOf2 = 1.414D;
double e = 2.718D;
final double RADIUSOFEARTH = 6370; // km
double ln2 = 0.6931;

double[] measures = new double[] { PI, squreRootOf2, e,
}
}```

The values can also come from calculations, whether the calculation is from an initialized variable or made locally in the curly brackets. Here is an example:

```public class Exercise {
public static void main(String[] args) {
final double DESNSITYOFWATER = 1000; // kg/m3 ;
double massOfEarth = 5.98 * 10e24; // kg
double earthMoonDistance = 2.39 * 10e5; // miles

double measures[] = new double[] {
DESNSITYOFWATER, 9.30 * 10.7, massOfEarth, earthMoonDistance
};
}
}```

The rule to follow is that, at the time the array is accessed, the compiler must be able to know exactly the value of each member of the array, no guessing.

All of the arrays we have declared so far were using only numbers. The numbers we used were decimal constants. If the array is made of integers, you can use decimal, hexadecimal values, or a combination of both. Here is an example:

```public class Exercise {
public static void main(String[] args) {
long red = 0xFF0000;
long someColor = 0x800000;

long[] colors = new long[] { 2510, red, 818203, someColor, 0xF28AC };
}
}```

An array can have types of values of any of the data types we have used so far. The rule to follow is that all members of the array must be of the same type. For example, you can declare an array of Boolean values, as long as all values can be evaluated to true or false. Here is an example:

```public class Exercise {
public static void main(String[] args) {
boolean[] fullTimeStudents = new boolean[] { true, true, true,
false, true, false };
}
}```

As stated already, each value of a Boolean array must be evaluated to true or false. This means that you can use variables or expressions as members of the array. Here is an example:

```public class Exercise {
public static void main(String[] args) {
double house1Value = 460885.85D;
double house2Value = 685770.00D;

boolean comparisons[] = new boolean[] { 25 < 10,
house1Value == house2Value,
true };
}
}```

As we will see when studying arrays and classes, you can use this technique to create an array of dates, times, or date and time values.

 Accessing the Members of an Array

 Introduction

After initializing an array, which means after each of its members has been given a value, you can access a member of the array to get, to manipulate, or even to change, its value. To access a member of the array, you use the square brackets as we saw above. As done for normal variables, one of the reasons for accessing a member of an array would be to display its value, which can be done by passing it to System.out.print() or to System.out.println(). Here is an example:

```public class Exercise {
public static void main(String[] args) {
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

System.out.print(numbers);
}
}```

This would produce:

`2448.32`

In the same way, you can access 1, a few or all members of the array. Here are examples:

```public class Exercise {
public static void main(String[] args) {
double numbers[] = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

System.out.println(numbers);
System.out.println(numbers);
System.out.println(numbers);
System.out.println(numbers);
System.out.println(numbers);
}
}```

This would produce:

```2448.32
12.44
6.28
632.04
525.38```

When accessing a member to display its value, you can also use System.out.printf(). To do this, pass the appropriate % expression to the first part of the method, and access the right member in the second part, based on its index. Here is an example:

```public class Exercise {
public static void main(String[] args) {
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

System.out.printf("%f", numbers);
}
}``` Practical Learning: Using the Members of an Array
1. To show the values of a member of an array, change the Main.java file as follows:

 ```package videocollection1; public class Main { public static void main(String[] args) { long[] shelfNumbers = new long[] { 2985, 8024, 5170, 1304, 9187, 1193, 3082, 8632, 4633, 9623 }; . . . No Change System.out.println("==============================="); System.out.println("Video Information"); System.out.println("-------------------------------"); System.out.println("Shelf #: " + shelfNumbers); System.out.println("Title: " + titles); System.out.println("Director: " + directors); System.out.println("Length: " + lengths + " minutes"); System.out.println("Rating: " + ratings); System.out.printf("Price: %.2f\n", prices); System.out.println("==============================="); } }```
2. Execute the application and test it. Here is an example:

 ```=============================== Video Information ------------------------------- Shelf #: 8024 Title: A Perfect Murder Director: Andrew Davis Length: 108 minutes Rating: R Price: 19.95 ===============================```
 For an Indexed Member of the Array

We saw how you can use the square brackets to access each member of the array one at a time. That technique allows you to access one, a few, or each member. If you plan to access all members of the array instead of just one or a few, you can use the for loop. The formula to follow is:

`for(DataType Initializer; EndOfRange; Increment) Do What You Want;`

In this formula, the for keyword, the parentheses, and the semi-colons are required. The DataType factor is used to specify how you will count the members of the array.

The Initializer specifies how you would indicate the starting of the count. As seen in Lesson 8, this initialization could use an initialized int-based variable.

The EndOfRange specifies how you would stop counting. If you are using an array, it should combine a conditional operation (<, <=, >, >=, or !=) with the number of members of the array minus 1.

The Increment factor specifies how you would move from one index to the next.

Here is an example:

```public class Exercise {
public static void main(String[] args) {
double numbers[] = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

for (int i = 0; i < 5; i++)
System.out.println(numbers[i]);
}
}```

This would produce:

```12.44
525.38
6.28
2448.32
632.04```

In the above code, we knew the number of components in the array. Sometimes, this information will not be obvious. We saw already that the Array class is equipped with a field named length. You can use it in the second part of a for loop. Here is an example:

```public class Exercise {
public static void main(String[] args) {
double numbers[] = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

for (int i = 0; i < numbers.length; i++)
System.out.println(numbers[i]);
}
}```

When using a for loop, you should pay attention to the number of items you use. If you use a number n less than the total number of members - 1, only the first n members of the array would be accessed. Here is an example:

```public class Exercise {
public static void main(String[] args) {
double numbers[] = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

for (int i = 0; i < 3; i++)
System.out.printf("Number: %f\n", numbers[i]);
}
}```

This would produce:

```Number: 12.440000
Number: 525.380000
Number: 6.280000```

On the other hand, if you use a number of items higher than the number of members minus one, the program would produce an error (we saw that the compiler would throw an exception). Practical Learning: Using a for Loop
1. To use a for loop, change the Main.java file as follows:

 ```package videocollection1; public class Main { public static void main(String[] args) { . . . No Change System.out.println("==============================="); System.out.println("Video Information"); for (int i = 0; i < 10; i++) { System.out.println("==============================="); System.out.printf("Video %d\n", i + 1); System.out.println("-------------------------------"); System.out.println("Shelf #: " + shelfNumbers); System.out.println("Title: " + titles); System.out.println("Director: " + directors); System.out.println("Length: " + lengths + " minutes"); System.out.println("Rating: " + ratings); System.out.printf("Price: %.2f\n", prices); } System.out.println("==============================="); } }```
2. Execute the application to see the result:

 ```=============================== Videos Information =============================== Video 1 ------------------------------- Shelf #: 2985 Title: The Distinguished Gentleman Director: Jonathan Lynn Length: 112 minutes Rating: R Price: 14.95 =============================== Video 2 ------------------------------- Shelf #: 8024 Title: A Perfect Murder Director: Andrew Davis Length: 108 minutes Rating: R Price: 19.95 =============================== Video 3 ------------------------------- Shelf #: 5170 Title: Chalte Chalte Director: Aziz Mirza Length: 145 minutes Rating: N/R Price: 22.45 =============================== Video 4 ------------------------------- Shelf #: 1304 Title: Ransom Director: Ron Howard Length: 121 minutes Rating: R Price: 14.95 =============================== Video 5 ------------------------------- Shelf #: 9187 Title: Not Another Teen Movie Director: Joel Gallen Length: 100 minutes Rating: Unrated Price: 9.95 =============================== Video 6 ------------------------------- Shelf #: 1193 Title: Madhubaala Director: Shivram Yadav Length: 0 minutes Rating: N/R Price: 17.5 =============================== Video 7 ------------------------------- Shelf #: 3082 Title: Get Shorty Director: Barry Sonnenfeld Length: 105 minutes Rating: R Price: 9.95 =============================== Video 8 ------------------------------- Shelf #: 8632 Title: Sneakers Director: Paul Alden Robinson Length: 126 minutes Rating: PG-13 Price: 9.95 =============================== Video 9 ------------------------------- Shelf #: 4633 Title: Born Invincible Director: Unknown Length: 90 minutes Rating: N/R Price: 5.95 =============================== Video 10 ------------------------------- Shelf #: 9623 Title: Hush Director: Jonathan Darby Length: 96 minutes Rating: PG-13 Price: 8.75 ===============================```
 For Each Member in the Array

In a for loop, you should know the number of members of the array. If you do not, the Java language allows you to let the compiler use its internal mechanism to get this count and use it to know where to stop counting. To assist you with this, you can use another version of the for loop. The formula to follow is:

`for (ArrayType Identifier: ArrayName) Use the Identifier `

The for keyword, the parentheses, and the colon are required.

The first factor of this syntax, ArrayType is the same data type as the array (it can also be the name of a class as we will learn in when studying collections).

The Identifier factor is a name of the variable you will use. This name is used to represent each component of the array.

After the closing parenthesis, use the Identifier as you see fit. Like a for loop that accesses all members of the array, this other version is used to access each array member, one at a time. Here is an example:

```public class Exercise {
public static void main(String[] args) {
double numbers[] = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

for(double number: numbers)
System.out.printf("Number: %f\n", number);
}
}```

This would produce:

```Number: 12.440000
Number: 525.380000
Number: 6.280000
Number: 2448.320000
Number: 632.040000``` Practical Learning: Getting Each Component of an Array
1. Change the file as follows:

 ```package videocollection1; public class Main { public static void main(String[] args) { . . . No Change System.out.println("Video Collection"); for(String title : titles) System.out.println(title); } } ```
2. Execute the application to see the result

 ```Video Collection The Distinguished Gentleman A Perfect Murder Chalte Chalte Ransom Not Another Teen Movie Madhubaala Get Shorty Sneakers Born Invincible Hush```
 Selecting a Value From an Array

 Introduction

Because an array is a list of values, it can include items that are not useful in all scenarios. For example, having an array made of too many values, at one time you may want to isolate only the first n members of the array, or the last m members of the array, or a range of members from an index i to an index j. Another operation you may be interested to perform is to find out if this or that value exists in the array. One more interesting operation would be to find out what members or how many members of the array respond to this or that criterion. All these operations are useful and possible with different techniques.

 Using a for Loop

Consider the following program:

```public class Exercise {
public static void main(String[] args) {
short[] numbers = new short[] {
102, 44, 525, 38, 6,
28, 24481, 327, 632, 104 };

for (int i = 0; i < numbers.length; i++)
System.out.println("Number: " + numbers[i]);
}
}```

This would produce:

```Number: 102
Number: 44
Number: 525
Number: 38
Number: 6
Number: 28
Number: 24481
Number: 327
Number: 632
Number: 104```

Imagine you want to access only the first n members of the array. To do this, you can use an if conditional statement nested in a for loop. Here is an example that produces the first 4 values of the array:

```public class Exercise {
public static void main(String[] args) {
short[] numbers = new short[] {
102, 44, 525, 38, 6,
28, 24481, 327, 632, 104 };

for (int i = 0; i < numbers.length; i++)
if (i < 4)
System.out.println("Number: " + numbers[i]);
}
}```

This would produce:

```Number: 102
Number: 44
Number: 525
Number: 38```

You can use the same technique to get the last m members of the array. You can also use a similar technique to get one or a few values inside of the array, based on a condition of your choice. Here is an example that gets the values that are multiple of 5 from the array:

```public class Exercise {
public static void main(String[] args) {
short[] numbers = new short[] {
102, 44, 525, 38, 6,
28, 24481, 327, 632, 104 };

for (int i = 0; i < numbers.length; i++)
if (numbers[i] % 5 == 0)
System.out.println("Number: " + numbers[i]);
}
}```

This would produce:

`Number: 525` Practical Learning: Checking a Value From an Array
1. To check a value from an array, change the file as follows:

 ```package videocollection1; import java.io.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long[] shelfNumbers = new long[] { 2985, 8024, 5170, 1304, 9187, 1193, 3082, 8632, 4633, 9623 }; String[] titles = new String[] { "The Distinguished Gentleman", "A Perfect Murder", "Chalte Chalte", "Ransom", "Not Another Teen Movie", "Madhubaala", "Get Shorty", "Sneakers", "Born Invincible", "Hush" }; String[] directors = new String[] { "Jonathan Lynn", "Andrew Davis", "Aziz Mirza", "Ron Howard", "Joel Gallen", "Shivram Yadav", "Barry Sonnenfeld", "Paul Alden Robinson", "Unknown", "Jonathan Darby" }; int[] lengths = new int[] { 112, 108, 145, 121, 100, 0, 105, 126, 90, 96 }; String[] ratings = new String[] { "R", "R", "N/R", "R", "Unrated", "N/R", "R", "PG-13", "N/R", "PG-13" }; double[] prices = new double[] { 14.95D, 19.95D, 22.45D, 14.95D, 9.95D, 17.50D, 9.95D, 9.95D, 5.95D, 8.75D }; System.out.println("==============================="); System.out.println("Video Collection"); System.out.print("Shelf Numbers: "); for(long code : shelfNumbers) System.out.print(code + " "); System.out.println("\n==============================="); long shelfNumber = 0; System.out.print("Enter the shelf number of the " + "video you want to check: "); shelfNumber = Long.parseLong(br.readLine()); System.out.println(); for(int i = 0; i < 10; i++) { if (shelfNumbers[i] == shelfNumber) { System.out.println("==============================="); System.out.println("Video Information"); System.out.println("-------------------------------"); System.out.println("Shelf #: " + shelfNumbers[i]); System.out.println("Title: " + titles[i]); System.out.println("Director: " + directors[i]); System.out.println("Length: " + lengths[i] + " minutes"); System.out.println("Rating: " + ratings[i]); System.out.printf("Price: %.2f\n", prices[i]); } } System.out.println("==============================="); } }```
2. Execute the application to test it
3. When prompted, enter a shelf number and press Enter. Here is an example:

 ```=============================== Video Collection Shelf Numbers: 2985 8024 5170 1304 9187 1193 3082 8632 4633 9623 =============================== Enter the shelf number of the video you want to check: 5170 =============================== Video Information ------------------------------- Shelf #: 5170 Title: Chalte Chalte Director: Aziz Mirza Length: 145 minutes Rating: N/R Price: 22.45 ===============================```