Introduction to Arrays in Java

Arrays are data structures that hold a group of elements and each element has a position denoted by an integer called the index of that element.  

 

Important properties of arrays

Important properties of arrays are:

  1. Array indexes (element positions) have to be integers and start at 0. 

  2. Arrays are allocated continuous memory locations and the array name holds a reference to the beginning of this memory block.

  3. The array name is a reference variable that contains a reference to an array object.

    • An array name contains the address of the first element of the array. 

  4. Individual elements can be located in constant time (unlike a linked list).

    • As we know the start address (from name of array) and size of each array element, we can calculate the exact memory location of the element from the start and the position(index) of the element. 

  5. The java.util.Arrays class is an utility class for arrays that support many operations against arrays such as copying, sorting, comparing etc. 

  6. The alternative to arrays is the ArrayList class, which is part of Java Collections framework, and is similar to arrays, but is not fixed in size like arrays.

  7. The ArrayList class can be used instead of arrays mainly when the size of the collection cannot be predicted exactly.

  8. Arrays can be one dimensional (linear list), two dimensional (like a matrix), three dimensional and so on.

  9. An array of objects is actually an array of object references. Each element of the array is a reference to an actual object.

  10. Note that like any objects, arrays has a toString method (e.g. myArray.toString()) and it will print something like [I@192d342. 

 

Declaring and initializing one dimensional arrays

One dimensional arrays will have one set of elements stored linearly and each element is identified using a single index variable.

 

Declaration of a one dimensional array without initialization

A one dimensional arrays can be declared as:

int[] myArray; or

int myArray[];

  • Note that the square bracket can come before or after the array name.

 

Multiple variables can be declared together (similar to any other variable declaration) in one line as:

int[] myArray1, myArray2; or

int myArray1[], myArray2[];

 

Declaring a one dimensional array allocating space

Arrays can be declared and allocated space as:

myArray = new int [5];

 

We can combine declaration and allocation into an initializer (similar to any other variable) as:    

int[] myArray = new int [5]; or

int myArray [] = new int [5];

 

Initializing array using the short hand syntax

You can also initialize an array with custom constant values using an initializer and the array will be allocated with enough space required and then initialized with those values:

int[] myArray = {1,2,3,4,5};

  • Now size of the array will be taken as 5 and we don't have to initialize with a size explicitly.

 

Important points to remember about declarations and initializations

  1. Number of brackets in declaration (left side) correspond to the dimension.

  2. We can have the brackets anywhere within the declaration, combine declaration and initialization etc.

  3. You can change the position of brackets in the declaration part of the array (left side) but not in the space allocation part (right side).

  4. The elements of an array are initialized to default values specific to the data type (e.g. 0 for int, null for class etc.) when you allocate space.

  5. You can't specify size for declarations (left side).

    • int i[4] = { 1, 2, 3, 4 } is NOT legal.

  6. The array will be allocated with enough space required as per your initializer statement and hence you don't have to (or can't) specify size along with the short hand initializer statement.

    • new int[2] {1, 2} is NOT legal

  7.  You can specify empty arrays or arrays with 0 size.

    • int[ ] i = {} ;

  8. Null array is not same as empty array.

    • If you try to access an element in a null array, you will get NullPointerException.

    • f you try to access an element in an empty array, you will get ArrayIndexOutOfBoundsException.

  9. The length property of the Array returns the number of elements in the array: Int length = myArray.length;

    • length is not a method like String’s length() method, but a property of any array.

  10. Array constants can only be used in initializers (with declaration and initialization in single line).

    • myArray = {1,2,3,4,5} won't compile is note done form the same line as declaration of myArray.

 

Accessing elements of an array

You can access individual elements of an array using syntax myArray[index] as:

myArray[0]

myArray[1]

myArray[2]

The first index of an array is 0.

The largest index of an array is its length - 1.

If you try to access an array using an index outside the range, say myArray[5], you will get ArrayIndexOutOfBoundsException.

 

Traversing an array

Arrays can be iterated using a for loop as:

for(int i=0;i< myArray.length;i++)

{

  System.out.println(myArray[i]);

}

  • Arrays (and collections such as the ArrayList) can also be iterated using the for-each loop, making use of iterators. 

  • You may use other loops as well.

 

Passing arrays to methods

Variables are passed by value to a method in Java ie, the value of the variable is passed and is copied to a method parameter variable (local variable declared in the signature); any change to the variable within the method will not affect the original variable.

An array name contains reference to the array object. When arrays are passed to a method, the array object reference is passed and copied to the method’s parameter. Hence the method parameter variable is also referring to the original array and any change made within the method will reflect in the original array.   

However, if we change the method parameter variable to point to a new array, the original array variable will not be modified.

Try out the questions 1 and 2 below for better understanding.

 

Check your understanding examples

Question 1

Find output:

public static void main(String[] args) {

    int arr[]={1,2,3};

    System.out.println("Original Array before passing.");

    printArray(arr);

    checkChange(arr);

    System.out.println("\nOriginal Array after passing.");

    printArray(arr);

  }

  public static void checkChange(int arr1[]){

    arr1[1]=7;

    System.out.println("\nModified Array.");

    printArray(arr1);

  }

  public static void printArray(int arr2[]){

    for(int i: arr2) {

      System.out.print(i+ " ");

    }

  }

 

Question 2

Find output:

public static void main(String[] args) {

    int arr[]={1,2,3};

    System.out.println("Original Array before passing.");

    printArray(arr);

    checkChange(arr);

    System.out.println("\nOriginal Array after passing.");

    printArray(arr);

  }

  public static void checkChange(int arr1[]){

    arr1 = new int[4];

    arr1[1]=7;

    System.out.println("\nModified Array.");

    printArray(arr1);

  }

  public static void printArray(int arr2[]){

    for(int i: arr2) {

      System.out.print(i+ " ");

    }

  }

 

Question 3

Find output:

public static void main(String [] args) {

int [] xx = null;

System.out.println(xx);

}

Quiz Answers

Answer 1

Original Array before passing.

1 2 3

Modified Array.

1 7 3

Original Array after passing.

1 7 3

Answer 2

Original Array before passing.

1 2 3

Modified Array.

0 7 0 0

Original Array after passing.

1 2 3

 

Answer 3

This will print: null.

 We will see more array traversing and other techniques in another note. 

Tags: 

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (55) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (9) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (7) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)