Java Arrays
An array is an object that stores a collection of values. An array can store two types of collection data: objects and primitives.
An array is a collection of values which are heap memory addresses.
In the case of primitive, it stores direct value, and in case of an object, it stores references to the object.
An array stores its object in a continuous fashion which results in improved access speed.
Example:
int[] ArrayNum = new int[] { 1,2,0 }; String[] ArrayObj = new String[] { "Ram", "Mohan", "Roy","INDIA" };
Array Initialization
int array[] // deceleration array[] = new int [2]; //allocation for (int i=0; i<array .length; i++) { // initialization using loop array[i] = i + 5; }
Some valid array:
1. String array[] = {"AA","BB","ss"};
2. int[] a = new int []{1,2,3,4,5};
3. String array2[] = new String[5];
array2[1]= "ZZ";
array2[2]= "SS";
array2[3]= "FF";
4. int intArray2[] = new int[]{0, 1};
5. String[] strArray2 = new String[]{"Summer", "Winter"};
6. int multiArray2[][] = new int[][]{ {0, 1}, {3, 4, 5}};
Another important point to note is that if we declare and initialize an array using two separate lines of code, we’ll use the keyword new to initialize the values. The following lines of code are correct:
int intArray[]; intArray = new int[]{0, 1};
But you can’t miss the keyword new and initialize your array as follows:
int intArray[]; intArray = {0, 1};
Passing Arrays to Methods
As we can pass primitive type values to methods, we can also pass arrays to methods.
For example, the following method displays the elements in an int array.
Example:
public class MyClass { public static void main(String[] args) { printArray(new int[]{1,2,3,4,5,6}); } public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } } }
Output:
1 2 3 4 5 6
printArray(new int[]{1,2,3,4,5,6}); statement invokes the printArray method to display 1,2,3,4,5,6.
Returning an Array from a Method
A method may also return an array. For example, the following method returns an array that is the reversal of another array:
Example:
public class MyClass { public static void main(String[] args) { int array[] = {1,2,3,4,5,6}; for(int x:reverse(array)) { System.out.print(x+", " ); } } 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; } }
Output:
6, 5, 4, 3, 2, 1,