How to use Arrays in Java

Google Sponsored Links

Arrays are Collection of similar data types that share common name and memory or 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.
Each item in an array is called an element, and each element is accessed by its numerical index. The total number of elements is called “length” or “size”. Here Index always starts from 0(zero).Array In Java

Declaration and Initialization Of Array:

<Data Type><array Variable>[] = new <Data Type>[size]


int num[] = new int[10];

Google Sponsored Links

float f[] = new float[5];

The following program-ArrayDemo creates an array of integers, puts some values in it, and prints each value to standard output.

class ArrayDemo {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;

// allocates memory for 5 integers
anArray = new int[5];

// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// etc.
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;

System.out.println(“Element at index 0: “+ anArray[0]);
System.out.println(“Element at index 1: “+ anArray[1]);
System.out.println(“Element at index 2: “+ anArray[2]);
System.out.println(“Element at index 3: “+ anArray[3]);
System.out.println(“Element at index 4: “+ anArray[4]);

The output from this program is:

Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500

Declaring a Variable to Refer to an Array

// declares an array of integers
int[] anArray;

Similarly, you can declare arrays of other types:

byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;

You can also place the square brackets after the array’s name:

// this form is discouraged
float anArrayOfFloats[];

Creating, Initializing, and Accessing an Array

One way to create an array is with the new operator. The next statement allocates an array with enough memory for ten integer elements and assigns the array to the anArray variable.

// create an array of integers

int[] anArray = new int[10];

The next few lines assign values to each element of the array:

anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc

Each array element is accessed by its numerical index:

System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);

Alternatively, you can use the shortcut syntax to create and initialize an array:

int[] anArray = { 
    100, 200, 300,
    400, 500, 600, 
    700, 800, 900, 1000

Here the length of the array is determined by the number of values provided between { and }.

You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of square brackets, such as String[][] names. Each element, therefore, must be accessed by a corresponding number of index values.

In the Java programming language, a multidimensional array is simply an array whose components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to vary in length, as shown in the following MultiDimArrayDemoprogram:

class MultiDimArrayDemo {
    public static void main(String[] args) {
        String[][] names = {
            {"Color", "Fruit ", "Games "},
            {"Red", "Orange"}
        // Color Red
        System.out.println(names[0][0] + names[1][0]);
        // Fruit Orange
        System.out.println(names[0][2] + names[1][1]);
The output is:
Color Red
Games Orange

Finally, you can use the built-in length property to determine the size of an array. The code


will print the array’s size to standard output.

Example :

class ArrayExample{
public static void main(String args[]){
int num[],i,j;
num = new int[j];

Now, let’s have a look at another interesting topic

Command Line Argument

  • These are the details that are supplied to program at the time of execution
  • These details get stored inside String args[]
  •  It can be embedded within other programs
  • Huge data can’t be accessed from it
  • It can be accessed by end users

Objective: To take short input during execution


class Table {
public static void main(String args[]){
int num=0;
System.out.println("Invalid Arguments");
num = Integer.parseInt(args[0]);
for(int i=0;i<=10;i++)

For Execution:

java Table 5        // args.lengt = 1
java Table          // args.lengt = 0
java Table 5 6 7    // args.lengt = 3

Octocat - CodedBug github

For working examples of array visit git hub repo at Codedbug

Most Frequently asked questions on Arrays In Java

No, we cannot change the array size. Though there are similar data types available which allow a change in size
Size of an array is mandatory to create an array
No. If you pass, there will be no compile-time error but you will get NegativeArraySizeException at run-time
They are the arrays containing arrays of different length. Jagged arrays are also multidimensional arrays. They are also called as ragged arrays
Answer for this is both yes and no. You cannot store a String in an array of primitive int, it will result in compile time error, but if you create an array of Object and assign String[] to it and then try to store Integer object on it. Compiler won't be able to detect that and it will throw ArrayStoreExcpetion at runtime.
Google Sponsored Links