SlideShare a Scribd company logo
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

More Related Content

PPTX
18. Java associative arrays
PPTX
Java Foundations: Lists, ArrayList<T>
PPTX
Java Foundations: Data Types and Type Conversion
PPTX
Java Foundations: Maps, Lambda and Stream API
PPTX
17. Java data structures trees representation and traversal
PPTX
20.2 Java inheritance
PPTX
Java Strings
PPTX
20.4 Java interfaces and abstraction
18. Java associative arrays
Java Foundations: Lists, ArrayList<T>
Java Foundations: Data Types and Type Conversion
Java Foundations: Maps, Lambda and Stream API
17. Java data structures trees representation and traversal
20.2 Java inheritance
Java Strings
20.4 Java interfaces and abstraction

What's hot (20)

PPTX
Java Foundations: Basic Syntax, Conditions, Loops
PPTX
Java Foundations: Methods
DOCX
DBMS Practical file 2019 BCAS301P (1).docx
PPT
JAVA Variables and Operators
PPT
Java 8 - CJ
PDF
ITFT-Constants, variables and data types in java
PPT
Collection v3
PPT
16717 functions in C++
 
PPTX
Java Foundations: Objects and Classes
PPT
JDBC
PDF
Sql query patterns, optimized
PPTX
SQL Server TOP(), Ranking, NTILE, and Aggregate Functions
PDF
Windows 10 Nt Heap Exploitation (English version)
PPTX
Java String
PDF
Java SE 8 lambdaで変わる プログラミングスタイル
PPT
Algorithms with-java-advanced-1.0
PDF
MySQL developing Store Procedure
PPT
Java Input Output and File Handling
PDF
Cheat Sheet java
PPT
Exception Handling
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Methods
DBMS Practical file 2019 BCAS301P (1).docx
JAVA Variables and Operators
Java 8 - CJ
ITFT-Constants, variables and data types in java
Collection v3
16717 functions in C++
 
Java Foundations: Objects and Classes
JDBC
Sql query patterns, optimized
SQL Server TOP(), Ranking, NTILE, and Aggregate Functions
Windows 10 Nt Heap Exploitation (English version)
Java String
Java SE 8 lambdaで変わる プログラミングスタイル
Algorithms with-java-advanced-1.0
MySQL developing Store Procedure
Java Input Output and File Handling
Cheat Sheet java
Exception Handling
Ad

Similar to Java Foundations: Arrays (20)

