Task 5 of 9 · 0 solved · 9 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

5.1 Arrays — changing and building

Lesson

Writing into an array

You can change an element by assigning to it: arr[i] = value. To make an empty array of a set size, use new int[n] — it creates n slots, each starting at 0. Then fill or update them by index, often in a loop.


Worked example

int[] nums = {1, 2, 3};
for (int i = 0; i < nums.length; i++) {
    nums[i] = nums[i] * 10;   // change each element
}
System.out.println(nums[0] + " " + nums[1] + " " + nums[2]);   // 10 20 30

▶ Try it: run this to multiply every element by 10. Change the multiplier or the starting values and re-run.



How do you set the first element of nums to 5?


What does new int[3] create?


Type what this prints:

int[] a = new int[2];
a[0] = 7;
a[1] = 8;
System.out.println(a[0] + a[1]);

True or false?