beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java Arrays

By Chaitanya Singh | Filed Under: Java Tutorials

What are Arrays in Java?

Arrays are objects which store multiple variables of the same type. It can hold primitive types as well as object references. In fact most of the collection types in Java which are the part of java.util package use arrays internally in their functioning. Since Arrays are objects, they are created during runtime .The array length is fixed.

Features of Array

  1. Arrays are objects
  2. They can even hold the reference variables of other objects
  3. They are created during runtime
  4. They are dynamic, created on the heap
  5. The Array length is fixed

Array Declaration

First let us get in to declaration of array which holds primitive types. The declaration of array states the type of the element that the array holds followed by the identifier and square braces which indicates the identifier is array type.

Example 1: Declaring an array which holds elements of integer type.

int aiMyArray[];

The above statement creates an array reference on the stack.

Different way of declaring an array –
Both the below statements are valid and same!!

int []aiMyArray;
int aiMyArray[];

Compilation error –
Below statement would cause a compilation error as compiler (JVM) doesn’t allocate object until it is actually instantiated to array object.

int aiFirstArray[] = new int[6];

The above statement creates an array of size 6 on the heap. For creation of Array object the JVM needs to know the size of the space to be allocated to the object, so the size need to be specified succeeding the new key word.

If you observe, all the elements of the array will be initialized to 0 as it’s created on the heap. If you want some other values instead of default values you need to specify as follows

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

The above statement declares, constructs and initializes the array.

Array Usage

The array elements can be accessed with the help of the index. aiFirstArray[0] refers to 1 ,aiFirstArray[1] refers to 2 etc. You can access up to aiFirstArray[n-1] where n is the size of the array. Accessing the array with an index greater than or equal to the size of the array leads to NullPointer Exception.

How to get the size of array?
aiFirstArray.length gives the size of the Array.

Example 3: The below example initializes the array elements to 1,2,3,4,5,6 and prints them.

class ArrayInitializing{
  public static void main(String args[]){
     int aiFirstArray[] = new int[6];
     for(int i=0;i<aiFirstArray.length;i++){
         aiFirstArray[i]=i+1;
     }
     for(int i=0;i<aiFirstArray.length;i++){
         System.out.println(aiFirstArray[i]);
     }
  }
}

Garbage collection and Arrays

aiFirstArray=null;

The above statement makes the array to point to null, means the array object which was on the heap is ready for garbage collection. Referring to array object now gives a NullPointer Exception.

Multidimensional Arrays

Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other array. These are also called Jagged Arrays.

Example:

int aiMdArray[][]=new int [2][];

The above statement creates an array where it has two elements pointing to null. You need not mention any thing in the second square brace as the individual arrays can be created later.

aiMdArray[0]=new int [2];

The above statement initializes the first element to a new array of 2 elements.

aiMdArray[0][0]=10;

The above statement initializes the first element of the first array to 10.

Array of References

Arrays in Java can also hold object references apart from primitives. Let us go through an example which explains Array of Objects.

Example 5: consider a class Employee which has a sub class Trainee

class Employee{}
class Trainee extends Employee{}

Consider this statement:

Employee emp[]=new Employee[3];

The above statement creates only an array of 3 elements which holds 3 employee references emp[0], emp[1], emp[2]. Note that the employee objects are not yet created. Referring to employee objects leads to Runtime Exception.

The following code initializes the employee objects

for(int i=0;i<emp.length;i++){
emp[i]=new Employee();
}

Since the parent class reference can also point to child class objects:

for(int i=0;i<emp.length;i++){
emp[i]=new Trainee();
}

Consider an Interface Salary which is being implemented by Employee.

interface Salary{}
class Employee implements Salary{}

We know that Interface cannot be instantiated, but the reference can be used to point to the objects of the classes that implements it. So we can have a code like the following one –

Salary sal[]=new Salary[2];
sal[0]=new Employee();
sal[1]=new Employee();

Enjoyed this post? Try these related posts

  1. Java Regular Expressions (java regex) Tutorial with examples
  2. Random shuffling of an array in Java
  3. Java Autoboxing and Unboxing with examples
  4. Sort an Array in Descending (Reverse) Order – Java
  5. Sorting float array in Java example
  6. @Override annotation in Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Index
  • Java Introduction
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Control Statements

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor
  • Java Interview Q

MORE ...

  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap