Declaration

a simple variable
int myVar;
1D array declaration
int[] my1D; or int my1D[];
The two lines above are similar except for the square bracket notation. Adding the set of empty square brackets tells the java compiler that the variable you are declaring is going to reference a one-dimensional array.

Instantiation

For one-dimensional arrays, declaring the array does not allocate space in memory for the collection of elements. To do that you must call upon the new keyword.
int[] my1D = new int[3];
This is similar to the instantiation of objects you have seen except for the strict square bracket notation. The line of code says to create an array that can store 3 distinct int elements.

int[] myArr = new int[size];
The number of elements in the collection is the number given on the right side of the assignment statement. It's important to not confuse the size with indexing. The size used in the instantiation is the number of spots. New programmers sometimes confuse the size vs the largest possible index.

Indexing

In the example below, you can see that declaring a simple primitive type will allocate memory and assign a default value to that variable. It works the way for an array of primitive types. Remember that numerical types are initialized to zero while a boolean is initialized to false. The first row in the table is meant to visualize the address of the locations. Think of an array as a bunch of lockers. Each locker has a locker number. For arrays, the first one is always at index 0 and it goes up consecutively from there. The last index is always at length - 1.

Declaration only:
int[] arr;
Declaration and instantiation of a 2-element integer array
int[] arr = new int[2];
After declaring the array, you can then read/write values to the location. In java, indexing starts at 0!
arr[0] = 1;

You must specify which location of the array you're reading/writing since you now have multiple locations! The following is an syntax error in java.
arr = 1; //this will not run because you must specify where in the array you're writing to since arr is an array

Access the last element

You can take advantage of the length property to access the last element of an array.

Given an array nums, print the last element:
System.out.println(nums[nums.length-1]);

In the code above, the reason you subtract -1 from the length is that indexing starts at 0 so the last element is located at length-1. For example, if the length of an array is 10 then the last element is at index 9 (1 less than the length).

Misconceptions Revisited
If you have an array created using the lines below, note that common error with new programmers in answer the questions about the number of elements vs the highest possible index.

int[] nums = new int[30];

A student may confuse the size of the array as 29. Why? Because indexing into the array starts at 0, they think 29 is the total number of elements rather than the highest possible index.

A student may confuse 30 as the highest index into the array. Why? They forget that indexing into an array starts at 0. In this case, the locations of the elements go from 0, 1, 2, ... , 29!  from 0 to 29 there are 30 distinct integers so it's consistent with the array length of 30.

Don't make these mistakes or be aware of your tendency to do so.

Literal Values

What if you want to assign an array a literal value during instantiation? The syntax to do this is shown below.
int x = 5;             //assign a primitive var a literal value 
int []x = { 1, -5, 0}; //assigning an array literal values.
This time instead of having one value like you would a normal variable, you have a bunch of elements. These elements are enclosed together with a set of curly brackets and comma-separated. Here are more examples.
boolean[] myBools = { true, true, false, false, true}; 
double[] myDoubles = {1.5, 3.14, 8.01};
When you assign an array of literal values, the length of the array is equal to the number of elements you assigned it.

For Loop Array Traversals

Recall that the first element in an array is located at index 0 while the last element is at length - 1. These are just a sequence of numbers you can easily generate with a for loop! A for loop can be used to generate locations you want to visit in an array. Each iteration will point to a location in the array thereby allowing you to visit each element in the array known as an array traversal.
int[] myArray = {9, 4, 0, -1, 7, 8, 10};
for(int index = 0; index < myArrray.length; index++){
//this example prints each element to the console
}
In the example above the loop is used to generate the indexes and as you visit each element you can print it to the console. What other things can you do? Find the sum of the elements in an array:
int sum = 0;
for(int i = 0; i < myArray.length; i++){
    sum += myArray[i];
}
Find the smallest element in the array:
int min = myArray[0];
for(int i = 1; i < myArray.length; i++){
    //check if the current element is smaller than current minimum
    if(min < myArray[i]){
        min = myArray[i];
    }
} 

