In this tutorial, we will learn How Can I Declare And Initialize An Array In Java? As we know array is used for storing similar elements in a sequence. To Initialize an array we need to declare it with the size we want to use.
Array In Java
The array is a data type where we can store the data of a similar type in a single variable, for example, we need to store a list of something or we can say a List of heights of people around can be stored in a variable of a type called array in java where we have to decide the size of the array while declaring.
For better understanding let’s understand more about an array
Declaration Of Array
To use an array first we need to declare it with the size we want. The point to remember here is we can not store more data than the size of the array we declared so keep in mind the expected size of the array and that could be required.
Although if we declare the array of size more than our requirement then it will use the memory more in any case we need to store any extra element then the limited array can not store it but it could store if the size is extra.
Now let’s take an example and declare a new array and store different elements.
int[] myIntArray = new int[3]; // each element of the array is initialised to 0 int[] myIntArray = {1, 2, 3}; int[] myIntArray = new int[]{1, 2, 3}; // Since Java 8. Doc of IntStream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html int [] myIntArray = IntStream.range(0, 100).toArray(); // From 0 to 99 int [] myIntArray = IntStream.rangeClosed(0, 100).toArray(); // From 0 to 100 int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).toArray(); // The order is preserved. int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).sorted().toArray(); // Sort
All the possible ways of the declaration are given above and they all are self-explanatory where we can say there are a number of ways to declare the array and store our data in a single location.
As it stores all data at one location so at the same time it might cause a situation where it is showing as there is no space available to store a new array but actually the memory space is there.
For some, the reason could be as the array stores all the elements on one single location means one after another and due to poor memory management, there might be a situation where the memory required to store the array is not free at one place that is not continuing.
The memory is free at different locations.
The Point to remember here is array could store homogeneous data only means one array can store a single type of data.
And lean more about array declaration at: Declare an Array
And also visit at JAVA TUTORIALfor learning and get solve your other questions.