java · level 1 · unit 6 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
An keeps many values together in one box.
An array is like an egg box: one box with a row of slots. Put the items between curly brackets, split by commas: String[] pets = {"cat", "dog"};. The square brackets mean many strings, not one.
Every must be the same type, so an int[] holds whole numbers only. pets.length tells you how many items there are. Unlike strings, arrays have no brackets after length.
To show every item at once, borrow with import java.util.Arrays; at the top. Remember String[] args in the frame? That is an array too.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] pets = {"cat", "dog", "goldfish"};
int[] ages = {3, 5, 1};
System.out.println(pets.length);
System.out.println(Arrays.toString(pets));
System.out.println(Arrays.toString(ages));
}
} Printing an array without Arrays.toString shows a strange code instead of the items.
guess first
How many pets? Guess first.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
public static void main(String[] args) {
String[] pets = {"cat", "dog", "goldfish"};
System.out.println(pets.length);
}
}
your turn
Your turn. Make your top three.
Fill the array on line 4 with three of your favourite things, each in its own quotes. Then press run to see the array and count it.
output
press run to see what happens
fix it
One snack is stuck to another. Can you fix it?
output
press run to see what happens
- Java is confused by line 4. Look at what sits between the items.
- Every item needs a comma between it and the next one. One comma is missing.
- Add a comma after "apple" on line 4, then press run.
nailed it
you packed lots of values in one box. :D
- An array holds many items of the same type.
.lengthcounts the items, with no brackets.Arrays.toStringshows every item at once.
new words in your collection
- array
- item
- Arrays.toString
This lesson isn’t saved. A free account remembers every lesson you finish.