When you declare an array _?

As with declarations for variables of other types, the declaration for an array variable does not create an array and does not allocate any memory to contain array elements. The code must create the array explicitly and assign it to

0 1 2 3 4 5 6 7 8 9
6.

Creating an Array

You create an array explicitly using Java's
0 1 2 3 4 5 6 7 8 9
8 operator. The next statement in the sample program allocates an array with enough memory for ten integer elements and assigns the array to the variable
0 1 2 3 4 5 6 7 8 9
6 declared earlier.
anArray = new int[10];  // create an array of integers
In general, when creating an array, you use the
0 1 2 3 4 5 6 7 8 9
8 operator, plus the data type of the array elements, plus the number of elements desired enclosed within brackets—[ and ].
new elementType[arraySize]
If the
0 1 2 3 4 5 6 7 8 9
8 statement were omitted from the sample program, the compiler would print an error like the following one and compilation would fail.
ArrayDemo.java:4: Variable anArray may not have been initialized.

Array Initializers

You can use a shortcut syntax for creating and initializing an array. Here�s an example:
boolean[] answers = { true, false, true, true, false };
The length of the array is determined by the number of values provided between { and }.

Accessing an Array Element

Now that some memory has been allocated for the array, the program assign values to the array elements:
for (int i = 0; i < anArray.length; i++) {
    anArray[i] = i;
    System.out.print(anArray[i] + " ");

}
This part of the code shows that to refer to an array element, either to assign a value to it or to get its value, you append brackets to the array name. The value between the brackets indicates (with a variable or other expression) the index of the element to access.

Getting the Size of an Array

To get the size of an array, you write
0 1 2 3 4 5 6 7 8 9
0

Be careful: Programmers new to the Java programming language are tempted to follow
int[] anArray;          // declare an array of integers
2 with an empty set of parenthesis. This doesn't work because
int[] anArray;          // declare an array of integers
2 is not a method.
int[] anArray;          // declare an array of integers
2 is a property provided by the Java platform for all arrays.

The

int[] anArray;          // declare an array of integers
5 loop in our sample program iterates over each element of
0 1 2 3 4 5 6 7 8 9
6, assigning values to its elements. The for loop uses anArray.length to determine when to terminate the loop.

Arrays are an important part of the fundamental data structures in Java. And they are incredibly useful in solving a lot of programming problems.

What is an array?

By definition, an array is a collection of data of the same type.

An array is usually declared so you can have multiple values in the same memory – unlike variables where you can only have one value in the memory.

So, arrays let you create one variable that holds different values together, instead of declaring a variable for each value.

The position of a particular data point in the array is called its index, while the data itself is called an element.

In this tutorial, I will show you how to declare an array, initialize it, and loop through it with the for loop and enhanced for loop. Then you can start using it in your Java projects.

I will be using the intelliJIDEA IDE to write the code. You can use it if you want, or you can also use any IDE of your choice.

How to Declare and Intialize an Array in Java

There are two ways you can declare and initialize an array in Java. The first is with the

dataType [] nameOfArray = new dataType [size]
0 keyword, where you have to initialize the values one by one. The second is by putting the values in curly braces.

How to initialize an array with the dataType [] nameOfArray = new dataType [size] 0 keyword

You can declare the array with the syntax below:

dataType [ ] nameOfArray;

dataType [] nameOfArray = new dataType [size]
2: the type of data you want to put in the array. This could be a string, integer, double, and so on.
dataType [] nameOfArray = new dataType [size]
3: signifies that the variable to declare will contain an array of values
dataType [] nameOfArray = new dataType [size]
4: The array identifier.

With the above information, you have only declared the array – you still need to initialize it.

The basic syntax for initializing an array in this way looks like this:

dataType [] nameOfArray = new dataType [size]

The size is usually expressed with a numberic value. It signifies how many values you want to hold in the array. Its value is immutable, meaning you won’t be able to put more than the number specified as the size in the array.

You can now go ahead and put values in the array like this:

package com.kolade;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
   // write your code here
String [] names = new String[3];
names[0] = "Quincy";
names[1] = "Abbey";
names[2] = "Kolade";
   }
}

In the code snippet above, I initialized an array of strings called names (the identifier). The size is 3, so it can only hold three values.

