Array concept in java with example
ARRAY CONCEPT (JAVA)
In Java, an array is a data structure that allows you to store a fixed-size sequence of elements of the same type. An array can be declared by specifying the type of the elements it will contain, followed by the square brackets []
, and then the name of the array. For example, in the program I provided, we declare an integer array called myArray
like this:
int[] myArray = new int[5];
This creates a new array of integers with 5 elements. The new
keyword is used to allocate memory for the array, and the number inside the square brackets (5
in this case) specifies the size of the array.
Once we have declared an array, we can access its individual elements using their index, which is a zero-based integer value that indicates the position of the element in the array. For example, to set the first element of myArray
to the value 10
, we do:
myArray[0] = 10;
Here, myArray[0]
refers to the first element of the array, because array indices start at 0 in Java. We can similarly set the values of the other elements of the array using their indices.
Finally, we can iterate over the elements of an array using a loop, such as a for
loop. In the program I provided, we use a for
loop to print out each element of the myArray
array. The loop counter i
starts at 0 and goes up to myArray.length - 1
, where myArray.length
is the length of the array (which is 5 in this case). Inside the loop, we access each element of the array using its index, which is i
in this case.
Example for array program:
Output :
Thanks for reading!
if need changes comment down
Comments
Post a Comment