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
Ad

More Related Content

What's hot (20)

Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
07 java collection
07 java collection07 java collection
07 java collection
Abhishek Khune
 
Introduction to NumPy
Introduction to NumPyIntroduction to NumPy
Introduction to NumPy
Huy Nguyen
 
17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
Intro C# Book
 
Bowling Game Kata C#
Bowling Game Kata C#Bowling Game Kata C#
Bowling Game Kata C#
Dan Stewart
 
Python list
Python listPython list
Python list
Prof. Dr. K. Adisesha
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
Indu Sharma Bhardwaj
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
Intro C# Book
 
Designing with malli
Designing with malliDesigning with malli
Designing with malli
Metosin Oy
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
Intro C# Book
 
Bnf and ambiquity
Bnf and ambiquityBnf and ambiquity
Bnf and ambiquity
BBDITM LUCKNOW
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
Sunil OS
 
Collection v3
Collection v3Collection v3
Collection v3
Sunil OS
 
A Presentation About Array Manipulation(Insertion & Deletion in an array)
A Presentation About Array Manipulation(Insertion & Deletion in an array)A Presentation About Array Manipulation(Insertion & Deletion in an array)
A Presentation About Array Manipulation(Insertion & Deletion in an array)
Imdadul Himu
 
003 - JavaFX Tutorial - Layouts
003 - JavaFX Tutorial - Layouts003 - JavaFX Tutorial - Layouts
003 - JavaFX Tutorial - Layouts
Mohammad Hossein Rimaz
 
Лекция 9. Поиск кратчайшего пути в графе
Лекция 9. Поиск кратчайшего пути в графеЛекция 9. Поиск кратчайшего пути в графе
Лекция 9. Поиск кратчайшего пути в графе
Mikhail Kurnosov
 
Strings in java
Strings in javaStrings in java
Strings in java
Kuppusamy P
 
Python tuples and Dictionary
Python   tuples and DictionaryPython   tuples and Dictionary
Python tuples and Dictionary
Aswini Dharmaraj
 
OOP V3.1
OOP V3.1OOP V3.1
OOP V3.1
Sunil OS
 
Searching in Arrays
Searching in ArraysSearching in Arrays
Searching in Arrays
Dhiviya Rose
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
Introduction to NumPy
Introduction to NumPyIntroduction to NumPy
Introduction to NumPy
Huy Nguyen
 
17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
Intro C# Book
 
Bowling Game Kata C#
Bowling Game Kata C#Bowling Game Kata C#
Bowling Game Kata C#
Dan Stewart
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
Intro C# Book
 
Designing with malli
Designing with malliDesigning with malli
Designing with malli
Metosin Oy
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
Intro C# Book
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
Sunil OS
 
Collection v3
Collection v3Collection v3
Collection v3
Sunil OS
 
A Presentation About Array Manipulation(Insertion & Deletion in an array)
A Presentation About Array Manipulation(Insertion & Deletion in an array)A Presentation About Array Manipulation(Insertion & Deletion in an array)
A Presentation About Array Manipulation(Insertion & Deletion in an array)
Imdadul Himu
 
Лекция 9. Поиск кратчайшего пути в графе
Лекция 9. Поиск кратчайшего пути в графеЛекция 9. Поиск кратчайшего пути в графе
Лекция 9. Поиск кратчайшего пути в графе
Mikhail Kurnosov
 
Python tuples and Dictionary
Python   tuples and DictionaryPython   tuples and Dictionary
Python tuples and Dictionary
Aswini Dharmaraj
 
Searching in Arrays
Searching in ArraysSearching in Arrays
Searching in Arrays
Dhiviya Rose
 

Similar to Java Foundations: Arrays (20)

07. Arrays
07. Arrays07. Arrays
07. Arrays
Intro C# Book
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
Abdul Samee
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
shafat6712
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
maznabili
 
ch07-arrays.ppt
ch07-arrays.pptch07-arrays.ppt
ch07-arrays.ppt
Mahyuddin8
 
