How do I declare and initialize an array in Java?

6    Asked by EdythFerrill in Java , Asked on May 21, 2025

How do you declare and initialize an array in Java? What are the different ways to create arrays with or without predefined values in your Java programs?

Declaring and initializing an array in Java is a fundamental concept, and there are multiple ways to do it depending on your needs—whether you know the values beforehand or just the size.

1. Declare an Array:

To declare an array in Java, you specify the type of elements it will hold, followed by square brackets.

  int[] numbers;

This line declares an array of integers but doesn’t allocate memory yet.

2. Initialize with Size:

If you know how many elements the array will hold but not their values yet, you can initialize it with a fixed size.

  numbers = new int[5];

  • This creates an array that can hold 5 integers.
  • All elements are automatically initialized to 0 (the default for int).

3. Declare and Initialize Together:

  int[] numbers = new int[5];

You can also assign values immediately:

  int[] numbers = {10, 20, 30, 40, 50};

  • This is called array literal initialization.
  • Java automatically calculates the array size based on the number of values.

4. Other Types:

Arrays can hold any data type, including objects:

  String[] names = {"Alice", "Bob", "Charlie"};

Summary:

  • Use new keyword when specifying size.
  • Use curly braces {} for direct value assignment.
  • Arrays in Java are zero-indexed and fixed in size.

So, based on your use case, Java gives you the flexibility to declare and initialize arrays in the way that suits your code best!



Your Answer

Interviews

Parent Categories