OCA Java SE 8 Core Java APIs - Java Arrays








An array is a memory on the heap for a designated number of elements.

An array is an ordered list. It can contain duplicates.

Creating an Array of Primitives

The most common way to create an array looks like this:

int[] n1 = new int[3]; 

There are three parts in array definition which specifies the type of the array (int) and the size (3).

This form of instantiating an array sets all the elements to the default value for that type.

The default value for all the elements is 0.

Array indexes start with 0 and count up.

Another way to create an array is to specify all the elements it should start out with:

int[] numbers2 = new int[] {1, 2, 3}; 

As a shortcut, Java lets you write this:

int[] numbers2 = {1, 2, 3}; 

This approach is called an anonymous array because you don't specify the type and size.

We can type the [] before or after the name, and adding a space is optional.

This means that all four of these statements do the exact same thing:

int[] myArray; 
int [] myArray2; 
int myArray3[]; 
int myArray4 []; 




Multiple Arrays in Declarations

The following code defines two array variables.

int[] ids, types; 

The following code defines type int[] and one variable of type int.

int ids[], types; 

Array with Reference Variables

We can define any Java type to be the type of the array including classes you create yourself.

The following code creates a built-in type with String:

public class Main { 
  public static void main(String args[]) { 
    String [] bugs = { "A", "B", "C" }; 
    String [] alias = bugs; 
    System.out.println(bugs.equals(alias));     // true 
    System.out.println(bugs.toString());
  }
} 

We can call equals() because an array is an object.

It returns true because of reference equality.

The equals() method on arrays does not look at the elements of the array.

We can call equals() method on an int[] too. int is a primitive; int[] is an object.

The following code never instantiated the array so it is just a reference variable to null.

String names[]; 

The following code creates an array of type String since that is the type mentioned in the declaration.

class Names { 
  String names[] = new String[2]; 
} 

It has two elements because the length is 2. Each of those two slots currently is null and can point to a String object.





Casting

The following line creates an array of type String.

String[] strings = { "stringValue" }; 

Then the code requires a cast because Object is a broader type than String.

Object[] objects = strings; 

After that a cast is needed because we are moving to a more specific type as follows.

String[] againStrings = (String[]) objects; 

The following line doesn't compile because a String[] only allows String objects and StringBuilder is not a String.

againStrings[0] = new StringBuilder();   // DOES NOT COMPILE 

We have a String[] referred to from an Object[] variable. At runtime, the code throws an ArrayStoreException.

objects[0] = new StringBuilder();        // careful! 

Example

The following code shows how to access array elements.

public class Main{
   public static void main(String[] argv){
        //declares and initializes the array.
        String[] myArray = {"C", "B", "A"}; 
        //tells us how many elements the array can hold. 
        System.out.println(myArray.length);           // 3 
        //elements are indexed starting with 0.  
        System.out.println(myArray[0]);               // C
        System.out.println(myArray[1]);               // B
        System.out.println(myArray[2]);               // A
   }
}

The following code prints out 6.

Even though all 6 elements of the array are null, there are still 6 of them.

String[] birds = new String[6]; 
System.out.println(birds.length); 

length does not consider what is in the array; it only considers how many slots have been allocated.

We can use a loop when reading from or writing to an array. This loop sets each element of number to 5 higher than the current index:

//instantiates an array with 10 slots.
int[] numbers = new int[10]; 

//a for loop using an extremely common pattern. 
//It starts at index 0, which is where an array begins as well. It keeps going,  
//one at a time, until it hits the end of the array. 
for (int i = 0; i < numbers.length; i++)  
    numbers[i] = i + 5; 

The following code throws exceptions. Array indexes start with 0. Since we have 10 elements in our array, this means only numbers[0] through numbers[9] are valid.

numbers[10] = 3; 

The following for loop incorrectly uses <= instead of <, which is also a way of referring to that 10th element.

numbers[numbers.length] = 5; 
for (int i = 0; i <= numbers.length; i++) 
   numbers[i] = i + 5; 

