SlideShare uma empresa Scribd logo
1 de 29
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

Mais conteúdo relacionado

Mais procurados

Regular expressions
Regular expressionsRegular expressions
Regular expressions
Raj Gupta
 

Mais procurados (20)

07. Arrays
07. Arrays07. Arrays
07. Arrays
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
 
PPS Arrays Matrix operations
PPS Arrays Matrix operationsPPS Arrays Matrix operations
PPS Arrays Matrix operations
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
 
Java Quiz Questions
Java Quiz QuestionsJava Quiz Questions
Java Quiz Questions
 
Лекция 2. Интерфейсы и абстрактные классы
Лекция 2. Интерфейсы и абстрактные классыЛекция 2. Интерфейсы и абстрактные классы
Лекция 2. Интерфейсы и абстрактные классы
 
Java codes
Java codesJava codes
Java codes
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
 
Arrays in java language
Arrays in java languageArrays in java language
Arrays in java language
 
Modul Praktek Java OOP
Modul Praktek Java OOP Modul Praktek Java OOP
Modul Praktek Java OOP
 
Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 
Generics in java
Generics in javaGenerics in java
Generics in java
 

Semelhante a Java Foundations: Arrays

arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
Abdul Samee
 
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
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
sotlsoc
 
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
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
irdginfo
 

Semelhante a 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
 

Mais de Svetlin Nakov

Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковДипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Svetlin Nakov
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТСвободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Svetlin Nakov
 
Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)
Svetlin Nakov
 

Mais de Svetlin Nakov (20)

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)
 
Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)
 

Último

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Último (20)

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 

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

Notas do Editor

  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