In general, arrays are the containers that store multiple variables of the same datatype. These are of fixed size and the size is determined at the time of creation. Each element in an array is positioned by a number starting from 0.
You can access the elements of an array using name and position as −
System.out.println(myArray[3]); //Which is 1457
In Java, arrays are treated as referenced types you can create an array using the new keyword similar to objects and populate it using the indices as −
int myArray[] = new int[7]; myArray[0] = 1254; myArray[1] = 1458; myArray[2] = 5687; myArray[3] = 1457; myArray[4] = 4554; myArray[5] = 5445; myArray[6] = 7524;
Or, you can directly assign values with in flower braces separating them with commas (,) as −
int myArray = { 1254, 1458, 5687, 1457, 4554, 5445, 7524};
You can print the contents of an array
public class PrintingArray { public static void main(String args[]) { //Creating an array int myArray[] = new int[7]; //Populating the array myArray[0] = 1254; myArray[1] = 1458; myArray[2] = 5687; myArray[3] = 1457; myArray[4] = 4554; myArray[5] = 5445; myArray[6] = 7524; //Printing Contents one by one System.out.println("Contents of the array: "); System.out.println(myArray[0]); System.out.println(myArray[1]); System.out.println(myArray[2]); System.out.println(myArray[3]); System.out.println(myArray[4]); System.out.println(myArray[5]); System.out.println(myArray[6]); } }
Contents of the array: 1254 1458 5687 1457 4554 5445 7524
public class PrintingArray { public static void main(String args[]) { //Creating an array int myArray[] = new int[7]; //Populating the array myArray[0] = 1254; myArray[1] = 1458; myArray[2] = 5687; myArray[3] = 1457; myArray[4] = 4554; myArray[5] = 5445; myArray[6] = 7524; //Printing Contents using for loop System.out.println("Contents of the array: "); for(int i=0; i<myArray.length; i++) { System.out.println(myArray[i]); } } }
Contents of the array: 1254 1458 5687 1457 4554 5445 7524
import java.util.Arrays; public class PrintingArray { public static void main(String args[]) { //Creating an array int myArray[] = new int[7]; //Populating the array myArray[0] = 1254; myArray[1] = 1458; myArray[2] = 5687; myArray[3] = 1457; myArray[4] = 4554; myArray[5] = 5445; myArray[6] = 7524; //Printing Contents using for loop System.out.println("Contents of the array: "); System.out.println(Arrays.toString(myArray)); } }
Contents of the array: [1254, 1458, 5687, 1457, 4554, 5445, 7524]