Broad Network


Arrays in Java

Java Basics – Part 11

Forward: In this part of the series, I explain how to create and use arrays in Java.

By: Chrysanthus Date Published: 2 Sep 2012

Introduction

This is part 11 of my series, Java Basics. In Java, an array is a set of consecutive objects (fields) of the same type, in memory. In this part of the series, I explain how to create and use arrays in Java. You can have a set of consecutive int objects; you can have a set of consecutive double objects; you can have a set of consecutive boolean objects; you can have a set of consecutive char objects.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

Array of Integers
The following is an array of 5 integers:

        int[] arrInt = {25, 20, 256, 5, 7};

The syntax to create an array is:

        Type[] arrayName = {value1, value2, value3, . . .};

You begin with the type for the objects that will be in the array. Then you have the open and close square brackets. Next you have a space. You then have the variable name for the array. Then you have the assignment operator. Next you have a block delimited by curly brackets. Inside the block, you have the data for the array. All the data must be of the same type. The data are separated by commas. After the last datum, there is no need for a comma. Each datum is kept in an object (region) in memory.

The data in an array has meaning. For example an array of ints might be an array of students marks in a test. The name of the array will have to be related to the meaning of the data. The following is the creation of an array of marks for 10 students.

        int[] marks = {43, 29, 35, 50, 60, 65, 78, 56, 67, 90};

This method of creating an array is referred to as creating the array by initialization or by short cut.

Arrays of doubles, booleans, chars, and Strings
The following is the creation of an array of doubles:

        double[] arrDble = {12.56, 0.258, 5.4, 456.01};

The number of elements in the array of doubles is 4.

The following is the creation of an array of booleans:

        boolean[] arrB = {true, false, false, true, false, true};

The following is the creation of an array of chars:

        char[] arrChar = {'A', 'a', 'C', 'k', 'F', 'Y'};

The following is the creation of an array of Strings:

        String[] theStrs = {"one1", "two2", "three3", "four4", "five5"};

There are five elements in the array of strings.

Creating an Empty Array
The syntax to create an empty array is:

    Type[] arrayName;

This is a complete statement. You begin with the data type such as int for all the elements to be, in the array. Next you have the square brackets (open and close). Then you have a space and then the variable name. Every statement ends with a semicolon.

The array is empty. However, you can go on to allocate empty elements (empty fields) for the array. You do this in another statement as in the following syntax:

    arrayName = new Type[number];

This is an assignment statement. It starts with the array name, then the assignment operator, then the reserved word, new, then the type such as int and then the square brackets. This time the square brackets have a number, which is the number of empty elements. I will explain how to assign values to empty elements of an array below. (In some cases such elements may have default values – see later).

Examples of the above two statements are:

    int[] myArr;
    myArr = new int[10];

The two statements can be combined in one as in:

    int[] myArr = new int[10];

The word, new, here and its role is called the new operator. When you create an array this way, you are creating the array using the new operator.

Index
Elements in an array have positions. Consider the following array:

        int[] marks = {43, 29, 35, 50, 60, 65, 78, 56, 67, 90};

The first element in the array is 43; the second is 29; the third is 35, and so on. The values in an array have positions. These positions are called indices. Index (position) counting in computing and arrays begin from zero, not one. So the index of the value, 43 above is zero; that of 29 is 1; that of 35 is 2; and so on.

Accessing an Array Element
To access a value in an array, you need to know the index of the value. The syntax to access an array element (value) after the array has been created and initialized is:

    arrayName[index]

If you want to access the first element of the above array, you would type:

    marks[0]

To access the second element you would type:

    marks[1]

To access the third element, you would type

    marks[2]

and so on. Always subtract 1 from the English position to have the index.

When accessing an array value, the index should not be more than the array size minus 1.

Assigning and Changing Array Value
When an array is created by initialization, its size is automatically known. When an array is created with the new operator, its size is still known. After defining an array, it is “empty”. However, after the initialization of an array, the array is not “empty”. Whatever is the case, you can assign a value or change the value of an element of an array as follows:

    arrayName[index] = value;

Assume that you want a value of 47 for an int array at index, 5. To assign or change the value at index, 5, you would type:

    marks[5] = 47;

Do not forget the semicolon at the end of the statement (above). Remember, index 5 means English position 6. In the case of changing of value, the old value is lost.

Example 11.1
The following example illustrates the use of an array where the arrays are created using the initialization method:

class ArrEx1
    {
        public static void main(String[] args)
            {
                double[] arrDble = {12.56, 0.258, 5.4, 456.01};
                double dbl = arrDble[0];
                System.out.println(dbl);

                boolean[] arrB = {true, false, false, true, false, true};
                boolean bl =  arrB[1];
                System.out.println(bl);

                char[] arrChar = {'A', 'a', 'C', 'k', 'F', 'Y'};
                char ch =  arrChar[2];
                System.out.println(ch);

                String[] theStrs = {"one", "two", "three", "four", "five"};
                String str =  theStrs[3];
                System.out.println(str);
            }
    }

Read and try the code.

Example 11.2
In the following example, an int array is defined. Five integers are assigned to this array and then displayed. The display is done using a for-loop.

class ArrForLoop
    {
        public static void main(String[] args)
            {
                int[] myInt;
                myInt = new int[5];

                myInt[0] = 8;
                myInt[1] = 63;
                myInt[2] = 55;
                myInt[3] = 78;
                myInt[4] = 2;

                for (int i=0; i<5; ++i)
                    {
                        System.out.println(myInt[i]);
                    }

            }
    }

You now know the basics of array in Java. Let us stop here and continue in the next part of the series.

Chrys
NEXT

Related Articles

Java Course

Comments

Become the Writer's Fan
Send the Writer a Message