An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables.
Each item in an array is called an element, and each element is accessed by its numerical index.
Using and array in your program is a 3 step process –
1) declaring an Array
2) constructing an Array
3) initializing an Array
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable:
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.
Example:
The following code snippets are examples of this syntax:
double[] myList; // preferred way.
or
double myList[]; // works but not preferred way.
Constructing an Array:
You can create an array by using the new operator with the following syntax:
arrayRefVar = new dataType[arraySize];
The above statement does two things:
• It creates an array using new dataType[arraySize];
• It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below:
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows:
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.
Example:
Following statement declares an array variable, myList, creates an array of 10 elements of double type, and assigns its reference to myList.:
double[] myList = new double[10];
or
double[] myList = {5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 111.23};
Initializing an Array
intArray[0]=1; // Assigns an integer value 1 to the first element 0 of the array
intArray[1]=2; // Assigns an integer value 2 to the second element 1 of the aray
Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i]);
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
This would produce following result:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
The foreach Loops:
JDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.
Example:
The following code displays all the elements in the array myList:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
}
}
}
This would produce following result:
1.9
2.9
3.4
3.5
Passing Arrays to Methods:
Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array:
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2:
printArray(new int[]{3, 1, 2, 6, 4, 2});
Returning an Array from a Method:
A method may also return an array. For example, the method shown below returns an array that is the reversal of another array:
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
Arrays are passed by reference:
Arrays are passed to functions by reference, or as a pointer to the original. This means anything you do to the Array inside the function affects the original.
class ArrayDemo {
public static void passByReference(String a[]){
a[0] = "Changed";
}
public static void main(String args[]){
String []b={"Apple","Mango","Orange"};
System.out.println("Before Function Call "+b[0]);
ArrayDemo.passByReference(b);
System.out.println("After Function Call "+b[0]);
}
}
Problem & Solution:
1. How to sort an array and search an element inside it?
Solution:
Following example shows how to use sort () and binarySearch () method to accomplish the task. The user defined method printArray () is used to display the output:
import java.util.Arrays;
public class MainClass {
public static void main(String args[]) throws Exception {
int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
Arrays.sort(array);
printArray("Sorted array", array);
int index = Arrays.binarySearch(array, 2);
System.out.println("Found 2 @ " + index);
}
private static void printArray(String message, int array[]) {
System.out.println(message
+ ": [length: " + array.length + "]");
for (int i = 0; i < array.length; i++) {
if(i != 0){
System.out.print(", ");
}
System.out.print(array[i]);
}
System.out.println();
}
}
Result:
The above code sample will produce the following result.
Sorted array: [length: 10]
-9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Found 2 @ 5
2. How to sort an array and insert an element inside it?
Solution:
Following example shows how to use sort () method and user defined method insertElement ()to accomplish the task.
import java.util.Arrays;
public class MainClass {
public static void main(String args[]) throws Exception {
int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
Arrays.sort(array);
printArray("Sorted array", array);
int index = Arrays.binarySearch(array, 1);
System.out.println("Didn't find 1 @ "
+ index);
int newIndex = -index - 1;
array = insertElement(array, 1, newIndex);
printArray("With 1 added", array);
}
private static void printArray(String message, int array[]) {
System.out.println(message
+ ": [length: " + array.length + "]");
for (int i = 0; i < array.length; i++) {
if (i != 0){
System.out.print(", ");
}
System.out.print(array[i]);
}
System.out.println();
}
private static int[] insertElement(int original[],
int element, int index) {
int length = original.length;
int destination[] = new int[length + 1];
System.arraycopy(original, 0, destination, 0, index);
destination[index] = element;
System.arraycopy(original, index, destination, index
+ 1, length - index);
return destination;
}
}
Result:
The above code sample will produce the following result.
Sorted array: [length: 10]
-9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Didn't find 1 @ -6
With 1 added: [length: 11]
-9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8
3. How to reverse an array list ?
Solution:
Following example reverses an array list by using Collections.reverse(ArrayList)method.
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
arrayList.add("E");
System.out.println("Before Reverse Order: " + arrayList);
Collections.reverse(arrayList);
System.out.println("After Reverse Order: " + arrayList);
}
}
Result:
The above code sample will produce the following result.
Before Reverse Order: [A, B, C, D, E]
After Reverse Order: [E, D, C, B, A]
4. How to write an array of strings to the output console ?
Solution:
Following example demonstrates writing elements of an array to the output console through looping.
public class Welcome {
public static void main(String[] args){
String[] greeting = new String[3];
greeting[0] = "This is the greeting";
greeting[1] = "for all the readers from";
greeting[2] = "Java Source .";
for (int i = 0; i < greeting.length; i++){
System.out.println(greeting[i]);
}
}
}
Result:
The above code sample will produce the following result.
This is the greeting
For all the readers From
Java source .
5. How to search the minimum and the maximum element in an array ?
Solution:
This example shows how to search the minimum and maximum element in an array by using Collection.max() and Collection.min() methods of Collection class .
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};
int min = (int) Collections.min(Arrays.asList(numbers));
int max = (int) Collections.max(Arrays.asList(numbers));
System.out.println("Min number: " + min);
System.out.println("Max number: " + max);
}
}
Result:
The above code sample will produce the following result.
Min number: 1
Max number: 9
6. How to merge two arrays ?
Solution:
This example shows how to merge two arrays into a single array by the use of list.Addall(array1.asList(array2) method of List class and Arrays.toString () method of Array class.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String args[]) {
String a[] = { "A", "E", "I" };
String b[] = { "O", "U" };
List list = new ArrayList(Arrays.asList(a));
list.addAll(Arrays.asList(b));
Object[] c = list.toArray();
System.out.println(Arrays.toString(c));
}
}
Result:
The above code sample will produce the following result.
[A, E, I, O, U]
7. How to fill (initialize at once) an array ?
Solution:
This example fill (initialize all the elements of the array in one short) an array by using Array.fill(arrayname,value) method and Array.fill(arrayname ,starting index ,ending index ,value) method of Java Util class.
import java.util.*;
public class FillTest {
public static void main(String args[]) {
int array[] = new int[6];
Arrays.fill(array, 100);
for (int i=0, n=array.length; i < n; i++) {
System.out.println(array[i]);
}
System.out.println();
Arrays.fill(array, 3, 6, 50);
for (int i=0, n=array.length; i< n; i++) {
System.out.println(array[i]);
}
}
}
Result:
The above code sample will produce the following result.
100
100
100
100
100
100
100
100
100
50
50
50
8. How to extend an array after initialisation?
Solution:
Following example shows how to extend an array after initialization by creating an new array.
public class Main {
public static void main(String[] args) {
String[] names = new String[] { "A", "B", "C" };
String[] extended = new String[5];
extended[3] = "D";
extended[4] = "E";
System.arraycopy(names, 0, extended, 0, names.length);
for (String str : extended){
System.out.println(str);
}
}
}
Result:
The above code sample will produce the following result.
A
B
C
D
E
9. How to remove an element of array?
Solution:
Following example shows how to remove an element from array.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList objArray = new ArrayList();
objArray.clear();
objArray.add(0,"0th element");
objArray.add(1,"1st element");
objArray.add(2,"2nd element");
System.out.println("Array before removing an
element"+objArray);
objArray.remove(1);
objArray.remove("0th element");
System.out.println("Array after removing an
element"+objArray);
}
}
Result:
The above code sample will produce the following result.
Array before removing an element[0th element,
1st element, 2nd element]
Array after removing an element[2nd element]
10. How to remove one array from another array?
Solution:
Following example uses Removeall method to remove one array from another.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList objArray = new ArrayList();
ArrayList objArray2 = new ArrayList();
objArray2.add(0,"common1");
objArray2.add(1,"common2");
objArray2.add(2,"notcommon");
objArray2.add(3,"notcommon1");
objArray.add(0,"common1");
objArray.add(1,"common2");
objArray.add(2,"notcommon2");
System.out.println("Array elements of array1" +objArray);
System.out.println("Array elements of array2" +objArray2);
objArray.removeAll(objArray2);
System.out.println("Array1 after removing
array2 from array1"+objArray);
}
}
Result:
The above code sample will produce the following result.
Array elements of array1[common1, common2, notcommon2]
Array elements of array2[common1, common2, notcommon,
notcommon1]
Array1 after removing array2 from array1[notcommon2]
11. How to find common elements from arrays?
Solution:
Following example shows how to find common elements from two arrays and store them in an array.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList objArray = new ArrayList();
ArrayList objArray2 = new ArrayList();
objArray2.add(0,"common1");
objArray2.add(1,"common2");
objArray2.add(2,"notcommon");
objArray2.add(3,"notcommon1");
objArray.add(0,"common1");
objArray.add(1,"common2");
objArray.add(2,"notcommon2");
System.out.println("Array elements of array1"+objArray);
System.out.println("Array elements of array2"+objArray2);
objArray.retainAll(objArray2);
System.out.println("Array1 after retaining common
elements of array2 & array1"+objArray);
}
}
Result:
The above code sample will produce the following result.
Array elements of array1[common1, common2, notcommon2]
Array elements of array2[common1, common2, notcommon,
notcommon1]
Array1 after retaining common elements of array2 & array1
[common1, common2]
12. How to find an object or a string in an Array?
Solution:
Following example uses Contains method to search a String in the Array.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList objArray = new ArrayList();
ArrayList objArray2 = new ArrayList();
objArray2.add(0,"common1");
objArray2.add(1,"common2");
objArray2.add(2,"notcommon");
objArray2.add(3,"notcommon1");
objArray.add(0,"common1");
objArray.add(1,"common2");
System.out.println("Array elements of array1"+objArray);
System.out.println("Array elements of array2"+objArray2);
System.out.println("Array 1 contains String common2?? "
+objArray.contains("common1"));
System.out.println("Array 2 contains Array1?? "
+objArray2.contains(objArray) );
}
}
Result:
The above code sample will produce the following result.
Array elements of array1[common1, common2]
Array elements of array2[common1, common2, notcommon, notcommon1]
Array 1 contains String common2?? true
Array 2 contains Array1?? false
13. How to check if two arrays are equal or not?
Solution:
Following example shows how to use equals () method of Arrays to check if two arrays are equal or not.
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws Exception {
int[] ary = {1,2,3,4,5,6};
int[] ary1 = {1,2,3,4,5,6};
int[] ary2 = {1,2,3,4};
System.out.println("Is array 1 equal to array 2?? "
+Arrays.equals(ary, ary1));
System.out.println("Is array 1 equal to array 3?? "
+Arrays.equals(ary, ary2));
}
}
Result:
The above code sample will produce the following result.
Is array 1 equal to array 2?? true
Is array 1 equal to array 3?? false
14. How to compare two arrays?
Solution:
Following example uses equals method to check whether two arrays are or not.
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws Exception {
int[] ary = {1,2,3,4,5,6};
int[] ary1 = {1,2,3,4,5,6};
int[] ary2 = {1,2,3,4};
System.out.println("Is array 1 equal to array 2?? "
+Arrays.equals(ary, ary1));
System.out.println("Is array 1 equal to array 3?? "
+Arrays.equals(ary, ary2));
}
}
Result:
The above code sample will produce the following result.
Is array 1 equal to array 2?? true
Is array 1 equal to array 3?? false