Java Array Introduction

Arrays are an important aspect of any programming language.

An array is a group of like-typed variables that are referred to by a common name.

An array is a set of variables that is referenced by using a single variable name combined with an index number. Each item of an array is called an element.

All the elements in an array must be of the same type.

Arrays of any type can be created and may have one or more dimensions.

A specific element in an array is accessed by its index.

Arrays offer a convenient means of grouping related information.

The array itself has a type that specifies what kind of elements it can contain.

An *int* array can contain *int* values, for example, and a String array can contain strings.

Array Index

The index number is written after the variable name and enclosed in brackets.

So if the variable name is *x*, you could access a specific element with an expression like *x[10]*.

You might think that x[7] would refer to the seventh element in the array.

But index numbers start with zero for the first element, so x[7] actually refers to the eighth element.

Example


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

        // allocates memory for 10 integers
        anArray = new int[10];
           
        // initialize first element
        anArray[0] = 100;
        // initialize second element
        anArray[1] = 200;
        // and so forth
        anArray[2] = 300;
        anArray[3] = 400;
        anArray[4] = 500;
        anArray[5] = 600;
        anArray[6] = 700;
        anArray[7] = 800;
        anArray[8] = 900;
        anArray[9] = 1000;

        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]);
        System.out.println("Element at index 5: "
                           + anArray[5]);
        System.out.println("Element at index 6: "
                           + anArray[6]);
        System.out.println("Element at index 7: "
                           + anArray[7]);
        System.out.println("Element at index 8: "
                           + anArray[8]);
        System.out.println("Element at index 9: "
                           + anArray[9]);
    }
} 

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
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000

In a real-world programming situation, you would probably use one of the supported looping constructs to iterate through each element of the array, rather than write each line individually as in the preceding example. However, the example clearly illustrates the array syntax. You will learn about the various looping constructs (for, while, and do-while).

One-Dimensional Arrays

A one-dimensional array is a list of like-typed variables.

To create an array, you first must create an array variable of the desired type.

The general form of a one-dimensional array declaration is

type var-name[ ];

Here, type declares the element type of the array.

The element type determines the data type of each element that comprises the array.

Thus, the element type for the array determines what type of data the array will hold.

For example, the following declares an array named month_days with the type “array of int”:

int month_days[];

Note

Even though an array has no corresponding class file, an array is still an object.

You can refer to the array object as a whole, rather than to a specific element of the array, by using the array’s variable name without an index.

Thus, if *x[5]* refers to an element of an array, *x* refers to the array itself.

Array Length

An array has a fixed length that’s set when the array is created.

This length determines the number of elements that can be stored in the array.

The maximum index value you can use with any array is one less than the array’s length.

Thus, if you create an array of ten elements, you can use index values from 0 to 9.

You can’t change the length of an array after you create the array.

You can access the length of an array by using the length field of the array variable. *x.length*, for example, returns the length of the array *x*.

Creating Arrays

Before you can create an array, you must declare a variable that refers to the array.

This variable declaration should indicate the type of elements that are stored by the array followed by a set of empty brackets, like this:

String[] names;

Here a variable named names is declared.

Its type is an array of String objects.

Alternative Array Declaration Syntax

Java also lets you put the brackets on the variable name rather than on the type.

There is a second form that may be used to declare an array:

type[] var-name;

Here, the square brackets follow the type specifier, and not the name of the array variable.

The following two statements both create arrays of int elements:

int[] array1;   // an array of int elements 
int array2[];   // another array of int elements

Both of these statements have exactly the same effect.

For example, the following two declarations are equivalent:

int al[] = new int[3];
int[] a2 = new int[3];

The following declarations are also equivalent:

char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];

The following,

int[] nums, nums2, nums3; // create three arrays

creates three array variables of type int. It is the same as writing

int nums[], nums2[], nums3[]; // create three arrays

Most Java programmers prefer to put the brackets on the type rather than on the variable name.

That statement doesn’t create an array; it merely declares a variable that can refer to an array.

You can actually create the array in two ways:

Use the new keyword followed by the array type, this time with the brackets filled in to indicate how many elements the array can hold.

For example:

String[] names; 
names = new String[10];

Here, an array of String objects that can hold ten strings is created.

Each of the strings in this array is initialized to an empty string.

As with any other variable, you can combine the declaration and the creation into one statement:

String[] names = new String[10];

Here the array variable is declared and an array is created in one statement.

Use a special shortcut that lets you create an array and populate it with values in one swoop:

String[] names = {"One", "Two", "Three"};

If you don’t know how many elements the array needs at compile time, you can use a variable or an expression for the array length.

Here’s a routine from a method that stores player names in an array of strings.

It starts by asking the user how many players are on the team. Then it creates an array of the correct size:

System.out.print("How many players? "); 
int count = sc.nextInt();          // sc is a Scanner 
String[] players = new String[count];

Initializing an Array

One way to initialize the values in an array is to simply assign them one by one:

String[] days = new Array[7]; 
days[0] = "Sunday"; 
days[1] = "Monday"; 
days[2] = "Tuesday"; 
days[3] = "Wednesday"; 
days[4] = "Thursday"; 
days[5] = "Friday"; 
days[6] = "Saturday";

Java has a shorthand way to create an array and initialize it with values:

String[] days = { "Sunday", "Monday", "Tuesday", 
                  "Wednesday", "Thursday", 
                  "Friday", "Saturday" };

Here each element to be assigned to the array is listed in an array initializer.

Here’s an example of an array initializer for an int array:

int[] primes = { 2, 3, 5, 7, 11, 13, 17 };

Note: The length of an array created with an initializer is determined by the number of values listed in the initializer.

An alternative way to code an initializer is this:

int[] primes = new int[] { 2, 3, 5, 7, 11, 13, 17 };

To use this type of initializer, you use the new keyword followed by the array type and a set of empty brackets. Then you code the initializer.

More example

Here is a program that creates an array of the number of days in each month:

// Demonstrate a one-dimensional array.
public class Main {
  public static void main(String args[]) {
    int month_days[];
    month_days = new int[12];
    month_days[0] = 31;
    month_days[1] = 28;
    month_days[2] = 31;
    month_days[3] = 30;
    month_days[4] = 31;
    month_days[5] = 30;
    month_days[6] = 31;
    month_days[7] = 31;
    month_days[8] = 30;
    month_days[9] = 31;
    month_days[10] = 30;
    month_days[11] = 31;
    System.out.println("April has " + month_days[3] + " days.");
  }
}

When you run this program, it prints the number of days in April.

As mentioned, Java array indexes start with zero, so the number of days in April is month_days[3] or 30.

Arrays can be initialized when they are declared.

An improved version of the previous program.

public class Main {
  public static void main(String args[]) {

    int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
                         30, 31 };
    System.out.println("April has " + month_days[3] + " days.");
  }
}

That’s it!
You have successfully completed the post. Do Share : )

Peace Out!

Also Read – Java Bitwise Operators


Check Out Deals on -> Amazon , Flipkart , Myntra , Adidas , Apple TV , Boat , Canva , Beardo , Coursera , Cleartrip , Fiverr , MamaEarth , SwiggyKFC


Leave a Reply

Your email address will not be published.