Java: Arrays
This page shows how to create array in Java.
Array in Java is like a fixed number of slots, each slot holds a item, and all of them the same type.
Here's a example.
/* 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 } }
Things to remember:
- To declare a array type, the syntax is:
type_or_class[] varName = …
. - To create a initial array, the syntax is:
varName = new type_or_class[n];
. - 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 illegal.
Assign Array Slots 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 } }
2-Dimensional Arrays
The syntax to declare 2-dimensional array is this type_or_class[][]
.
public class Ar2 { public static void main(String[] args) { // declaring that xx is a 2-dimensional array int[][] xx; // give the variable a value, and declare its dimensions. xx = new int[3][2]; // assign a value to a array slot xx[0][0] = 6; System.out.print(xx[0][0]); // prints the value of a slot System.out.println(); System.out.print(xx[0].length); // prints the length of a row } }
Note: list-like things such as lists, hash table, see Java: Collection and Map .
Jagged Arrays
You can create a 2D array with m rows and each row have different number of slots.
Array of Objects
Array element can be any object.
See: Java: Array of Objects .
Resizable Array
Array cannot be resized (cannot add element).
If you want to be able to resize array, use ArrayList
. See: Java: Collection and Map