Java Foundations
Arrays in Java
Your Course
Instructors
George Georgiev
Svetlin Nakov
The Judge System
Sending your Solutions
for Automated Evaluation
Testing Your Code in the Judge System
▪ Test your code online in the SoftUni Judge system:
https://judge.softuni.org/Contests/3294
Arrays
Fixed-Size Sequences
of Numbered Elements
Table of Contents
1. Arrays
2. Array Operations
3. Reading Arrays from the Console
4. For-each Loop
7
Arrays in Java
Working with Arrays of Elements
What are Arrays?
▪ In programming, an array is a sequence of elements
Element’s index
Array of 5
0 1 2 3 4
elements … … … … …
Element of an array
▪ Arrays have fixed size (array.length)
cannot be resized
▪ Elements are of the same type (e.g. integers)
▪ Elements are numbered from 0 to length-1
9
10
Working with Arrays
▪ Allocating an array of 10 integers:
int[] numbers = new int[10]; All elements are
initially == 0
▪ Assigning values to the array elements: The length holds
for (int i = 0; i < numbers.length; i++) the number of
array elements
numbers[i] = 1;
▪ Accessing array elements by index: The [] operator
accesses
numbers[5] = numbers[2] + numbers[7]; elements by index
numbers[10] = 1; // ArrayIndexOutOfBoundsException
11
Days of Week – Example
▪ The days of a week can be stored in an array of strings:
String[] days = {
Operator Value
"Monday",
days[0] Monday
"Tuesday",
days[1] Tuesday
"Wednesday",
days[2] Wednesday
"Thursday",
days[3] Thursday
"Friday",
days[4] Friday
"Saturday",
days[5] Saturday
"Sunday"
days[6] Sunday
};
12
Problem: Day of Week
▪ Enter a day number [1…7] and print
the day name (in English) or "Invalid day!"
String[] days = { "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday" };
int day = Integer.parseInt(sc.nextLine());
if (day >= 1 && day <= 7)
System.out.println(days[day - 1]);
The first day in our array
else is on index 0, not 1.
System.out.println("Invalid day!");
Reading Array
Using a for Loop or String.split()
14
Reading Arrays From the Console
▪ First, read the array length from the console :
int n = Integer.parseInt(sc.nextLine());
▪ Next, create an array of given size n and read its elements:
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(sc.nextLine());
}
15
Reading Array Values from a Single Line
▪ Arrays can be read from a single line of separated values
2 8 30 25 40 72 -2 44 56
String values = sc.nextLine();
String[] items = values.split(" ");
int[] arr = new int[items.length];
for (int i = 0; i < items.length; i++)
arr[i] = Integer.parseInt(items[i]);
16
Shorter: Reading Array from a Single Line
▪ Read an array of integers using functional programming:
String inputLine = sc.nextLine();
String[] items = inputLine.split(" "); import
int[] arr = Arrays.stream(items) java.util.Arrays;
.mapToInt(e -> Integer.parseInt(e)).toArray();
int[] arr = Arrays You can chain
.stream(sc.nextLine().split(" ")) methods
.mapToInt(e -> Integer.parseInt(e)).toArray();
17
Printing Arrays on the Console
▪ To print all array elements, a for-loop can be used
▪ Separate elements with white space or a new line
String[] arr = {"one", "two"};
// == new String [] {"one", "two"};
// Process all array elements
for (int i = 0; i < arr.length; i++) {
System.out.printf("arr[%d] = %s%n", i, arr[i]);
}
18
Problem: Reverse an Array of Integers
▪ Read an array of integers (n lines of integers), reverse it and
print its elements on a single line, space-separated:
3 4
10 -1
30 20 10 20 5 99 20 -1
20
30 99
5
19
Solution: Reverse an Array of Integers
// Read the array (n lines of integers)
int n = Integer.parseInt(sc.nextLine());
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = Integer.parseInt(sc.nextLine());
// Print the elements from the last to the first
for (int i = n - 1; i >= 0; i--)
System.out.print(arr[i] + " ");
System.out.println();
20
Printing Arrays with for / String.join(…)
▪ Use for-loop:
String[] arr = {"one", "two"};
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
▪ Use String.join(separator, array): Works only
with strings
String[] strings = { "one", "two" };
System.out.println(String.join(" ", strings)); // one two
int[] arr = { 1, 2, 3 };
System.out.println(String.join(" ", arr)); // Compile error
21
Problem: Reverse Array of Strings
▪ Read an array of strings (space separated values), reverse it and
print its elements:
a b c d e e d c b a -1 hi ho w w ho hi -1
▪ Reversing array elements:
exchange
a b c d e
22
Solution: Reverse Array of Strings
String[] elements = sc.nextLine().split(" ");
for (int i = 0; i < elements.length / 2; i++) {
String oldElement = elements[i];
elements[i] = elements[elements.length - 1 - i];
elements[elements.length - 1 - i] = oldElement;
}
System.out.println(String.join(" ", elements));
For-each Loop
Iterate through Collections
For-each Loop
▪ Iterates through all elements in a collection
▪ Cannot access the current index
▪ Read-only
for (var item : collection) {
// Process the value here
}
25
Print an Array with Foreach
int[] numbers = { 1, 2, 3, 4, 5 };
for (int number : numbers) {
System.out.println(number + " ");
}
12345
26
Problem: Even and Odd Subtraction
▪ Read an array of integers
▪ Sum all even and odd numbers
▪ Find the difference
▪ Examples:
1 2 3 4 5 6 3 2 4 6 8 10 30
3 5 7 9 11 -35 2 2 2 2 2 2 12
27
Solution: Even and Odd Subtraction
int[] arr = Arrays.stream(sc.nextLine().split(" "))
.mapToInt(e -> Integer.parseInt(e)).toArray();
int evenSum = 0;
int oddSum = 0;
for (int num : arr) {
if (num % 2 == 0) evenSum += num;
else oddSum += num;
}
// TODO: Find the difference and print it
Live Exercises
Summary
▪ ▪ Arrays
… hold a sequence of elements
▪ ▪…Elements are numbered
▪ …from 0 to length – 1
▪ Creating (allocating) an array
▪ Accessing array elements by index
▪ Printing array elements
29
Next Steps
▪▪ Join
… the SoftUni "Learn To Code" Community
▪ …
▪ …https://softuni.org
▪ Access the Free Coding Lessons
▪ Get Help from the Mentors
▪ Meet the Other Learners