Single dimensional array
One-dimensional arrays are lists of the same typed variables. To create an array, you first need to declare an array variable of the required type.
Syntax to declare
There are two different ways to declare an array –
// First way (Most preferred way) data-type[] array_name; // Second way data-type array_name[];
Declaration example
// First way int[] intArray1; // Second way int intArray2[];
Syntax for Instantiation
Arrays in Java are instantiated just like other objects using the keyword ‘new’.
array_name = new data-type[<array-size>];
Example
Java single dimensional array example, try modifying and changing the values.
import java.util.Arrays; public class SingleDimArray { public static void main(String[] args) { int[] myArray = new int[5]; myArray[0] = 10; myArray[1] = 2; myArray[2] = 7; myArray[3] = 11; myArray[4] = 99; // Printing the string representation of the array System.out.println(Arrays.toString(myArray)); } }
Java allows us to declare, instantiate and assign values to the array using a single line statement even without specifying the size for the array, there are two different ways to achieve it –
// First way int[] myArrayX = new int[]{1, 2, 3, 4, 5}; // Second way int[] myArrayY = {1, 2, 3, 4, 5};
If you notice, here we’ve not specified size for the array, the size of the array is set automatically at runtime.