Saturday, January 11, 2025
HomeProgrammingJava Initialize array

Java Initialize array

In Java, an array can be initialized in several ways. The simplest way is by specifying the size during declaration:

java

int[] arr = new int[5];

This creates an array of size 5 with default values (e.g., 0 for integers).

See also  XML Schema

You can also directly initialize the array with values:

java

int[] arr = {1, 2, 3, 4, 5};

For multi-dimensional arrays, initialize as follows:

java

int[][] arr = {{1, 2}, {3, 4}};

Another approach is using loops to assign values:

See also  CSS Border

java

for (int i = 0; i < arr.length; i++) { arr[i] = i + 1;}

These methods provide flexibility depending on your requirements.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x