• Home
  • Arrays of Primitive Data Types – Java

Arrays of Primitive Data Types – Java

In Java, an array is an object that stores a fixed-size sequential collection of elements of the same data type. An array of primitive data types is an array that stores only values of primitive data types such as int, char, and boolean.

Here is an example of how to declare and initialize an array of primitive data types in Java:

int[] intArray = {1, 2, 3, 4, 5}; // declares and initializes an array of integers
char[] charArray = {'a', 'b', 'c'}; // declares and initializes an array of characters
boolean[] boolArray = {true, false, true}; // declares and initializes an array of booleans

To access the elements of an array, you can use the array index. The index of an array starts at 0 and goes up to the size of the array minus 1. For example, to access the first element of the intArray, you can use intArray[0].

You can also use a loop to iterate through all the elements of an array. Here is an example of how to use a for loop to print all the elements of an intArray:

for (int i = 0; i < intArray.length; i++) {
System.out.println(intArray[i]);
}

This will print the values 1, 2, 3, 4, and 5.

You can also use the for-each loop to iterate through an array of primitive data types. Here is an example of how to use a for-each loop to print all the elements of an intArray:

for (int element : intArray) {
System.out.println(element);
}

This will also print the values 1, 2, 3, 4, and 5.