A fixed-size data structure in Java lets you store many values of the same data type in a single variable. Arrays hold groups of similar components like integers, floating-point numbers, letters, or objects. In Java, arrays are zero-indexed, which means that the first element is index 0, the second at index 1, and so on.
Declaring and Creating an Array
dataType[] arrayName;
arrayName = new dataType[arraySize];
- To declare an array define the variable type with the [].
- We can declare the dataType and variable name and then create an array with its size.
You can also declare and build an array in a single line by using the following syntax:
String[] devilFruits = {"Gum-Gum Fruit","Mera Mera No Mi", "Haki"};
Int[] countScore = {"100","33","600"};
Access An Array
String[] devilFruits = { "Gum-Gum Fruit", "Mera Mera No Mi", "Paramecia" };
System.out.println(devilFruits[0]);
- Using the index of the array, we can access the content within it.
Change Array Element
String[] devilFruits = { "Gum-Gum Fruit", "Mera Mera No Mi", "Paramecia" };
devilFruits[1] = "Haki";
System.out.println(devilFruits[1]);
- We can change an array element provided with the index and new content which should be within it.
Length
String[] devilFruits = { "Gum-Gum Fruit", "Mera Mera No Mi", "Paramecia" };
System.out.println(devilFruits.length);
- Using the length method, we can fetch the length of an array.
- This will return 3.