Java Array
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
Array Declaration (for integers)
To declare an array, define the variable type with square brackets:
Method 1:
int[] values;
values = new int[3]; //allocation in memory
Specifying value to Array
values[0] = 2;
values[1] = 4;
values[2] = 6;
Method 2:
int[] numbers = {5, 6, 7}; //allocation and specifying values
Access the Elements of an Array
You access an array element by referring to the index number.
This statement accesses the value of the first element in int[] values; , numbers:
Code: Output
int[] values;
values = new int[3]; 2
values[0] = 2;
values[1] = 4;
values[2] = 6;
System.out.println(values[0]);
Code: Output
int[] numbers = {5, 6, 7};
7
System.out.println(values[2]);
Index 0 1 2
Array {5 6 7}
Array of Strings Declaration
Method 1:
String[] cars = new String[3]; //allocation in memory
Specifying value to Array
cars[0] = "BMW";
cars[1] = "Porsche";
cars[2] = "Ford";
Method 2:
String[] phones = {"Samsung", "Iphone", "Oppo"};//allocation and specifying
values
Access the Elements of an Array (String[])
You access an array element by referring to the index number.
This statement accesses the value of the first element in String[]cars, phones;:
Code: Output
String[] cars = new String[3];
Ford
cars[0] = "BMW";
cars[1] = "Porsche";
cars[2] = "Ford";
System.out.println(cars[2]);
Code: Output
String[] cars = new String[3];
Samsung
cars[0] = "BMW";
cars[1] = "Porsche";
cars[2] = "Ford";
System.out.println(phones[0]);