How Can We Help?
Introduction
An array is a set of members. Each member can contain an object or primitive value. Arrays in Java are objects and can be treated like any other object. The arrays can contain values of any type (primitive types or objects), but we can’t store different types in the same array. You can have an array of integers, or array of strings, or an array of arrays, but you can not have an array that contains, for example, both strings and integers.
Array members are stored in the memory sequentially, and their index identifies them. For example – if the array is called myList, then myList[0] is its first element, and myList[5] is its sixth element, indexed with 5.
To create an array in Java – we’ll need to perform 3 steps:
- Declare a variable in which the array will be stored.
- Please create a new array object and assign it to the array variable.
- Place the elements (members) values in the array.
Declaring an array
The array variable indicates the type of object to be placed in the array (as in other variables) and the array name, followed by parentheses ([]). The following expressions are a typical declaration of array-type variables:
string newWords[ ];
point answers[ ]; // point is an object
int years[ ];
We can write the declaration as follows:
string [ ] newWords;
point[ ] answers; // point is an object
int[ ] years;
Creating an Array
The first way is to apply the new operator to create a new instance of the array:
String [ ] names = new String [10];
This statement creates a new array of type strings with 10 members (so-called elements).
Array-type objects can contain primitive types, e.g., integers or logical values, and may contain whole objects:
int [ ] years = new int [99];
When we create an array using new, all members are already initialized (0 for numbers, false for boolean, ‘\ 0’ for letter strings, and null for objects). We can then assign the actual values to the array members.
String[ ] meals= {"chicken", "salad", "desert", "potato", "rice"};
Accessing the Array Members
Basic Syntax
To assign a value to a given array member, we can perform the following steps:
myarray [1] = 12;
sentence [0] = "The";
sentence [10] = sentence [0];
It is important to note that the array in Java is an array of references (indexes) to its elements (similar to C and C++ pointer arrays).
Example of Array Operations:
class ArrayExample {
String[] firstNames = {"Donna", "Emma", "Michael", "John"};
String[] lastNames = new String[firstNames.length];
void displayNames() {
int i = 0;
System.out.println(firstNames[i] + " " + lastNames[i]);
i++;
System.out.println(firstNames[i]+ " " + lastNames[i]);
i++;
System.out.println(firstNames[i]+ " " + lastNames[i]);
i++;
System.out.println(firstNames[i]+ " " + lastNames[i]);
}
public static void main (String args[]) {
ArrayExample s = new ArrayExample();
s.printNames();
System.out.println("----------");
s.lastNames[0] = "Summer";
s.lastNames[1] = "Stone";
s.lastNames[2] = "Jackson";
s.lastNames[3] = "Nash";
s.displayNames();
}
}
Output:
Donna null
Emma null
Michael null
John null
Donna Summer
Emma Stone
Michael Jackson
John Nash
Methods with Arrays as Arguments
The following table presents Java methods that perform operations over arrays. The arguments are usually arrays, and the returned values can be boolean, integer or void.
Method | Description |
---|---|
public static boolean equals(long[] a, long[] a2) | Returns true if the two specified arrays of longs are equal. Two arrays are considered equal if both arrays contain the same number of elements and all pairs of corresponding elements in the two arrays are equal. The same method can be applied to other primitive data types (Byte, short, Int, etc.) |
public static void fill(int[] a, int val) | Assign a specified int value to each array element a[] of ints. We can use the same method for all other primitive data types (Byte, short, Int, etc.) |
public static void sort(Object[] a) | Sorts a specified array of objects into ascending order, according to the natural ordering of its elements. The same method can be used by all other primitive data types ( Byte, short, Int, etc.) |
public static int binarySearch(Object[] a, Object key) | Searches the specified array of Objects ( Byte, Int, double, etc.) for the specified value using the binary search algorithm. The array must be sorted before making this call. |
Examples
Example for a foreach Loop
it will display all of the array elements on the screen:
public class ExampleArray {
public static void main(String[] args) {
double[] myArray = {0.8, 3.7, 5.6, 7.9};
// Display all the array elements
for (double element: myArray) {
System.out.println(element);
}
}
}
Output:
0.8
3.7
5.6
7.9
Example – equals() Method
Comparing two arrays:
import java.util.Arrays;
public class examEquals {
public static void main(String[] args)
{
int[] a = new int[] {2, 3, 5};
int[] b = new int[] {2, 3, 4};
int[] c = new int[] {2, 3, 5};
boolean result1 = Arrays.equals(a, b);
if (result1)System.out.println("The arrays are equal.");
else System.out.println("The arrays are not equal.");
boolean result2 = Arrays.equals(a, c);
if (result2)System.out.println("The arrays are equal.");
else System.out.println("The arrays are not equal.");
}
}
Output:
The arrays are not equal.
The arrays are equal.
Example – fill() Method
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
int arr[]= {3, 4, 1, 8, 2, 3, 7, 5, 3};
Arrays.fill(arr, 8);
System.out.println("Filling array with 8-s:" + Arrays.toString(arr));
}
}
Output:
Filling array with 8-s: [8, 8, 8, 8, 8, 8, 8, 8, 8]
Example – passing Arrays as arguments to a method.
Just as with primitive data types, the arrays in Java can be passed as arguments to methods and returned in the main class.
public class ArrayMethod {
public static void main(String[] args) {
int[] a = {100, 101, 102, 103};
displayElements(a);
}
public static void displayElements(int[] a) {
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + ",");
System.out.println();
}
}
Output:
100, 101, 102, 103
Example – Returning an Array to the main method:
public class ReturnArray1
{
public static void main(String args[])
{
int[] a=method1();
for (int i = 0; i < a.length; i++)
System.out.print( a[i]+ " ");
}
public static int[] method1()
{
int[] arr={0,2,4,6,8}; //initializing array
return arr;
}
}
Output:
0, 2, 4, 6, 8