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];answered = [false, false, false]answered = [0, 0, 0]0is the placeholder forint. Each type has its own, and forbooleanit isfalse.answered = [null, null, null]nullis the placeholder forString. Abooleanalways holdstrueorfalse.answered = []The3in brackets makes an array with 3 elements.
What is in corners?
record Point(double x, double y) { }
Point[] corners = new Point[4];- Four
nulls, the same placeholder as forString - Four
Point(0.0, 0.0)sJava doesn’t call the constructor for you. Every element is a placeholder until the program puts aPointthere. - It is an error, because
Pointneeds anxand ayIt runs fine:new Point[4]makes the array, but noPoints.