There are 3 indexes in total:

  • The value,
    dataType [] nameOfArray = new dataType [size]
    
    5 is at index
    dataType [] nameOfArray = new dataType [size]
    
    6
  • The value
    dataType [] nameOfArray = new dataType [size]
    
    7 is at index
    dataType [] nameOfArray = new dataType [size]
    
    8
  • The value
    dataType [] nameOfArray = new dataType [size]
    
    9 is at index
    package com.kolade;
    
    import java.util.Arrays;
    
    public class Main {
    
        public static void main(String[] args) {
       // write your code here
    String [] names = new String[3];
    names[0] = "Quincy";
    names[1] = "Abbey";
    names[2] = "Kolade";
       }
    }
    
    0

Don’t be confused by the numbers 0, 1, 2. Arrays are zero-indexed, so counting starts from 0, not 1.

In the array above, if you add extra data – for example,

package com.kolade;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
   // write your code here
String [] names = new String[3];
names[0] = "Quincy";
names[1] = "Abbey";
names[2] = "Kolade";
   }
}
1 – you would get an error because you have specified that the array should only contain 3 values. If you want to add more values, you have to increase the size of the array.

When you declare an array _?

To print the array to the console, you can use the inbuilt

package com.kolade;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
   // write your code here
String [] names = new String[3];
names[0] = "Quincy";
names[1] = "Abbey";
names[2] = "Kolade";
   }
}
2 method:

System.out.println(Arrays.toString(names));

When you declare an array _?

2. How to initialize an array in one line

You can initialize an array in one line with the basic syntax below:

dataType [ ] nameOfArray = {value1, value2, value3, value4}

With this method, you don’t need to specify the size of the array, so you can put any number of values you want in it.

Check out the example in the code snippet below:

package com.kolade;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
   // write your code here
     String [] namesTwo = {"Quincy", "Abbey", "Kolade", "Chris", "Kayode"};
  }
}

Printing the array to the console shows the values like this:

When you declare an array _?

How to Loop Through an Array in Java

You can loop through an array in Java with the for loop and enhanced for loop. With the for loop, you have access to the index of the individual values, but with the enhanced for loop, you don’t.

How to loop through an array with the package com.kolade; import java.util.Arrays; public class Main { public static void main(String[] args) { // write your code here String [] names = new String[3]; names[0] = "Quincy"; names[1] = "Abbey"; names[2] = "Kolade"; } } 3 loop

In Java, you can use the for loop with the basic syntax below:

for (dataType i = 0; i < nameOfArray.length; i++) {
    //   Code to execute
}

You can then loop through the

package com.kolade;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
   // write your code here
String [] names = new String[3];
names[0] = "Quincy";
names[1] = "Abbey";
names[2] = "Kolade";
   }
}
4 array like this:

package com.kolade;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
   // write your code here

        String [] namesTwo = {"Quincy", "Abbey", "Kolade", "Chris", "Kayode"};

        for (int i = 0; i < namesTwo.length; i++) {
            System.out.println("Element at index " + i + " : " + namesTwo[i]);
        }
    }
}

When you declare an array _?

How to loop through an array with the enhanced package com.kolade; import java.util.Arrays; public class Main { public static void main(String[] args) { // write your code here String [] names = new String[3]; names[0] = "Quincy"; names[1] = "Abbey"; names[2] = "Kolade"; } } 3 loop

The enhanced for loop is a cleaner version of the for loop. The downside is that with it, you don’t have access to the index of the individual values in the array.

The basic syntax of the enhanced for loop looks like this:

for (dataType variable : nameOfArray) {
    // Code to execute
}
package com.kolade;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
   // write your code here

        String [] namesTwo = {"Quincy", "Abbey", "Kolade", "Chris", "Kayode"};

        for (String names : namesTwo) {
            System.out.println(names);
        }
    }
}

When you declare an array _?

Conclusion

In this tutorial, you learned how to declare and initialize an array in two different ways – with the new keyword and using curly braces.

You also learned how to loop through arrays with the for loop and enhanced for loop, so you don’t just initialize an array and do nothing with it.

Thank you for reading, and keep coding.

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT


When you declare an array _?
Kolade Chris

Web developer and technical writer focusing on frontend technologies.


If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

What does it mean to declare an array?

An "array declaration" names the array and specifies the type of its elements. It can also define the number of elements in the array. A variable with array type is considered a pointer to the type of the array elements.

When can an array be declared?

When a function parameter is declared as an array, the compiler treats the declaration as a pointer to the first element of the array. For example, if x is a parameter and is intended to represent an array of integers, it can be declared as any one of the following declarations: int x[]; int *x; int x[10];

Which is used to declare an array?

Here are two valid ways to declare an array: int intArray[]; int[] intArray; The second option is oftentimes preferred, as it more clearly denotes of which type intArray is.