Sorting

The following code shows how to sort an int array.

/*from  www .j  a  v  a 2s . co  m*/
import java.util.*;          // import whole package including Arrays 
import java.util.Arrays;     // import just Arrays 

public class Main{
   public static void main(String[] argv){
        int[] numbers = { 6, 9, 1 }; 
        Arrays.sort(numbers); 
        for (int i = 0; i < numbers.length; i++)  
            System.out.print (numbers[i] +  " "); 
   }
}

The code above generates the following result.

Sorting 2

Try this again with String types:

import java.util.*;          // import whole package including Arrays 
import java.util.Arrays;     // import just Arrays 

public class Main{
   public static void main(String[] argv){
        String[] strings = { "10", "9", "100" }; 
        Arrays.sort(strings); 
        for (String string : strings) 
          System.out.print(string + " "); 
   }
}

This code outputs 10 100 9.

The problem is that String sorts in alphabetic order, and 1 sorts before 9.

Searching

Java provides a convenient way to binary search the sorted arrays.

The following table lists the Binary search rules.

if Target element is found in sorted array, then return Index of found if Target element not found in sorted array, then return Negative value showing one smaller than the negative of index, where a match needs to be inserted to preserve sorted order.

public class Main{
   public static void main(String[] argv){

      int[] numbers = {2,4,6,8}; 
      System.out.println(Arrays.binarySearch(numbers, 2)); // 0 
      System.out.println(Arrays.binarySearch(numbers, 4)); // 1 
      System.out.println(Arrays.binarySearch(numbers, 1)); // -1 
      System.out.println(Arrays.binarySearch(numbers, 3)); // -2 
      System.out.println(Arrays.binarySearch(numbers, 9)); // -5 
   
   }
}

Varargs

Here are three examples with a main() method:

public static void main(String[] args)  
public static void main(String args[])  
public static void main(String... args) // varargs 

The third example uses a syntax called varargs (variable arguments).

You can use a variable defined using varargs as if it were a normal array.

For example args.length and args[0] are legal.

Multidimensional Arrays

Arrays are objects, and array components can be objects.

Multiple array separators are all it takes to declare arrays with multiple dimensions.

The first two examples are nothing surprising and declare a two-dimensional (2D) array.

The third example also declares a 2D array.

The final example declares two arrays on the same line.

Adding up the brackets, vars4 is a 2D array and space is a 3D array.

int[][] vars1;          // 2D array 
int vars2 [][];         // 2D array 
int[] vars3[];          // 2D array 
int[] vars4 [], space [][];  // a 2D AND a 3D array 

You can specify the size of your multidimensional array in the declaration:

String [][] rectangle = new String[3][2]; 

The result of this statement is an array rectangle with three elements, each of which refers to an array of two elements.

An array doesn't need to be rectangular in shape.

Consider this one:

int[][] differentSize = {{1, 4}, {3}, {9,8,7}}; 

We start with an array of three elements.

The elements in the next level are all different sizes.

One is of length 2, the next length 1, and the last length 3.

Another way to create an asymmetric array is to initialize just an array's first dimension, and define the size of each array component in a separate statement:

int [][] args = new int[4][]; 
args[0] = new int[5]; 
args[1] = new int[3]; 

Java array is arrays of arrays.

This example prints out a 2D array:

int[][] twoD = new int[3][2]; 
for (int i = 0; i < twoD.length; i++) { 
  for (int j = 0; j < twoD[i].length; j++) 
    System.out.print(twoD[i][j] + " "); // print element 
  System.out.println();                 // time for a new row 
} 

We have two loops here. The first uses index i and goes through the first subarray for twoD.

The second uses a different loop variable j.

The inner loop looks at how many elements are in the second-level array. The inner loop prints the element and leaves a space for readability.

When the inner loop completes, the outer loop goes to a new line and repeats the process for the next element.

The following code uses the enhanced for loop.

for (int[] inner : twoD) { 
      for (int num : inner) 
            System.out.print(num + " "); 
      System.out.println(); 
}