Beginner · Arrays and strings · topic 11 of 60 · 25 min
Arrays
Explanation
Why arrays?
Thirty students' marks in thirty separate variables is unmanageable. An array stores many values of the same type under one name, and a loop can process them all. Java arrays have a fixed length chosen when they are created; for lists that grow, you will use ArrayList (module 7).
int[] marks = new int[5]; // five ints, all 0
marks[0] = 78;
marks[1] = 92;
int[] prices = {499, 120, 2999}; // create and fill in one step
String[] cities = {"Delhi", "Pune"};
System.out.println(prices.length); // 3 (a field, no brackets)
System.out.println(prices[2]); // 2999
System.out.println(marks[4]); // 0 (default value)Default values
| Element type | Default |
|---|---|
| int, long, short, byte | 0 |
| double, float | 0.0 |
| boolean | false |
| char | '\u0000' (the null character) |
| String and any object | null |
Looping over arrays
int total = 0;
for (int i = 0; i < prices.length; i++) total += prices[i]; // when you need the index
for (int p : prices) System.out.println(p); // when you only need valuesThe Arrays helper class
import java.util.Arrays;
int[] a = {42, 7, 19};
System.out.println(a); // something like [I@1b6d3586 (not the contents!)
System.out.println(Arrays.toString(a)); // [42, 7, 19]
Arrays.sort(a); // sorts in place: [7, 19, 42]
int[] bigger = Arrays.copyOf(a, 5); // [7, 19, 42, 0, 0]
int[] filled = new int[4];
Arrays.fill(filled, -1); // [-1, -1, -1, -1]
System.out.println(Arrays.equals(a, new int[]{7, 19, 42})); // true
System.out.println(a == new int[]{7, 19, 42}); // false (different objects)Arrays are objects
An array variable holds a reference. int[] b = a; does not copy the elements; both names point to the same array, so changing b[0] changes a[0]. To copy, use a.clone() or Arrays.copyOf(a, a.length). Passing an array to a method passes the reference, so the method can change the caller's elements.
int[] a = {1, 2, 3};
int[] b = a; // same array
b[0] = 100;
System.out.println(a[0]); // 100
int[] c = a.clone(); // independent copy
c[1] = 200;
System.out.println(a[1]); // 2Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Arrays · 1/6
In this lesson you will store many values of one type in an array.
Prefer a video by a teacher? Find free videos on “java arrays tutorial Arrays.toString sort copyOf” on YouTube ↗
In real life: A week of temperature readings
A weather kiosk at a railway station stores the last seven daily maximum temperatures in an int array, then shows the average and the hottest day.
int[] temps = {34, 36, 38, 35, 41, 39, 37};
int sum = 0, hottest = 0;
for (int i = 0; i < temps.length; i++) {
sum += temps[i];
if (temps[i] > temps[hottest]) hottest = i;
}
System.out.printf("Average %.1f, hottest on day %d (%d°C)%n", sum / 7.0, hottest + 1, temps[hottest]);Practice (0/3 done)
What does this print? int[] a = new int[3]; a[1] = 5; System.out.println(Arrays.toString(a));
What does this print? int[] x = {1, 2, 3}; int[] y = x; y[2] = 9; System.out.println(x[2] + x.length);
Write MarksReport.java with an int array of 8 marks. Print the array with Arrays.toString, the total, the average with 2 decimals, the highest and lowest marks, and how many students scored 60 or more.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Two-dimensional arrays and array algorithmsArrays and strings · same module
- Strings in depthArrays and strings · same module
- StringBuilder and formattingArrays and strings · same module
- Arrays: one name, many valuesC# and .NET · Arrays, strings and null
- ArraysC Programming (from zero to systems) · Functions and arrays
- Arrays, std::array and a first look at std::vectorC++ Programming (modern C++ and DSA) · References, pointers, arrays and strings
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What is the index of the last element of an array a?
Answer: a.length - 1
Indexes run from 0 to length - 1.
What is the default value of elements in new String[4]?
Answer: null
Object elements default to null.
How do you get the length of an array arr?
Answer: arr.length
For arrays, length is a field (no brackets). Strings use length().
Which compares the CONTENTS of two int arrays?
Answer: Arrays.equals(a, b)
== and array.equals compare references.
What is the index of the last item in an array of length 8?Related
Which copies array a (3 ints) into array b?Related
What is the index of the LAST element of an array of size 10?Related
What is the type of [...]int{1, 2, 3}?Related
Answer: [3]int
... asks the compiler to count the elements, so it is an array of length 3.
From Arrays and slices
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 4 more topics in “Arrays and strings” before its exam: Two-dimensional arrays and array algorithms, Strings in depth, StringBuilder and formatting, Wrapper classes and autoboxing.
- Module 3 exam: Arrays and strings · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Classes and objects. 60 topics left in the course before the final exam.