Object Arrays

You declare and instantiate an array of primitive types similar to what is shown. Just change the type from int to your desired type such as boolean or double. Arrays of objects behave slightly differently because you need to do some additional work. The array only allocates memory to store object references. The objects themselves do not exist. You must instantiate them separately. More on this later in 6.3.


length

If you want to know how many elements an array was allocated to have, you can use the length property. An array in java is an object. Because of this, the dot operator is valid to use. length is an attribute of all arrays. To get the length you then just access it using the dot operator such as my2D.length.

MyClass myArray[] = new MyClass[10];

The array above contains 0 objects! Each spot can refer to an object, but they do not yet exist. You will have to explicitly create the objects in order to start working with the array or you will get a NullPointerException!


for(int x = 0; x < myArray.length; x++){
   myArray[x] = new MyClass();
}

In the example above, the objects are CREATED once you call the actual constructor for the MyClass objects.  

Partial Array Traversals

Anything you can make your for loop do in terms of indexing will allow you to visit whatever part of the array you like! For example, how do you visit only half of the array? Well, you can make the for loop stop sooner!

Find the sum of the elements in the first half of an array:
int sum = 0;
for(int i = 0; i < myArray.length/2; i++){
    sum += myArray[i];
}

Find the sum of every odd indexed element: int sum = 0; for(int i = 1; i < myArray.length; i+=2){     sum += myArray[i]; }
You should now complete the practice problems to test your ability to work with 1D arrays!

Enhanced For Loop

If you have a typical traversal where you visit each element you can use an enhanced for loop. This for loop handles the actual visitation to each element and indexing visiting elements from index 0 to the last valid index. The two loops are compared below.

//Template
for( type temp : nameOfArray){
    //temp holds the element in the array and will automatically update each iteration
    System.out.println(temp);
}
//What it looks like in practice
int[] nums = { 2, 5, 1, 8, 0 };
for(int el : nums){ //for each element in nums
    System.out.println(el);
}
You can read the loop as " For every element in nums "

Example with ArrayList

ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(7);
arr.add(3);

for(int el: arr){
System.out.print(el);
}


The code will print 73.

Common Error 1:

When using the temp variable of an enhanced-for-loop, the actual array does not change if the elements are primitive types (boolean, int, double, String).

int[] nums = { 2, 5, 1, 8, 0 };
for(int el : nums){ //for each element in nums
    el = 7;
}

The code above does not alter the elements of nums to be 7. Why? el is a temp variable that is a primitive type because the array contains primitive data (in this case int). Since this is the case, el will have a COPY of the elements at each position. So whatever you do to the copy only affects the copy!

Common Error 2:

Remember that the general rule is that the temp variable used in an enhanced for-loop does not affect the original elements. This is also true for "Objectified" primitives such as Integer, Double and Boolean. These are the class versions of the primitive data types BUT they behave similarly to a regular primitive datatype! See the example below.

ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(7);
arr.add(3);

for(Integer el: arr){
el += 5;
}

What is stored in arr after running the loop? It still contains 7 and 3 because el+=5 only alters the value of the copy NOT the elements of the list!

Common Error 3:

Strings ALSO follow the mentioned rule above! Strings are immutable in java so when you assign a variable to another String, you're actually creating a copy.

ArrayList<String> arr = new ArrayList<String>();
arr.add("hello");
arr.add("world");

for(String el: arr){
el = el + "s";
}

What does arr contain after running the loop? It still contains "hello" and "world". el in the enhanced for-loop will contain a copy of the elements NOT the actual reference to the element.

"REAL" object types!:

Now let's see how it behaves for objects that are not the "primitive" types mentioned above!

class Square{
int x;
public Square(){ x = 3; };
}
Square[] arr = { new Square(), new Square() };

