Java OOP – Introduction To Arrays

Table of Contents

Related Tutorials

Whatever the language, arrays are a fundamental part of the language. Arrays are useful for storing data and organizing it in certain ways.

Arrays fall under the category of “homogeneous data structures”. This means that every element in the array belongs to the same type or class.

Up until now we have worked with only two or three variables at a time. In a real application the scenario is quite different. Most of the time we have to work with a large number of variables. For example, there could be 100 or more members in a movie club. Each with a different id and name. In our object oriented concept we have to create 100 objects and give them different names. Consider the User class. If we want to create 100 User objects we would do something like this:

User user1 = new User();
User user2 = new User();
User user3 = new User();

User user100 = new User();

This is a time-consuming monotonous process that should be avoided. After all, we want to avoid repetitive tasks in programming. The idea of Arrays comes handy here.

Remember you do not have to use arrays. Everything in Java and every other language is just a tool, like a hammer or chisel, to make what you want to happen happen effectively. But arrays are just easy and efficient to use. They aren't necessary, but they are convenient. Instead of an array, you could just as easily declare multiple instances of variables of a specific type.
    int num1;
    int num2;
    int num3;

And then, specifically, process the data.


However, as the number of elements grows, this becomes cumbersome.

An array is a collection of elements that are similar. These similar elements could be all ints, all floats, all chars, and so on. An array of characters is commonly referred to as a ‘string,’ whereas an array of ints or floats is simply referred to as an array. Any given array’s elements must all be of the same type. That is, we cannot have an array of ten numbers, five of which are ints and five of which are floats.

Remember our all about data types. We compared variables with a container or more specifically jar. Think of an array as a tray of jars. All of the same sizes. 

Let us first tell you how to declare an array in Java and build our knowledge on top of that.

To declare an array, use square brackets to define the variable type:

int[] numbers;
User[] users;

Arrays are treated as objects in Java. So we have to create an array in the heap. To create a new array we use the new keyword just like creating an object.

numbers = new int[];
users = new User[];

But we also have to declare the size of an array. In simple words, how many same types of data that array will contain. We do it like this:

numbers = new int[10];
users = new User[100];

We can do all this in a single line:

int[] numbers = new int[10];
User[] user = new User[100];

Do not forget to declare the size of an array. If you forget your compiler will complain and won’t let you compile the code. And one other thing, you can not change the size of an array after you have created it.

Arrays Are Objects

An array is a container object that holds a fixed number of single-type values. The length of an array is determined when it is created. Its length is fixed after it is created. You’ve already seen an array example in the main method of the “Hello World!” application.

An array’s items are referred to as elements. An array’s elements are all variables. In other words, a reference variable or one of the eight primitive variable types (think: Large Furry Dog). Anything that can be assigned to a variable of that type can also be assigned to an array element of that type. Each element is accessed by its numerical index. Numbering starts with 0, as shown in the preceding illustration. As a result, the 4th element, for example, would be accessed at index 5. So in an array of type int (int[]), each element can hold an int.

Each element in an User array (User[]) can hold… an User? No, keep in mind that a reference variable only stores a reference (a remote control), not the object itself. As a result, each element in an User array can hold a remote control for an User. Of course, we still need to create the User objects, which you’ll see in the next section.