PPTX
07. Arrays
PPTX
arrays-120712074248-phpapp01
PPTX
6_Array.pptx
PPT
07 Arrays
PPT
ch07-arrays.ppt
PPT
Arrays (Lists) in Python................
PDF
CP PPT_Unit IV computer programming in c.pdf
PPT
PPT
array: An object that stores many values of the same type.
PPTX
CSE 1102 - Lecture 6 - Arrays in C .pptx
PPTX
16. Arrays Lists Stacks Queues
PPTX
Recurrence Relation
PPT
js sdfsdfsdfsdfsdfsdfasdfsdfsdfsdaaray.ppt
PPTX
CSE115 C Programming Multidimensional Array Introduction
PPTX
Arrays in Java with example and types of array.pptx
PPTX
Net (f#) array
PPTX
Arrays in programming
DOCX
object oriented programming lab manual .docx
PPTX
Java Programming
PPTX
Chapter 7.1
07. Arrays
arrays-120712074248-phpapp01
6_Array.pptx
07 Arrays
ch07-arrays.ppt
Arrays (Lists) in Python................
CP PPT_Unit IV computer programming in c.pdf
array: An object that stores many values of the same type.
CSE 1102 - Lecture 6 - Arrays in C .pptx
16. Arrays Lists Stacks Queues
Recurrence Relation
js sdfsdfsdfsdfsdfsdfasdfsdfsdfsdaaray.ppt
CSE115 C Programming Multidimensional Array Introduction
Arrays in Java with example and types of array.pptx
Net (f#) array
Arrays in programming
object oriented programming lab manual .docx
Java Programming
Chapter 7.1
Ad

More from Svetlin Nakov (20)

PPTX
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
PPTX
AI за ежедневието - Наков @ Techniverse (Nov 2024)
PPTX
AI инструменти за бизнеса - Наков - Nov 2024
PPTX
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
PPTX
Software Engineers in the AI Era - Sept 2024
PPTX
Най-търсените направления в ИТ сферата за 2024
PPTX
BG-IT-Edu: отворено учебно съдържание за ИТ учители
PPTX
Programming World in 2024
PDF
AI Tools for Business and Startups
PPTX
AI Tools for Scientists - Nakov (Oct 2023)
PPTX
AI Tools for Entrepreneurs
PPTX
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
PPTX
AI Tools for Business and Personal Life
PDF
Дипломна работа: учебно съдържание по ООП - Светлин Наков
PPTX
Дипломна работа: учебно съдържание по ООП
PPTX
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
PPTX
AI and the Professions of the Future
PPTX
Programming Languages Trends for 2023
PPTX
IT Professions and How to Become a Developer
PPTX
GitHub Actions (Nakov at RuseConf, Sept 2022)
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
AI за ежедневието - Наков @ Techniverse (Nov 2024)
AI инструменти за бизнеса - Наков - Nov 2024
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
Software Engineers in the AI Era - Sept 2024
Най-търсените направления в ИТ сферата за 2024
BG-IT-Edu: отворено учебно съдържание за ИТ учители
Programming World in 2024
AI Tools for Business and Startups
AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Entrepreneurs
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
AI Tools for Business and Personal Life
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
AI and the Professions of the Future
Programming Languages Trends for 2023
IT Professions and How to Become a Developer
GitHub Actions (Nakov at RuseConf, Sept 2022)

Recently uploaded (20)

PDF
5 Lead Qualification Frameworks Every Sales Team Should Use
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
top salesforce developer skills in 2025.pdf
PDF
System and Network Administration Chapter 2
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPT
Introduction Database Management System for Course Database
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
Understanding NFT Marketplace Development_ Trends and Innovations.pdf
PPTX
Essential Infomation Tech presentation.pptx
PPTX
FLIGHT TICKET RESERVATION SYSTEM | FLIGHT BOOKING ENGINE API
PPTX
Materi-Enum-and-Record-Data-Type (1).pptx
PPTX
Transform Your Business with a Software ERP System
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
System and Network Administraation Chapter 3
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPT
JAVA ppt tutorial basics to learn java programming
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
5 Lead Qualification Frameworks Every Sales Team Should Use
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
top salesforce developer skills in 2025.pdf
System and Network Administration Chapter 2
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Introduction Database Management System for Course Database
Softaken Excel to vCard Converter Software.pdf
ManageIQ - Sprint 268 Review - Slide Deck
Understanding NFT Marketplace Development_ Trends and Innovations.pdf
Essential Infomation Tech presentation.pptx
FLIGHT TICKET RESERVATION SYSTEM | FLIGHT BOOKING ENGINE API
Materi-Enum-and-Record-Data-Type (1).pptx
Transform Your Business with a Software ERP System
2025 Textile ERP Trends: SAP, Odoo & Oracle
System and Network Administraation Chapter 3
VVF-Customer-Presentation2025-Ver1.9.pptx
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
JAVA ppt tutorial basics to learn java programming
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool

Java Foundations: Arrays

  • 3. The Judge System Sending your Solutions for Automated Evaluation
  • 4. Testing Your Code in the Judge System  Test your code online in the SoftUni Judge system: https://judge.softuni.org/Contests/3294
  • 6. Table of Contents 1. Arrays 2. Array Operations 3. Reading Arrays from the Console 4. For-each Loop 7
  • 7. Arrays in Java Working with 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 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
  • 10.  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
  • 11.  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.
  • 12. Reading Array Using a for Loop or String.split()
  • 13.  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()); }
  • 14.  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
  • 15.  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;
  • 16.  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]); }
  • 17.  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
  • 18. 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();
  • 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 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
  • 21. 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));
  • 23.  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 }
  • 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 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
  • 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
  • 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