OnJava8-Examples/arrays/ArrayOptions.java

77 lines
2.2 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// arrays/ArrayOptions.java
2015-11-14 16:18:05 -08:00
// <20>2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -07:00
// Initialization & re-assignment of arrays.
import java.util.*;
public class ArrayOptions {
public static void main(String[] args) {
// Arrays of objects:
BerylliumSphere[] a; // Local uninitialized variable
BerylliumSphere[] b = new BerylliumSphere[5];
2015-06-15 17:47:35 -07:00
// The references inside the array are
// automatically initialized to null:
2015-11-03 12:00:44 -08:00
System.out.println("b: " + Arrays.toString(b));
2015-06-15 17:47:35 -07:00
BerylliumSphere[] c = new BerylliumSphere[4];
for(int i = 0; i < c.length; i++)
if(c[i] == null) // Can test for null reference
c[i] = new BerylliumSphere();
2015-06-15 17:47:35 -07:00
// Aggregate initialization:
BerylliumSphere[] d = { new BerylliumSphere(),
new BerylliumSphere(), new BerylliumSphere()
};
2015-06-15 17:47:35 -07:00
// Dynamic aggregate initialization:
a = new BerylliumSphere[]{
new BerylliumSphere(), new BerylliumSphere(),
};
2015-06-15 17:47:35 -07:00
// (Trailing comma is optional in both cases)
2015-11-03 12:00:44 -08:00
System.out.println("a.length = " + a.length);
System.out.println("b.length = " + b.length);
System.out.println("c.length = " + c.length);
System.out.println("d.length = " + d.length);
2015-06-15 17:47:35 -07:00
a = d;
2015-11-03 12:00:44 -08:00
System.out.println("a.length = " + a.length);
2015-06-15 17:47:35 -07:00
// Arrays of primitives:
int[] e; // Null reference
int[] f = new int[5];
2015-06-15 17:47:35 -07:00
// The primitives inside the array are
// automatically initialized to zero:
2015-11-03 12:00:44 -08:00
System.out.println("f: " + Arrays.toString(f));
2015-06-15 17:47:35 -07:00
int[] g = new int[4];
for(int i = 0; i < g.length; i++)
g[i] = i*i;
int[] h = { 11, 47, 93 };
2015-06-15 17:47:35 -07:00
// Compile error: variable e not initialized:
//!print("e.length = " + e.length);
2015-11-03 12:00:44 -08:00
System.out.println("f.length = " + f.length);
System.out.println("g.length = " + g.length);
System.out.println("h.length = " + h.length);
2015-06-15 17:47:35 -07:00
e = h;
2015-11-03 12:00:44 -08:00
System.out.println("e.length = " + e.length);
2015-06-15 17:47:35 -07:00
e = new int[]{ 1, 2 };
2015-11-03 12:00:44 -08:00
System.out.println("e.length = " + e.length);
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
b: [null, null, null, null, null]
a.length = 2
b.length = 5
c.length = 4
d.length = 3
a.length = 3
f: [0, 0, 0, 0, 0]
f.length = 5
g.length = 4
h.length = 3
e.length = 3
e.length = 2
2015-09-07 11:44:36 -06:00
*/