Create an Array in Java



In this article, we will learn to create an Array in Java. Arrays provide an efficient way to manage and access data collections, making them essential for many programming tasks.

What is an Array?

A Java array is an ordered, fixed-size collection of elements of the same data type. Each element in an array is kept at a specific index, beginning with 0. Java arrays may store primitive data types (int, double, char) and objects (like String, Integer).

Creating an Array

In Java, you can create an array just like an object using the new keyword. The syntax of creating an array in Java using the new keyword ?

type[] reference = new type[10];

Where,

  • type is the data type of the elements of the array.
  • reference is the reference that holds the array.

And, if you want to populate the array by assigning values to all the elements one by one using the index ?

reference [0] = value1;
reference [1] = value2;

Example 1

if you want to create an integer array of 5 elements you can create it using the new keyword ?

int[] myArray = new int[5];
//You can populate the array element by element using the array index:
myArray [0] = 101;
myArray [1] = 102;
//You can also create and initialize an array directly using the flower brackets ({}).
int [] myArray = {10, 20, 30, 40, 50}

Example 2

Initializing with a loop, we can use for loop to assign values to an empty array ?

int[] numbers = new int[5]; 
for (int i = 0; i < numbers.length; i++) {
    numbers[i] = (i + 1) * 10; // Assigning values dynamically
}

Example 3

Accessing array elements by their index value and printing them as per the chosen index ?

int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[2]);

Output

30

Conclusion

Arrays in Java are a powerful way to store and manipulate collections of data. By understanding how to declare, create, initialize, and access arrays, you can efficiently handle large sets of values in your Java programs.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-03-07T17:38:36+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements