Home / Questions / Example of Array Declaration and Initialization
Explanatory Question

Example of Array Declaration and Initialization

👁 169 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

Declaring and then Initializing:


int[] arr;       // Declares an array of integers
arr = new int[5]; // Initializes the array with 5 elements

Declaration and Initialization Together:


int[] arr = new int[5]; // Declares and initializes an array of 5 integers

Initializing with Values: You can also declare and initialize the array with values at the same time.


int[] arr = {1, 2, 3, 4, 5}; // Declares, initializes, and assigns values

Multi-dimensional Array Declaration: For 2D arrays (or more), the syntax is:


int[][] matrix = new int[3][4]; // Declares a 2D array with 3 rows and 4 columns