Core java Arrays Core Java

An array is a data structure that stores a collection of values of the same type. You access each individual value through an integer index. For example, if a is an array of integers, then a[i] is the ith integer in the array.

You declare an array variable by specifying the array type—which is the element type followed by []—and the array variable name. For example, here is the declaration of an array a of integers:

However, this statement only declares the variable a. It does not yet initialize a with an actual array. You use the new operator to create the array.

This statement sets up an array that can hold 100 integers.

NOTE: You can define an array variable either as

Most Java programmers prefer the former style because it neatly separates the type int[] (integer array) from the variable name.

The array entries are numbered from 0 to 99 (and not 1 to 100). Once the array is created, you can fill the entries in an array, for example, by using a loop:

CAUTION: If you construct an array with 100 elements and then try to access the element a[100] (or any other index outside the range 0 ... 99), then your program will terminate with an “array index out of bounds” exception.

To find the number of elements of an array, use array.length. For example:

Once you create an array, you cannot change its size (although you can, of course, change an individual array element). If you frequently need to expand the size of an array while a program is running, you should use a different data structure called an array list.

The “for each” Loop

Java SE 5.0 introduced a powerful looping construct that allows you to loop through each element in an array (as well as other collections of elements) without having to fuss with index values.

The enhanced for loop

sets the given variable to each element of the collection and then executes the statement(which, of course, may be a block). The collection expression must be an array or an objectof a class that implements the Iterable interface, such as ArrayList.

For example,

prints each element of the array a on a separate line.