The block of code above shows a simple Square class with a default constructor assigning the value of its instance variable to 3. The array is declared and initialized to contain two Square objects.

for(Square temp: arr){ //for each Square in arr
//as the loop visits each element, it is referenced as temp!
temp.x++;
}
What will the Squares' instance variables be after the loop runs? They will be both 4! This is because with objects, the variable temp is a reference type which would actually refer to the actual object rather than a "copy".
Comparing array traversal with enhanced for-loops:
for(Square el : arr){
el.x++;
}
//Equivalent regular for-loop version
for(int i = 0; i < arr.length; i++){
Square temp = arr[i];
temp++;
}

//Another equivalent loop
for(int i = 0; i < arr.length; i++){
arr[i].x++;
}

General Tips

An enhanced for loop is not what you need to use if you need to alter the elements in the array. You especially do not want to do it when working with primitive type arrays. This is because the variable used can be a copy of the actual element so incrementing it will not affect the actual array values. It's better to use a traditional for loop with indexing for those types of problems.

Some good rules to follow if you are new to programming:
    Do not use enhanced for loops if you need an index as it's likely more convenient to use a traditional loop that already has indexing variables.
    Do not use enhanced for loops if you need to change the values in the array.
    Do not use enhanced for loops if you want to control what part of the array to visit or the order.
    Do not confuse the element for the index in enhanced for-loops!
       example: for(int i : nums)  -> i
is NOT an index. It is the element in the 1D array. 

Algorithms To Know

You should be familiar with the following algorithms to be prepared for the AP Exam. Use the practice problems to help you build your skill in writing these types of algorithms!


  • Compute a sum, average, or mode of array elements
//Example Finding the sum
//assume arr exists with values
int sum = 0; for(int i =0; i < arr.length; i++){ sum+= arr[i]; }
  • Search for a particular element in the array
    //assume arr exists with values
    //look for the lucky number 7 for(int i =0; i < arr.length; i++){ if(arr[i] == 7){ System.out.println("Found a 7"); } }
  • Determine if at least one element has a particular property
    //assume arr exists with values
    //Check if an element is divisible by 6 and not 0 int total = 0; for(int i =0; i < arr.length; i++){ if(arr[i] % 6 == 0 && arr[i] !=0 ){ total++; } }
  • Determine if all elements have a particular property
    //assume arr exists with values
    //check to make sure all values are non-negative for(int i =0; i < arr.length; i++){ if(arr[i] < 0){ System.out.println("Found a negative number! Exit! Does not meet requirement"); break; } }
  • Determine the minimum or maximum value in an array
int currMin = arr[0]; //assume smallest is first element
int minIndex = 0;
for(int i = 1; i < arr.length; i++){
   //if you find a smaller number, make that the smallest
    if(currMin > arr[i]){ //if there is a number smaller than the currentMin, update!
       minIndex = i;      //found a smaller number so update the index and value
       currMin = arr[i];
    }
}
System.out.println("Smallest number is "+currMin+" at index "+minIndex);
  • Access all consecutive pairs of elements
    //assume arr exists with values
    //look for two consecutive pairs of 7s in the array //Note the -1 in the condition. Since the if-statement accesses i+1, we //want to make sure that loop stops incrementing i once it is at the 2nd to last //element. If you let i continue to the very last index, the if-statement will go OutOfBounds!!!! for(int i =0; i < arr.length - 1 ; i++){ if(arr[i] == 7 && arr[i+1] ==7){      System.out.println("Found a consecutive pair of 7s"); } }
  • Determine the presence or absence of duplicate elements
  • Determine the number of elements meeting specific criteria
  • Shift or rotate elements left or right
  • Reverse the order of the elements

By the way, these algorithms can easily be applied to ArrayList or 2D arrays later! If you learn the fundamental parts of these algorithms now, it will only help you conceptually when you are asked to apply them to other data structures.