Take note of one important detail in the image above: the array, despite being an array of primitives, is an object. Whether they’re declared to hold primitives or object references, arrays are always objects. However, an array object can be declared to hold primitive values. In other words, the array object may contain primitive elements, but the array itself is never a primitive. Whatever the array contains, the array itself is always an object!

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

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

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

        System.out.println("Element at index 0: "
                           + numbers[0]);
        System.out.println("Element at index 1: "
                           + numbers[1]);
        System.out.println("Element at index 2: "
                           + numbers[2]);
        System.out.println("Element at index 3: "
                           + numbers[3]);
        System.out.println("Element at index 4: "
                           + numbers[4]);
        System.out.println("Element at index 5: "
                           + numbers[5]);
        System.out.println("Element at index 6: "
                           + numbers[6]);
        System.out.println("Element at index 7: "
                           + numbers[7]);
        System.out.println("Element at index 8: "
                           + numbers[8]);
        System.out.println("Element at index 9: "
                           + numbers[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) in the Control Flow section.

Declaring A Variable To Refer To An Array

The following line of code in the preceding program declares an array (named numbers):

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

An array declaration, like declarations for other types of variables, has two components: the array’s type and the array’s name. The type of an array is written as type[], where type is the data type of the elements contained; the brackets are special symbols indicating that this variable contains an array. The array’s size is not part of its type (which is why the brackets are empty). The name of an array can be anything you want as long as it follows the rules and conventions discussed in the naming section. The declaration, like other types of variables, does not actually create an array; it simply informs the compiler that this variable will hold an array of the specified type.

Similarly, you can declare arrays of other types.

byte[] numbersOfBytes;
short[] numbersOfShorts;
long[] numbersOfLongs;
float[] numbersOfFloats;
double[] numbersOfDoubles;
boolean[] numbersOfBooleans;
char[] numbersOfChars;
String[] numbersOfStrings;

However, this form is discouraged by convention; the brackets identify the array type and should appear alongside the type designation.

Creating, Initializing, And Accessing An Array

The new operator is one way to create an array. The following statement in the ArrayDemo program allocates memory for an array with 10 integer elements and assigns the array to the numbers variable.

// create an array of integers
numbers = new int[10];

If this statement is missing, the compiler generates the following error and compilation fails: Variable numbers may not have been initialized.

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

numbers[0] = 100; // initialize first element
numbers[1] = 200; // initialize second element
numbers[2] = 300; // and so forth

Each array element is accessed by its numerical index:

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

You can also use the shortcut syntax to create and initialize an array:

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

The number of values provided between braces and separated by commas determines the length of the array in this approach.

You can also use two or more sets of brackets, such as String[][] names, to declare an array of arrays (also known as a multidimensional array). Think of it as a tray of trays of jars. Each element of an array of arrays must be accessed by a corresponding number of index values.

A multidimensional array in the Java programming language is an array whose elements are also arrays. This is not the case with arrays in C or Fortran. As a result, the rows can vary in length, as demonstrated by the following MultiDimArrayDemo program:

class MultiDimArrayDemo {
    public static void main(String[] args) {
        String[][] names = {
            {"Mr. ", "Mrs. ", "Ms. "},
            {"Smith", "Jones"}
        // Mr. Smith
        System.out.println(names[0][0] + names[1][0]);
        // Ms. Jones
        System.out.println(names[0][2] + names[1][1]);


The output from this program is:

Mr. Smith
Ms. Jones

Finally, the built-in length property can be used to determine the size of any array. The following code prints the size of the array to standard output:


Loop Through An Array

The for loop can be used to loop through the array elements, and the length property can be used to specify how many times the loop should run.

The following example outputs all elements in the numbers array:

for(int i=0; i<numbers.length; i++){//loopes 10 times

There is another type of for loop in java called for-each loop or enhanced for loop, which is used exclusively to loop through elements in arrays:


for (type variable : arrayname) {

Using a “for-each” loop, the following example outputs all elements in the numbers array:

for(int num:numbers){

The example above can be read like this:

for each int element (called num) in numbers, print out the value of num.

When the for loop and for-each loop are compared, the for-each method is easier to write, does not require a counter (via the length property), and is more readable.

Arrays are a powerful and useful programming concept. Java SE includes methods for performing some of the most common array manipulations. We will discuss them as we go.

Let us wrap this tutorial creating 10 User objects and iterating through the list to print the list.

class User {
    private int userId;
    private String userName;
    public int getUserId() {
        return userId;
    public void setUserId(int uid) {
        userId = uid;
    public String getUserName() {
        return userName;
    public void setUserName(String name) {
        userName = name;
public class UserArrayDemo {
    public static void main(String[] args) {
        //An array to hold 10 User type variables
        User[] users = new User[10];
        // creating 10 users
        for (int i = 0; i < 10; i++) {
            users[i] = new User();
        // setting users ids and names
        // printing users informations
        for (User user : users) {
            System.out.println("User [userId=" + user.getUserId()+", userName="+user.getUserName()+"]");

Share The Tutorial With Your Friends