SlideShare a Scribd company logo
CSE 143
Lecture 1
Arrays (review)
slides created by Marty Stepp
http://www.cs.washington.edu/143/
2
Arrays (7.1)
• array: An object that stores many values of the same type.
– element: One value in an array.
– index: A 0-based integer to access an element from
an array.
index 0 1 2 3 4 5 6 7 8 9
value 12 49 -2 26 5 17 -6 84 72 3
element 0 element 4 element 9
3
Array declaration
type[] name = new type[length];
– Example:
int[] numbers = new int[10];
– All elements' values are initially 0.
index 0 1 2 3 4 5 6 7 8 9
value 0 0 0 0 0 0 0 0 0 0
4
Accessing elements
name[index] // access
name[index] = value; // modify
– Example:
numbers[0] = 27;
numbers[3] = -6;
System.out.println(numbers[0]);
if (numbers[3] < 0) {
System.out.println("value 3 is negative");
}
index 0 1 2 3 4 5 6 7 8 9
value 0 0 0 0 0 0 0 0 0 0
index 0 1 2 3 4 5 6 7 8 9
value 27 0 0 -6 0 0 0 0 0 0
5
Out-of-bounds
• Legal indexes: between 0 and the array's length - 1.
– Reading or writing any index outside this range will throw an
ArrayIndexOutOfBoundsException.
• Example:
int[] data = new int[10];
System.out.println(data[0]); // okay
System.out.println(data[9]); // okay
System.out.println(data[-1]); // exception
System.out.println(data[10]); // exception
index 0 1 2 3 4 5 6 7 8 9
value 0 0 0 0 0 0 0 0 0 0
6
The length field
name.length
• An array's length field stores its number of elements.
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
// output: 0 2 4 6 8 10 12 14
– It does not use parentheses like a String's .length().
7
Quick initialization
type[] name = {value, value, … value};
– Example:
int[] numbers = {12, 49, -2, 26, 5, 17, -6};
– Useful when you know what the array's elements will be.
– The compiler figures out the size by counting the values.
index 0 1 2 3 4 5 6
value 12 49 -2 26 5 17 -6
8
The Arrays class
• Class Arrays in package java.util has useful static
methods for manipulating arrays:
Method name Description
binarySearch(array, value) returns the index of the given value in
a sorted array (< 0 if not found)
copyOf(array, length) returns a new array with same
elements
equals(array1, array2) returns true if the two arrays contain
the same elements in the same order
fill(array, value) sets every element in the array to
have the given value
sort(array) arranges the elements in the array
into ascending order
toString(array) returns a string representing the
array, such as "[10, 30, 17]"
9
Array as parameter
public static type methodName(type[] name) {
– Example:
public static double average(int[] numbers) {
...
}
• Call:
methodName(arrayName);
– Example:
int[] scores = {13, 17, 12, 15, 11};
double avg = average(scores);
10
Array as return
public static type[] methodName(parameters) {
– Example:
public static int[] countDigits(int n) {
int[] counts = new int[10];
...
return counts;
}
• Call:
type[] name = methodName(parameters);
– Example:
int[] tally = countDigits(229231007);
System.out.println(Arrays.toString(tally));
11
Exercise
• Write a method named stutter that accepts an array of
integers as a parameter and returns a new array, twice as
long as the original, with two copies of each original
element.
– If the method were called in the following way:
int[] a = {4, 7, -2, 0, 15};
int[] a2 = stutter(a);
System.out.println("a is " + Arrays.toString(a));
System.out.println("a2 is " + Arrays.toString(a2));
– The output produced would be:
a is [4, 7, -2, 0, 15]
a2 is [4, 4, 7, 7, -2, -2, 0, 0, 15, 15]
12
Exercise solutions
public static int[] stutter(int[] a) {
int[] result = new int[a.length * 2];
for (int i = 0; i < a.length; i++) {
result[2 * i] = a[i];
result[2 * i + 1] = a[i];
}
return result;
}
public static int[] stutter(int[] a) {
int[] result = new int[a.length * 2];
for (int i = 0; i < result.length; i++) {
result[i] = a[i / 2];
}
return result;
}
13
Testing code (bonus)
• Q: How can we tell if our stutter method works properly?
– A: We must test it.
• Q: How do we test code?
– A: Call the method several times and print/examine the results.
• Q: Can we test all possible usages of this method?
Q: Can we prove that the stutter code has no bugs?
– A: No; exhaustive testing is impractical/impossible for most
code.
– A: No; testing finds bugs but cannot prove the absence of
bugs.
14
How to test code
• test case: Running a piece of code once on a given input.
• Q: Which cases should we choose to test?
– equivalence classes of input : Think about kinds of inputs:
• positive vs. negative numbers vs. 0; null (maybe)
• unique values vs. duplicates (consecutive and non-consecutive)
• an empty array; a 1-element array; a many-element array
• Q: What are some properties to look for in testing code?
– boundaries : Hits cases close to a relevant boundary, e.g. the
maximum allowed value, the first/last element in an array, etc.
– code coverage : Hits all paths through code (if/elses, etc.)
– preconditions : What does the method assume? Does the code
ever violate those assumptions?
15
Exercise
• Write a short piece of code that tests the stutter method.
– Decide on a group of test input cases.
– For each test case:
• Print the array's contents before and after stuttering.
• Print whether the test was successful or failed.
16
Exercise solution 1
public static void main(String[] args) {
int[] a1 = {1, 2, 4, 5, 6};
int[] a2 = stutter(a1);
System.out.println(Arrays.toString(a2));
...
}
• Pros:
– simple, short
• Cons:
– must manually check output to see if it is correct
– must copy/paste to create each test case (redundant)
17
Exercise solution 2
public static void main(String[] args) {
test(new int[] {1, 2, 4, 5, 6, 8},
new int[] {1, 1, 2, 2, 4, 4, 5, 5, 6, 6, 8, 8});
test(new int[] {0, 0, 7, 9},
new int[] {0, 0, 0, 0, 7, 7, 9, 9});
test(new int[] {-50, 95, -9876},
new int[] {-50, -50, 95, 95, -9876, -9876});
test(new int[] {42}, new int[] {42, 42});
test(new int[] {}, new int[] {});
}
public static void test(int[] a, int[] expected) {
int[] a2 = stutter(a);
System.out.print(Arrays.toString(a) + " -> " +
Arrays.toString(a2) + " : ");
if (Arrays.equals(a2, expected)) {
System.out.println("Pass");
} else {
System.out.println("FAIL!!!");
}
}
Ad

More Related Content

Similar to array: An object that stores many values of the same type. (20)

An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
Martin Chapman
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
Intro C# Book
 
Array
ArrayArray
Array
PRN USM
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
Svetlin Nakov
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
chandrasekar529044
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
ansariparveen06
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
AqeelAbbas94
 
array Details
array Detailsarray Details
array Details
shivas379526
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
irdginfo
 
Topic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptTopic20Arrays_Part2.ppt
Topic20Arrays_Part2.ppt
adityavarte
 
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
 
Basics of Data structure using C describing basics concepts
Basics of Data structure using C describing basics conceptsBasics of Data structure using C describing basics concepts
Basics of Data structure using C describing basics concepts
shanthidl1
 
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
 
07+08slide.pptx
07+08slide.pptx07+08slide.pptx
07+08slide.pptx
MURADSANJOUM
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
Venkateswarlu Vuggam
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
Adil Jafri
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
Venkateswarlu Vuggam
 
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
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
info309708
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
sotlsoc
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
Martin Chapman
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
Svetlin Nakov
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
irdginfo
 
Topic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptTopic20Arrays_Part2.ppt
Topic20Arrays_Part2.ppt
adityavarte
 
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
 
Basics of Data structure using C describing basics concepts
Basics of Data structure using C describing basics conceptsBasics of Data structure using C describing basics concepts
Basics of Data structure using C describing basics concepts
shanthidl1
 
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
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
Adil Jafri
 
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
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
info309708
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
sotlsoc
 

Recently uploaded (20)

Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
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
 
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
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
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
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
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
 
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
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
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
 
Top 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docxTop 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docx
Portli
 
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
 
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
 
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
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
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
 
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
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
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
 
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
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
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
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
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
 
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
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
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
 
Top 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docxTop 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docx
Portli
 
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
 
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
 
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
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
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
 
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
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Ad

array: An object that stores many values of the same type.

  • 1. CSE 143 Lecture 1 Arrays (review) slides created by Marty Stepp http://www.cs.washington.edu/143/
  • 2. 2 Arrays (7.1) • array: An object that stores many values of the same type. – element: One value in an array. – index: A 0-based integer to access an element from an array. index 0 1 2 3 4 5 6 7 8 9 value 12 49 -2 26 5 17 -6 84 72 3 element 0 element 4 element 9
  • 3. 3 Array declaration type[] name = new type[length]; – Example: int[] numbers = new int[10]; – All elements' values are initially 0. index 0 1 2 3 4 5 6 7 8 9 value 0 0 0 0 0 0 0 0 0 0
  • 4. 4 Accessing elements name[index] // access name[index] = value; // modify – Example: numbers[0] = 27; numbers[3] = -6; System.out.println(numbers[0]); if (numbers[3] < 0) { System.out.println("value 3 is negative"); } index 0 1 2 3 4 5 6 7 8 9 value 0 0 0 0 0 0 0 0 0 0 index 0 1 2 3 4 5 6 7 8 9 value 27 0 0 -6 0 0 0 0 0 0
  • 5. 5 Out-of-bounds • Legal indexes: between 0 and the array's length - 1. – Reading or writing any index outside this range will throw an ArrayIndexOutOfBoundsException. • Example: int[] data = new int[10]; System.out.println(data[0]); // okay System.out.println(data[9]); // okay System.out.println(data[-1]); // exception System.out.println(data[10]); // exception index 0 1 2 3 4 5 6 7 8 9 value 0 0 0 0 0 0 0 0 0 0
  • 6. 6 The length field name.length • An array's length field stores its number of elements. for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); } // output: 0 2 4 6 8 10 12 14 – It does not use parentheses like a String's .length().
  • 7. 7 Quick initialization type[] name = {value, value, … value}; – Example: int[] numbers = {12, 49, -2, 26, 5, 17, -6}; – Useful when you know what the array's elements will be. – The compiler figures out the size by counting the values. index 0 1 2 3 4 5 6 value 12 49 -2 26 5 17 -6
  • 8. 8 The Arrays class • Class Arrays in package java.util has useful static methods for manipulating arrays: Method name Description binarySearch(array, value) returns the index of the given value in a sorted array (< 0 if not found) copyOf(array, length) returns a new array with same elements equals(array1, array2) returns true if the two arrays contain the same elements in the same order fill(array, value) sets every element in the array to have the given value sort(array) arranges the elements in the array into ascending order toString(array) returns a string representing the array, such as "[10, 30, 17]"
  • 9. 9 Array as parameter public static type methodName(type[] name) { – Example: public static double average(int[] numbers) { ... } • Call: methodName(arrayName); – Example: int[] scores = {13, 17, 12, 15, 11}; double avg = average(scores);
  • 10. 10 Array as return public static type[] methodName(parameters) { – Example: public static int[] countDigits(int n) { int[] counts = new int[10]; ... return counts; } • Call: type[] name = methodName(parameters); – Example: int[] tally = countDigits(229231007); System.out.println(Arrays.toString(tally));
  • 11. 11 Exercise • Write a method named stutter that accepts an array of integers as a parameter and returns a new array, twice as long as the original, with two copies of each original element. – If the method were called in the following way: int[] a = {4, 7, -2, 0, 15}; int[] a2 = stutter(a); System.out.println("a is " + Arrays.toString(a)); System.out.println("a2 is " + Arrays.toString(a2)); – The output produced would be: a is [4, 7, -2, 0, 15] a2 is [4, 4, 7, 7, -2, -2, 0, 0, 15, 15]
  • 12. 12 Exercise solutions public static int[] stutter(int[] a) { int[] result = new int[a.length * 2]; for (int i = 0; i < a.length; i++) { result[2 * i] = a[i]; result[2 * i + 1] = a[i]; } return result; } public static int[] stutter(int[] a) { int[] result = new int[a.length * 2]; for (int i = 0; i < result.length; i++) { result[i] = a[i / 2]; } return result; }
  • 13. 13 Testing code (bonus) • Q: How can we tell if our stutter method works properly? – A: We must test it. • Q: How do we test code? – A: Call the method several times and print/examine the results. • Q: Can we test all possible usages of this method? Q: Can we prove that the stutter code has no bugs? – A: No; exhaustive testing is impractical/impossible for most code. – A: No; testing finds bugs but cannot prove the absence of bugs.
  • 14. 14 How to test code • test case: Running a piece of code once on a given input. • Q: Which cases should we choose to test? – equivalence classes of input : Think about kinds of inputs: • positive vs. negative numbers vs. 0; null (maybe) • unique values vs. duplicates (consecutive and non-consecutive) • an empty array; a 1-element array; a many-element array • Q: What are some properties to look for in testing code? – boundaries : Hits cases close to a relevant boundary, e.g. the maximum allowed value, the first/last element in an array, etc. – code coverage : Hits all paths through code (if/elses, etc.) – preconditions : What does the method assume? Does the code ever violate those assumptions?
  • 15. 15 Exercise • Write a short piece of code that tests the stutter method. – Decide on a group of test input cases. – For each test case: • Print the array's contents before and after stuttering. • Print whether the test was successful or failed.
  • 16. 16 Exercise solution 1 public static void main(String[] args) { int[] a1 = {1, 2, 4, 5, 6}; int[] a2 = stutter(a1); System.out.println(Arrays.toString(a2)); ... } • Pros: – simple, short • Cons: – must manually check output to see if it is correct – must copy/paste to create each test case (redundant)
  • 17. 17 Exercise solution 2 public static void main(String[] args) { test(new int[] {1, 2, 4, 5, 6, 8}, new int[] {1, 1, 2, 2, 4, 4, 5, 5, 6, 6, 8, 8}); test(new int[] {0, 0, 7, 9}, new int[] {0, 0, 0, 0, 7, 7, 9, 9}); test(new int[] {-50, 95, -9876}, new int[] {-50, -50, 95, 95, -9876, -9876}); test(new int[] {42}, new int[] {42, 42}); test(new int[] {}, new int[] {}); } public static void test(int[] a, int[] expected) { int[] a2 = stutter(a); System.out.print(Arrays.toString(a) + " -> " + Arrays.toString(a2) + " : "); if (Arrays.equals(a2, expected)) { System.out.println("Pass"); } else { System.out.println("FAIL!!!"); } }