☰ Contents Collecting Values

Arrays of Unusual Size

Student: Do you always have to type out all the elements of an array?
Prof: How do you mean?
Student: Well, like, I know programs can work with really big data. So when you have an array with, like, a million numbers in it, do you have to type them all in?
Prof: Ah, I get what you’re asking. No! You can create arrays with a calculated size:
Student: OK, so the number in brackets is how many elements the array has? I get it. Why are they all zero?
Prof: It turns out Java has a built-in idea of placeholder values, and 0 is the placeholder value for int.
Student: What happens for String then?
Prof: Ah it has a special placeholder called null:
Student: What’s null? Why isn’t it like "" or something?
Prof: Ah we will say more about null very soon. For now we won’t use null as a value, it’ll just be in arrays that we create and we’ll always fill them in before we use them.
Student: OK so we can use new Type[count] to make an array of count elements. And it works for any type?
Prof: That’s right. We call it array creation.

Practice

What is scores.length?

String[] names = { "Ada", "Alan", "Grace" };
double[] scores = new double[names.length + 1];

What does the book show for answered?

boolean[] answered = new boolean[3];
  1. answered = [false, false, false]
  2. answered = [0, 0, 0]
    0 is the placeholder for int. Each type has its own, and for boolean it is false.
  3. answered = [null, null, null]
    null is the placeholder for String. A boolean always holds true or false.
  4. answered = []
    The 3 in brackets makes an array with 3 elements.

What is in corners?

record Point(double x, double y) { }
Point[] corners = new Point[4];
  1. Four nulls, the same placeholder as for String
  2. Four Point(0.0, 0.0)s
    Java doesn’t call the constructor for you. Every element is a placeholder until the program puts a Point there.
  3. It is an error, because Point needs an x and a y
    It runs fine: new Point[4] makes the array, but no Points.