Introduction to Arrays
What is an Array ?
Java array is an object which contains elements of a similar data type. The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.
Array can contain primitives (int, char, etc.) as well as object (or non-primitive) references of a class depending on the definition of the array. In case of primitive data types, the actual values are stored in contiguous memory locations.
Types of Array in java
There are two types of array.
- Single Dimensional Array
- Multidimensional Array
Single Dimension Array :
A list of items can be given one variable name using only one subscript and such a variable is called a single-subscripted variable or a one-dimensional array. The array subscript or index begins from 0.
Syntax: data_type array_name[Number_of Elements] ;
2-Dimension Array :
This array can be defined as an array of several one-dimensional arrays. It can be visualized in the form of a table with rows and columns. It is an array with two indexes. One index represents the row number and the other the column number.
Syntax: data_type array_name [row size][column size] ;
Multi Dimension Array :
A 2-D array can be defined as an array of several 1-D arrays. Likewise, a 3-D array can be defined as an array of several 2-D arrays. In general, an n-dimensional array can be defined as an array of several (n-1) dimensional arrays.
arr is a 3-D array with 2 two-D arrays. Each 2-D array has 2 rows and 2 columns.
Java code to demonstrate working of array
Java Program to Print the Odd & Even Numbers in an Array
This is a Java Program to Print the Odd & Even Numbers in an Array.
Enter size of array and then enter all the elements of that array. Now using for loop and if codition we use to distinguish whether given integer in the array is odd or even.
Enter no. of elements you want in array:5 Enter all the elements: 1 2 3 4 5 Odd numbers:1 3 5 Even numbers:2 4