Declaring An Array Variable in Java
Declaring An Array Variable in Java
A Java array variable is declared just like you would declare a variable
of the desired type, except you add [] after the type. Here is a simple
Java array declaration example:
int[] intArray;
You can use a Java array as a field, static field, a local variable, or
parameter, just like any other variable. An array is simply a variation of
the data type. Instead of being a single variable of that type, it is a
collection of variables of that type.
String[] stringArray;
MyClass[] myClassArray;
You actually have a choice about where to place the square brackets []
when you declare an array in Java. The first location you have already
seen. That is behind the name of the data type (e.g. String[]). The
second location is after the variable name. The following Java array
declarations are actually all valid:
int[] intArray;
int intArray[];
String[] stringArray;
String stringArray[];
MyClass[] myClassArray;
MyClass myClassArray[];
Personally I prefer to locate the square brackets [] after the data type
(e.g. String[]) and not after the variable name. After all, an array is a
special kind of data type, so I feel it is easier to read the code when the
square brackets are placed right after the data type in the array
declaration.
Instantiating an Array in Java
When you declare a Java array variable you only declare the variable
(reference) to the array itself. The declaration does not actually create
an array. You create an array like this:
int[] intArray;
Once an array has been created its size cannot be changed. In some
languages arrays can change their size after creation, but in Java an
array cannot change its size once it is created. If you need an array-
like data structure that can change its size, you should use a List.
Notice how the values to be inserted into the array are listed inside
the { ... } block. The length of this list also determines the length of
the created array.
It is the part inside the curly brackets that is called an array literal.
This style works for arrays of all primitive types, as well as arrays of
strings. Here is a string array example:
Each element in the array has an index (a number). You can access
each element in the array via its index. Here is an example:
intArray[0] = 0;
This example first sets the value of the element (int) with index 0, and
second it reads the value of the element with index 0 into
an int variable.
You can use the elements in a Java array just like if they were ordinary
variables. You can read their value, assign values to them, use the
elements in calculations and pass specific elements as parameters to
method calls.
Array Length
You can access the length of an array via its length field. Here is an
example:
Iterating Arrays
You can loop through all the elements of an array using the Java for
loop. Here is an example of iterating an array with a for loop in Java:
The variable i is initialized to 0 and runs up until the length of the array
minus 1. In this case, i takes the values 0 through 9, each time
repeating the code inside the for loop one time, and for each
iteration i has a different value.
You can also iterate an array using the "for-each" loop in Java. Here is
how that looks:
The for-each loop gives you access to each element in the array, one
at a time, but gives you no information about the index of each
element. Additionally, you only have access to the value. You cannot
change the value of the element at that position. If you need that, use a
normal for-loop as shown earlier.
For for-each loop also works with arrays of objects. Here is an example
showing you how to iterate an array of String objects:
intArray[0][2] = 129;
The variable named oneInt will contain the value 129 after the last line
of Java code has executed.
The example first creates an array. Then it defines an insert index and
a new value to insert. Then all elements from the insertion index and to
the end of the array are shifted one index down in the array. Note that
this will shift the last value in the array out of the array (it will simply be
deleted).
insertIntoArray(ints, 0, 10);
insertIntoArray(ints, 1, 23);
insertIntoArray(ints, 9, 67);
This example first creates an int array. Then it sets the value of the
element with index 10 to 123. Then the example removes the element
with index 10. It removes the element by shifting all elements below
index 10 one position up in the array. After the removal, the last
element in the array will exist twice. Both in the last and second last
element.
Second, the example iterates through the array and compares each
value to minValue. If the element in the array is smaller
than minVal then minVal is set to the value of the element.
Finally the minimum value found in the array is printed out. In the
example above the minimum value is 0.
Here is how you find the maximum value in an array. It is pretty similar
to finding the minimum value.
I will cover a few of the methods found in this class in the following
sections. Remember, in order to usejava.util.Arrays in your Java
classes you must import it. Here is how
importing java.util.Arrays could look in a Java class of your own:
package myjavaapp;
import java.util.Arrays;
}
}
Copying Arrays
You can copy an array into another array in Java in several ways.
The first way to copy an array in Java is to iterate through the array
and copy each value of the source array into the destination array.
Here is how copying an array looks using that method:
System.out.println(java.util.Arrays.toString(ints));
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Sorting Arrays
You can sort the elements of an array using the Arrays.sort() method.
Sorting the elements of an array rearranges the order of the elements
according to their sort order. Here is an Arrays.sort() example:
System.out.println(java.util.Arrays.toString(ints));
java.util.Arrays.sort(ints);
System.out.println(java.util.Arrays.toString(ints));
The for loop iterates over the array and inserts values into each
element. The values inserted will go from 10 to 1 in descending order.
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
The array is then sorted using Arrays.sort(). The elements will now be
ordered in ascending order.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
After sorting the array we iterate through it and print out the employee
names. This is how the output printed looks:
Anna
John
Xander
Notice how the order has been reversed compared to the order in
which they were originally inserted into the array.
Xander
Anna
John
Arrays.fill(intArray, 123);
System.out.println(Arrays.toString(intArray));
This example creates an int array and fills the value 123 into all
elements in the array. The last line of the example converts the array
to a String and prints it out to the console. Here is what the output
would look like:
[123, 123, 123, 123, 123, 123, 123, 123, 123, 123]
Arrays.fill(ints2, 3, 5, 123) ;
System.out.println(Arrays.toString(intArray));
This example only fills the elements which have index 3 and 4 (3 to 5
without 5) with the value 123. Here is the output printed from this
example:
0, 0, 0, 123, 123, 0, 0, 0, 0, 0]
System.out.println(index);
The second line of this example searches in the array for the value 6.
The binarySearch() method will return the index in the array in which
the element was found. In the example above
the binarySearch()method would return 3.
If more than one element exists in the array with the searched value,
there is no guarantee about which element will be found.
System.out.println(index);
The number 7 is not found in the array. The number 7 should have
been inserted into the array at index 4, if 7 was to be inserted into the
array (and the sort order kept). Therefore binarySearch() returns -4 - 1
= -5 .
If all elements in the array are smaller than the sought value,
then binarySearch() will return - length of the array - 1. Look at this
example:
System.out.println(index);
In this example we search for 12 in the array, but all elements in the
array are smaller than 12. ThereforebinarySearch() will return -length (-
6) - 1 = -6 -1 = -7.
System.out.println(index);
This example searches the array for the value 2 but only between
index 0 and 4 (without 4).
System.out.println(ints1EqualsInts2);
System.out.println(ints1EqualsInts3);