Line At A Time
Lesson 13: Arrays
Arrays Store a list of numbers in one variable.
1import java.util.Arrays;
2
3public static void main(String[] args) {
4 int[] arr = {1, 2, 3};
5 System.out.println(Arrays.toString(arr));
6}
Terminal
$ javac Main.java
$ java Main
[1, 2, 3]
Every line, explained
import java.util.Arrays;
import lines go at the very top of a Java file and bring in extra tools. java.util.Arrays is a helper class full of useful methods for working with arrays; we need it for Arrays.toString below.
public static void main(String[] args) {
Every Java program starts at the main method. When you run the program, Java looks for this exact line, public static void main(String[] args), and runs everything between its { and } from top to bottom.
int[] arr = {1, 2, 3};
int[] declares an array: a list of values stored in a single variable. In Java the values go between curly braces: {1, 2, 3}. Every item must be the same type (here int). You read items back by their index, which starts at 0: arr[0] is 1, arr[1] is 2 and arr[2] is 3.
System.out.println(Arrays.toString(arr));
Careful: printing an array directly, System.out.println(arr), does NOT show its contents in Java! It prints a strange code like [I@1b6d3586 (the exact letters depend on the array's type). Arrays.toString(arr) converts the array into readable text like [1, 2, 3] first, and that is what we print.
}
This closing curly brace } ends the main method. In Java every opening brace { must have a matching closing brace }.