Java: Array
What is Array
- Java Array is fixed number of slots.
- Each slot holds a item, and all of them the same type.
- Java Array cannot be resized (cannot add or remove element)
/* example showing array declaration, initialization, and filling out the slots. */ public class Ar { public static void main(String[] args) { // declare var that's array of int datatype int[] xx; // assign the array int items, 10 of them xx = new int[10]; // array assignment for each slot is like this: xx[3] = 7; System.out.print(xx[3] + "\n"); // prints 7 // xx.length returns number of items System.out.print(xx.length + "\n"); // prints 10 // if a array slot has not given a value, it is garbage. // In this specific case, java fills it with 0. for (int i = 0; i < xx.length; i++) { System.out.print(xx[i] + " "); } // prints 0 0 0 7 0 0 0 0 0 0 } }
Array Syntax
- To declare a array type:
TypeOrClass[] varName = …
. - To create a initial array:
varName = new TypeOrClass[n];
.
Assign Value to Array Slots
- After a array is created, you need to assign value to each slot. Like this:
varName[3] = 7;
. - If a array slot isn't initialized, its value is garbage.
Note that code like int[10] varName;
is invalid.
Declare and Initialize Array, Syntax Shortcut
You can use this shortcut syntax int[] xx = {3,7,4};
to declare and initialize array at the same time
// example of array public class Aj { public static void main(String[] args) { int[] xx = {3,7,4}; for (int i = 0; i < xx.length; i++) { System.out.print(xx[i] + " "); } // prints 3 7 4 } }
Resizable Array
If you want to be able to resize array, use ArrayList
.