Arrays (Lists) in Python................
Arrays (Lists) in Python................Arrays (Lists) in Python................
Arrays (Lists) in Python................
saulHS1
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
saneshgamerz
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
Praveen M Jigajinni
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
BG Java EE Course
 
array: An object that stores many values of the same type.
array: An object that stores many values of the same type.array: An object that stores many values of the same type.
array: An object that stores many values of the same type.
KurniawanZaini1
 
CSE 1102 - Lecture 6 - Arrays in C .pptx
CSE 1102 - Lecture 6 - Arrays in C .pptxCSE 1102 - Lecture 6 - Arrays in C .pptx
CSE 1102 - Lecture 6 - Arrays in C .pptx
Salim Shadman Ankur
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
Intro C# Book
 
Recurrence Relation
Recurrence RelationRecurrence Relation
Recurrence Relation
NilaNila16
 
Arrays in Java with example and types of array.pptx
Arrays in Java with example and types of array.pptxArrays in Java with example and types of array.pptx
Arrays in Java with example and types of array.pptx
ashwinibhosale27
 
Net (f#) array
Net (f#)  arrayNet (f#)  array
Net (f#) array
DrRajeshreeKhande
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
object oriented programming lab manual .docx
object oriented programming  lab manual .docxobject oriented programming  lab manual .docx
object oriented programming lab manual .docx
Kirubaburi R
 
Java Programming
Java ProgrammingJava Programming
Java Programming
Nanthini Kempaiyan
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
sotlsoc
 
R1-Intro (2udsjhfkjdshfkjsdkfhsdkfsfsffs
R1-Intro (2udsjhfkjdshfkjsdkfhsdkfsfsffsR1-Intro (2udsjhfkjdshfkjsdkfhsdkfsfsffs
R1-Intro (2udsjhfkjdshfkjsdkfhsdkfsfsffs
sabari Giri
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
Abdul Samee
 
ch07-arrays.ppt
ch07-arrays.pptch07-arrays.ppt
ch07-arrays.ppt
Mahyuddin8
 
Arrays (Lists) in Python................
Arrays (Lists) in Python................Arrays (Lists) in Python................
Arrays (Lists) in Python................
saulHS1
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
saneshgamerz
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
BG Java EE Course
 
array: An object that stores many values of the same type.
array: An object that stores many values of the same type.array: An object that stores many values of the same type.
array: An object that stores many values of the same type.
KurniawanZaini1
 
CSE 1102 - Lecture 6 - Arrays in C .pptx
CSE 1102 - Lecture 6 - Arrays in C .pptxCSE 1102 - Lecture 6 - Arrays in C .pptx
CSE 1102 - Lecture 6 - Arrays in C .pptx
Salim Shadman Ankur
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
Intro C# Book
 
Recurrence Relation
Recurrence RelationRecurrence Relation
Recurrence Relation
NilaNila16
 
Arrays in Java with example and types of array.pptx
Arrays in Java with example and types of array.pptxArrays in Java with example and types of array.pptx
Arrays in Java with example and types of array.pptx
ashwinibhosale27
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
object oriented programming lab manual .docx
object oriented programming  lab manual .docxobject oriented programming  lab manual .docx
object oriented programming lab manual .docx
Kirubaburi R
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
sotlsoc
 
R1-Intro (2udsjhfkjdshfkjsdkfhsdkfsfsffs
R1-Intro (2udsjhfkjdshfkjsdkfhsdkfsfsffsR1-Intro (2udsjhfkjdshfkjsdkfhsdkfsfsffs
R1-Intro (2udsjhfkjdshfkjsdkfhsdkfsfsffs
sabari Giri
 
Ad

More from Svetlin Nakov (20)

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

Recently uploaded (20)

Adobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest VersionAdobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest Version
kashifyounis067
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
Adobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest VersionAdobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest Version
kashifyounis067
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 

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