Create an Array
In this chapter you will learn:
- How to declare an array type and allocate memory
- What are the default value for different type of array
- What are Alternative Array Declaration Syntax
- How to initialize an array during the declaration
Array creation is a two-step process
There are two steps involved in array creation:
- declare a variable of the desired array type.
- allocate the memory using
new
.
In Java all arrays are dynamically allocated. You can access a specific element in the array with [index]. All array indexes start at zero. For example, the following code assigns the value 28 to the second element of days.
public class Main {
public static void main(String[] argv) {
int days[];/*j av a 2 s .c o m*/
days = new int[12];
days[1] = 28;
System.out.println(days[1]);
}
}
It is possible to combine the declaration of the array variable with the allocation of the array itself.
int month_days[] = new int[12];
Array Element Initialization Values
Different types of array have different default value. For most of the primitive types the default value is 0. For object array the default value is null. The following table lists the default value for various array types.
Element Type | Initial Value |
---|---|
byte | 0 |
int | 0 |
float | 0.0f |
char | '\u0000' |
object reference | null |
short | 0 |
long | 0L |
double | 0.0d |
boolean | false |
Alternative Array Declaration Syntax
The square brackets follow the type specifier, and not the name of the array variable.
type[] var-name;
For example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char d1[][] = new char[3][4];
char[][] d2 = new char[3][4];
Arrays can be initialized when they are declared
When an array is initialized when they are declared the array will be created large enough to hold the number of elements. And there is no need to use new.
public class Main {
public static void main(String args[]) {
//java2s. c o m
int days[] = {31, 28, 31,};
System.out.println("days[2] is " + days[2]);
}
}
The output:
Next chapter...
What you will learn in the next chapter: