Java Arrays

tutorial and example
tutorial and example

JAVA ARRAY

An array is an object that stores a collection of values. Array can store two types of collection data: objects and primitives.

An array is a collection of values which are heap memory addresses.

In case of primitive, it stores direct value and in case of object, it stores references to the object.

Array stores its object in a continuous fashion which results into improved access speed.

Example:

Array Initialization

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:

But you can’t miss the keyword new and initialize your array as follows:

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:

Output:

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:

Output: