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

Java Foundations: Arrays

  • 1.
  • 2.
  • 3.
    The Judge System Sendingyour Solutions for Automated Evaluation
  • 4.
    Testing Your Codein the Judge System  Test your code online in the SoftUni Judge system: https://judge.softuni.org/Contests/3294
  • 5.
  • 6.
    Table of Contents 1.Arrays 2. Array Operations 3. Reading Arrays from the Console 4. For-each Loop 7
  • 7.
    Arrays in Java Workingwith Arrays of Elements
  • 8.
     In programming,an array is a sequence of elements  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 What are Arrays? 9 Array of 5 elements Element’s index Element of an array … … … … … 0 1 2 3 4
  • 9.
     Allocating anarray of 10 integers:  Assigning values to the array elements:  Accessing array elements by index: Working with Arrays 10 int[] numbers = new int[10]; for (int i = 0; i < numbers.length; i++) numbers[i] = 1; numbers[5] = numbers[2] + numbers[7]; numbers[10] = 1; // ArrayIndexOutOfBoundsException All elements are initially == 0 The length holds the number of array elements The [] operator accesses elements by index
  • 10.
     The daysof a week can be stored in an array of strings: Days of Week – Example 11 String[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; Operator Value days[0] Monday days[1] Tuesday days[2] Wednesday days[3] Thursday days[4] Friday days[5] Saturday days[6] Sunday
  • 11.
     Enter aday number [1…7] and print the day name (in English) or "Invalid day!" Problem: Day of Week 12 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]); else System.out.println("Invalid day!"); The first day in our array is on index 0, not 1.
  • 12.
    Reading Array Using afor Loop or String.split()
  • 13.
     First, readthe array length from the console :  Next, create an array of given size n and read its elements: Reading Arrays From the Console 14 int n = Integer.parseInt(sc.nextLine()); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(sc.nextLine()); }
  • 14.
     Arrays canbe read from a single line of separated values Reading Array Values from a Single Line 15 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]); 2 8 30 25 40 72 -2 44 56
  • 15.
     Read anarray of integers using functional programming: Shorter: Reading Array from a Single Line 16 int[] arr = Arrays .stream(sc.nextLine().split(" ")) .mapToInt(e -> Integer.parseInt(e)).toArray(); String inputLine = sc.nextLine(); String[] items = inputLine.split(" "); int[] arr = Arrays.stream(items) .mapToInt(e -> Integer.parseInt(e)).toArray(); You can chain methods import java.util.Arrays;
  • 16.
     To printall array elements, a for-loop can be used  Separate elements with white space or a new line Printing Arrays on the Console 17 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]); }
  • 17.
     Read anarray of integers (n lines of integers), reverse it and print its elements on a single line, space-separated: Problem: Reverse an Array of Integers 18 3 10 20 30 30 20 10 4 -1 20 99 5 5 99 20 -1
  • 18.
    Solution: Reverse anArray of Integers 19 // 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();
  • 19.
     Use for-loop: Use String.join(separator, array): Printing Arrays with for / String.join(…) 20 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 String[] arr = {"one", "two"}; for (int i = 0; i < arr.length; i++) System.out.println(arr[i]); Works only with strings
  • 20.
     Read anarray of strings (space separated values), reverse it and print its elements:  Reversing array elements: Problem: Reverse Array of Strings 21 a b c d e e d c b a -1 hi ho w w ho hi -1 a b c d e exchange
  • 21.
    Solution: Reverse Arrayof Strings 22 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));
  • 22.
  • 23.
     Iterates throughall elements in a collection  Cannot access the current index  Read-only For-each Loop for (var item : collection) { // Process the value here }
  • 24.
    int[] numbers ={ 1, 2, 3, 4, 5 }; for (int number : numbers) { System.out.println(number + " "); } Print an Array with Foreach 25 1 2 3 4 5
  • 25.
     Read anarray of integers  Sum all even and odd numbers  Find the difference  Examples: Problem: Even and Odd Subtraction 26 1 2 3 4 5 6 3 3 5 7 9 11 -35 2 4 6 8 10 30 2 2 2 2 2 2 12
  • 26.
    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 Solution: Even and Odd Subtraction 27
  • 27.
  • 28.
     …  … … Summary 29  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  Access the Free Coding Lessons  Get Help from the Mentors  Meet the Other Learners https://softuni.org

Editor's Notes

  • #2 Hello, I am Svetlin Nakov from SoftUni (the Software University). Together with my colleague George Georgiev, we shall teach this free Java Foundations course, which covers important concepts from Java programming, such as arrays, lists, methods, strings, classes, objects and exceptions, and prepares you for the "Java Foundations" official exam from Oracle. In this lesson your instructor George will explain and demonstrate how to work with arrays: reading arrays from the console, processing arrays, using the for-each loop, printing arrays and simple array algorithms. You will learn also how to declare and allocate an array of certain length, two ways to read an array from the console, how to traverse and print the elements from array, how to access an element by index and to modify an element at certain index. Along with the live coding examples, your instructor George will give you some hands-on exercises to gain practical experience with the mentioned coding concepts. Let's start learning arrays!
  • #3 Before the start, I would like to introduce your course instructors: Svetlin Nakov and George Georgiev, who are experienced Java developers, senior software engineers and inspirational tech trainers. They have spent thousands of hours teaching programming and software technologies and are top trainers from SoftUni. I am sure you will like how they teach programming.
  • #4 Most of this course will be taught by George Georgiev, who is a senior software engineer with many years of experience with Java, JavaScript and C++. George enjoys teaching programming very much and is one of the top trainers at the Software University, having delivered over 300 technical training sessions on the topics of data structures and algorithms, Java essentials, Java fundamentals, C++ programming, C# development and many others. I have no doubt you will benefit greatly from his lessons, as he always does his best to explain the most challenging concepts in a simple and fun way.
  • #5 Before we dive into the course, I want to show you the SoftUni judge system, where you can get instant feedback for your exercise solutions. SoftUni Judge is an automated system for code evaluation. You just send your code for a certain coding problem and the system will tell you whether your solution is correct or not and what exactly is missing or wrong. I am sure you will love the judge system, once you start using it!
  • #6 // Solution to problem "01. Student Information". import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String name = sc.nextLine(); int age = Integer.parseInt(sc.nextLine()); double grade = Double.parseDouble(sc.nextLine()); System.out.printf("Name: %s, Age: %d, Grade: %.2f", name, age, grade); } }
  • #7 In programming arrays are indexed sequences of elements, which naturally map to the real-world sequences and sets of objects. In this section, you will learn the concept of "arrays" and how to use arrays in Java: how to declare and allocate an array of certain length, how to read an array from the console, how to traverse and print the elements from array, how to access an element by index and to modify an element at certain index. Working with arrays and lists is an essential skill for the software development profession, so you should spend enough time to learn it in depth. In this course we have prepared many hands-on exercises to practice working with arrays. Don't skip them!
  • #31 Did you like this lesson? Do you want more? Join the learners' community at softuni.org. Subscribe to my YouTube channel to get more free video tutorials on coding and software development. Get free access to the practical exercises and the automated judge system for this coding lesson. Get free help from mentors and meet other learners. Join now! It's free. SOFTUNI.ORG