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

What's hot

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
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
Intro C# Book
 
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
 
List in Python
List in PythonList in Python
List in Python
Sharath Ankrajegowda
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
bhavesh prakash
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
Prof. Dr. K. Adisesha
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
DevoAjit Gupta
 
Python Programming
Python Programming Python Programming
Python Programming
Sreedhar Chowdam
 
Java Strings
Java StringsJava Strings
Java Strings
RaBiya Chaudhry
 
Java String
Java String Java String
Java String
SATYAM SHRIVASTAV
 
Python list
Python listPython list
Python list
ArchanaBhumkar
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
Ravi_Kant_Sahu
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
String Handling
String HandlingString Handling
String Handling
Bharat17485
 
non-strict functions, bottom and scala by-name parameters
non-strict functions, bottom and scala by-name parametersnon-strict functions, bottom and scala by-name parameters
non-strict functions, bottom and scala by-name parameters
Philip Schwarz
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
Hermann Hueck
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
Hock Leng PUAH
 

What's hot (20)

20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
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
 
List in Python
List in PythonList in Python
List in Python
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
 
Python Programming
Python Programming Python Programming
Python Programming
 
Java Strings
Java StringsJava Strings
Java Strings
 
Java String
Java String Java String
Java String
 
Python list
Python listPython list
Python list
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
String Handling
String HandlingString Handling
String Handling
 
non-strict functions, bottom and scala by-name parameters
non-strict functions, bottom and scala by-name parametersnon-strict functions, bottom and scala by-name parameters
non-strict functions, bottom and scala by-name parameters
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 

Similar to Java Foundations: Arrays

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
 
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
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
 
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
 
Net (f#) array
Net (f#)  arrayNet (f#)  array
Net (f#) array
DrRajeshreeKhande
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
Java Programming
Java ProgrammingJava Programming
Java Programming
Nanthini Kempaiyan
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
sotlsoc
 
javaArrays.pptx
javaArrays.pptxjavaArrays.pptx
javaArrays.pptx
AshishNayyar11
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
Mrhaider4
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
manish kumar
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................
suchitrapoojari984
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
JayanthiM19
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
irdginfo
 

Similar to Java Foundations: Arrays (20)

arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
 
ch07-arrays.ppt
ch07-arrays.pptch07-arrays.ppt
ch07-arrays.ppt
 
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
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
Recurrence Relation
Recurrence RelationRecurrence Relation
Recurrence Relation
 
Net (f#) array
Net (f#)  arrayNet (f#)  array
Net (f#) array
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
 
javaArrays.pptx
javaArrays.pptxjavaArrays.pptx
javaArrays.pptx
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
 

More from 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
 
IT Professions and Their Future
IT Professions and Their FutureIT Professions and Their Future
IT Professions and Their Future
Svetlin Nakov
 
How to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a JobHow to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a Job
Svetlin Nakov
 
Призвание и цели: моята рецепта
Призвание и цели: моята рецептаПризвание и цели: моята рецепта
Призвание и цели: моята рецепта
Svetlin Nakov
 
What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?
Svetlin Nakov
 
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
Svetlin Nakov
 

More from Svetlin Nakov (20)

Най-търсените направления в ИТ сферата за 2024
Най-търсените направления в ИТ сферата за 2024Най-търсените направления в ИТ сферата за 2024
Най-търсените направления в ИТ сферата за 2024
 
BG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учителиBG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учители
 
Programming World in 2024
Programming World in 2024Programming World in 2024
Programming World in 2024
 
AI Tools for Business and Startups
AI Tools for Business and StartupsAI Tools for Business and Startups
AI Tools for Business and Startups
 
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)
 
AI Tools for Entrepreneurs
AI Tools for EntrepreneursAI Tools for Entrepreneurs
AI Tools for Entrepreneurs
 
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
 
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
 
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковДипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин Наков
 
Дипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООПДипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООП
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТСвободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
 
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
 
Programming Languages Trends for 2023
Programming Languages Trends for 2023Programming Languages Trends for 2023
Programming Languages Trends for 2023
 
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
 
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)
 
IT Professions and Their Future
IT Professions and Their FutureIT Professions and Their Future
IT Professions and Their Future
 
How to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a JobHow to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a Job
 
Призвание и цели: моята рецепта
Призвание и цели: моята рецептаПризвание и цели: моята рецепта
Призвание и цели: моята рецепта
 
What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?
 
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
 

Recently uploaded

GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
YousufSait3
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Requirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional SafetyRequirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional Safety
Ayan Halder
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
ssuserad3af4
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
Yara Milbes
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 

Recently uploaded (20)

GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Requirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional SafetyRequirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional Safety
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 

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

  1. 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!
  2. 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.
  3. 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.
  4. 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!
  5. // 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); } }
  6. 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!
  7. 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