should read this loop as “for each element in a”. The designers of the Java language considered using keywords such as foreach and in. But this loop was a late addition to the Java language, and in the end nobody wanted to break old code that already contains methods or variables with the same names (such as

Of course, you could achieve the same effect with a traditional for loop:

However, the “for each” loop is more concise and less error prone. (You don’t have to worry about those pesky start and end index values.)

NOTE: The loop variable of the “for each” loop traverses the elements of the array, not the index values.

The “for each” loop is a pleasant improvement over the traditional loop if you need toprocess all elements in a collection. However, there are still plenty of opportunities touse the traditional for loop. For example, you may not want to traverse the entire collection,or you may need the index value inside the loop.

TIP: There is an even easier way to print all values of an array, using the toString method of the Arrays class. The call Arrays.toString(a) returns a string containing the array elements, enclosed in brackets and separated by commas, such as "[2, 3, 5, 7, 11, 13]". To print the array, simply call

Array Initializers and Anonymous Arrays

Java has a shorthand to create an array object and supply initial values at the same time. Here’s an example of the syntax at work:

Notice that you do not call new when you use this syntax.

You can even initialize an anonymous array:

This expression allocates a new array and fills it with the values inside the braces. It counts the number of initial values and sets the array size accordingly. You can use this syntax to reinitialize an array without creating a new variable. For example,

is shorthand for

NOTE: It is legal to have arrays of length 0. Such an array can be useful if you write a method that computes an array result and the result happens to be empty. You construct an array of length 0 as

Note that an array of length 0 is not the same as null.

Array Copying

You can copy one array variable into another, but then both variables refer to the same array:

The result. If you actually want to copy all values of one array into a new array, you use the copyTo method in the Arrays class:

The second parameter is the length of the new array. A common use of this method is to increase the size of an array:

The additional elements are filled with 0 if the array contains numbers, false if the array contains boolean values. Conversely, if the length is less than the length of the original array, only the initial values are copied.

Copying an array variable

Copying an array variable

NOTE: Prior to Java SE 6, the arraycopy method in the System class was used to copy elements from one array to another. The syntax for this call is

The to array must have sufficient space to hold the copied elements.

For example, the following statements, whose result, set up two arrays and then copy the last four entries of the first array to the second array. The copy starts at position 2 in the source array and copies four entries, starting at position 3 of the target.

The output is

0: 1001 1: 1002 2: 1003 3: 5 4: 7 5: 11 6: 13

C++ NOTE: A Java array is quite different from a C++ array on the stack. It is, however, essentially the same as a pointer to an array allocated on the heap. That is,

In Java, the [] operator is predefined to perform bounds checking. Furthermore, there is no pointer arithmetic—you can’t increment a to point to the next element in the array.

Command-Line Parameters

You have already seen one example of Java arrays repeated quite a few times. Every Java program has a main method with a String[] args parameter. This parameter indicates that the main method receives an array of strings, namely, the arguments specified on the command line.

For example, consider this program:

If the program is called as java Message -g cruel world

then the args array has the following contents:

args[0]: "-g" args[1]: "cruel" args[2]: "world" The program prints the message Goodbye, cruel world!

C++ NOTE: In the main method of a Java program, the name of the program is not stored in the args array. For example, when you start up a program as java Message -h worldfrom the command line, then args[0] will be "-h" and not "Message" or "java".

Array Sorting

To sort an array of numbers, you can use one of the sort methods in the Arrays class:

This method uses a tuned version of the QuickSort algorithm that is claimed to be very efficient on most data sets. The Arrays class provides several other convenience methods for arrays that are included in the API notes at the end of this section.

The program in Listing below puts arrays to work. This program draws a random combination of numbers for a lottery game. For example, if you play a “choose 6 numbers from 49” lottery, then the program might print this:

Bet the following combination. It'll make you rich!

To select such a random set of numbers, we first fill an array numbers with the values 1, 2,. . . , n:

A second array holds the numbers to be drawn:

Now we draw k numbers. The Math.random method returns a random floating-point number that is between 0 (inclusive) and 1 (exclusive). By multiplying the result with n, we obtain a random number between 0 and n – 1.

We set the ith result to be the number at that index. Initially, that is just r + 1, but as you’ll see presently, the contents of the numbers array are changed after each draw.

Now we must be sure never to draw that number again—all lottery numbers must be distinct. Therefore, we overwrite numbers[r] with the last number in the array and reduce n by 1.

The point is that in each draw we pick an index, not the actual value. The index points into an array that contains the values that have not yet been drawn.After drawing k lottery numbers, we sort the result array for a more pleasing output:

java.util.Arrays 1.2

  • static String toString(type[] a) 5.0
    returns a string with the elements of a, enclosed in brackets and delimited by
  • java.util.Arrays 1.2

  • static type copyOf(type[] a, int length) 6
  • static type copyOf(type[] a, int start, int end) 6
    returns an array of the same type as a, of length either length or end - start, filled
    with the values of a.
  • java.util.Arrays 1.2

  • static void sort(type[] a)
    sorts the array, using a tuned QuickSort algorithm.
  • java.util.Arrays 1.2

  • static int binarySearch(type[] a, type v)
  • static int binarySearch(type[] a, int start, int end type v) 6
    uses the binary search algorithm to search for the value v. If it is found, its index is
    returned. Otherwise, a negative value r is returned; -r - 1 is the spot at which v
    should be inserted to keep a sorted
  • java.util.Arrays 1.2

  • static void fill(type[] a, type v)
    sets all elements of the array to v.
  • java.util.Arrays 1.2

  • static boolean equals(type[] a, type[] b)
    returns true if the arrays have the same length, and if the elements in
    corresponding indexes match.
  • java.util.Arrays 1.2

  • static void arraycopy(Object from, int fromIndex, Object to, int toIndex, int count)
    copies elements from the first array to the second array.
  • java.util.Arrays 1.2

Multidimensional Arrays
Multidimensional arrays use more than one index to access array elements. They are used for tables and other more complex arrangements. You can safely skip this section until you have a need for this storage mechanism.

Suppose you want to make a table of numbers that shows how much an investment of $10,000 will grow under different interest rate scenarios in which interest is paid annually and reinvested. Table below illustrates this scenario.

Growth of an Investment at Different Interest Rates

Growth of an Investment at Different Interest Rates

You can store this information in a two-dimensional array (or matrix), which we call balances. Declaring a two-dimensional array in Java is simple enough. For example:

As always, you cannot use the array until you initialize it with a call to new. In this case, you can do the initialization as follows:

In other cases, if you know the array elements, you can use a shorthand notion for initializing
multidimensional arrays without needing a call to new. For example:

Once the array is initialized, you can access individual elements by supplying two brackets, for example, balances[i][j].

The example program stores a one-dimensional array interest of interest rates and a twodimensional array balance of account balances, one for each year and interest rate. We initialize the first row of the array with the initial balance:

NOTE: A “for each” loop does not automatically loop through all entries in a two-dimensional array. Instead, it loops through the rows, which are themselves one-dimensional arrays. To visit all elements of a two-dimensional array a, nest two loops, like this:
for (double[] row : a)
for (double value : row)
do something with value

TIP: To print out a quick and dirty list of the elements of a two-dimensional array, call System.out.println(Arrays.deepToString(a));
The output is formatted like this:
[[16, 3, 2, 13], [5, 10, 11, 8], [9, 6, 7, 12], [4, 15, 14, 1]]

Ragged Arrays
So far, what you have seen is not too different from other programming languages. But there is actually something subtle going on behind the scenes that you can sometimes turn to your advantage: Java has no multidimensional arrays at all, only one-dimensional arrays. Multidimensional arrays are faked as “arrays of arrays.”

For example, the balances array in the preceding example is actually an array that contains ten elements, each of which is an array of six floating-point numbers

A two-dimensional array

A two-dimensional array

The expression balances[i] refers to the ith subarray, that is, the ith row of the table. It is itself an array, and balances[i][j] refers to the jth entry of that array. Because rows of arrays are individually accessible, you can actually swap them!

It is also easy to make “ragged” arrays, that is, arrays in which different rows have different lengths. Here is the standard example. Let us make an array in which the entry at row i and column j equals the number of possible outcomes of a “choose j numbers from i numbers” lottery.
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1

Because j can never be larger than i, the matrix is triangular. The ith row has i + 1 elements. (We allow choosing 0 elements; there is one way to make such a choice.) Tobuild this ragged array, first allocate the array holding the rows.

Now that the array is allocated, we can access the elements in the normal way, provided we do not overstep the bounds.

C++ NOTE: In C++, the Java declaration double[][] balances = new double[10][6]; // Java is not the same as double balances[10][6]; // C++ or even double (*balances)[6] = new double[10][6]; // C++
Instead, an array of 10 pointers is allocated:
double** balances = new double*[10]; // C++

Then, each element in the pointer array is filled with an array of 6 numbers:

Mercifully, this loop is automatic when you ask for a new double[10][6]. When you want ragged arrays, you allocate the row arrays separately.You have now seen the fundamental programming structures of the Java language. The next section covers object-oriented programming in Java.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Core Java Topics