0% found this document useful (0 votes)
8 views45 pages

Understanding Java Arrays Basics

This document covers the fundamentals of arrays in computer science, including their declaration, creation, and usage for storing and accessing values. It discusses limitations, multi-dimensional arrays, and common pitfalls, as well as practical exercises for implementing array operations. Additionally, it highlights the concept of pass-by-value and provides a brief overview of simple algorithms related to arrays.

Uploaded by

createursite
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views45 pages

Understanding Java Arrays Basics

This document covers the fundamentals of arrays in computer science, including their declaration, creation, and usage for storing and accessing values. It discusses limitations, multi-dimensional arrays, and common pitfalls, as well as practical exercises for implementing array operations. Additionally, it highlights the concept of pass-by-value and provides a brief overview of simple algorithms related to arrays.

Uploaded by

createursite
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Computer Science 1

Module 5
Arrays
Learning Goals
• You know what arrays are and how to declare them
• You can use an array to store and access values
• You can combine loops and arrays to iterate over values
• You are aware of the limitations of arrays
• You know what multi-dimensional arrays are and how to use them
• You know what pass-by-value means and what the consequences are
• You know the difference between single variables and arrays
• You are aware of common pitfalls when using arrays
Limitations of Variables
Up to now, you need to know how many you
need, BEFORE the program starts.

Consider the following task:


“Write a program that reads in an unspecified number
of values that ends with a letter and write those values
out in sorted order.”
Arrays
Solution:
use variables that can store a number of values
myArray

Created
dynamically,
i.e. length can
be specified at
runtime
Array Definition
A collection of data items, all of the same type,
packaged under a single name/identifier
- Like String or Scanner, it is not a basic data type but
an “object”
- Like Scanner, it needs to be declared AND created

Scanner input;
input = new Scanner([Link]);
Array Declaration

rea
a r dy to
efe
r ho
an ence ld
arr
numbers null ay to
Array Creation
new <type>[<length>]

0
0
0
numbers null
Au 0
t
zer o-init 0
ov
alu to 0
( Ja es 0
spe a v
cifi 0
c!) 0
0
Access to Values
numbers
<arrayName>[<index>]

0
0
0
0
0
0
0
0
0
0
An example
Do
be esn’t
a C nee
ON
STA d to
NT
!
Exercise together: SimpleArray
• Create an array of 10 elements
• Populate it such that element i = i
• Print out the array, iterating over its elements with a for loop
• Print out the array again, this time using the static method
[Link]()
ArrayOutOfBoundsException

• Runtime error numbers


• One of the most common
0

programming errors 0

? 0
0
0
0

? 0
0
0
? 0
A little bit of history
Java catches you when you read/write out of array
bounds
This wasn’t always the case with earlier programming
languages

rn et
te
a rly in rm
E wo
Instantiating Arrays
Like Strings, arrays can be instantiated
[Very useful for testing!!]

Only possible for basic type arrays and String arrays (and arrays of arrays of
those)
Arrays of Objects

words

E
rea ach
a r d y t fie ld
efe o
h
a S renc old
tri e t
ng o
main(String[] args)

Command line arguments passed


into the java program
Arrays of Arrays
Arrays are objects!
Arrays can hold objects!
= multi-dimensional arrays

numbermatrix


Multidimensional Arrays

one dim ension


Length in

Leng
th in
othe
rdi me n
sion
Making Multidimensional Arrays
numberCollection


Multi-dimensional Array of
Different Lengths
numberCollection


Exercise together: MultidimensionalArray
• Make a multidimensional array initialized with the following values:

{{1,2,3,4,5}, {10,20}, {100,200,300,400}}

• Print it with a nested for loop


• Print it using the [Link]() method
Shortcut for normal people!! use

When multi-dimensional arrays are rectangular:


When it represents a board, matrix, image, …

All dimension-lengths can be given in one go:

Þ 99.9% or more of all arrays will be initialized this


way
Array Length
Once an array is created, its length can not be
changed.
- What if the number of elements in it is unknown at
creation?
E.g. “read in an unknown number
of integers, ending with a
letter, then sort the numbers”
Array Length Solutions
1. Create an array larger than the largest
expected/reasonable number of entries

Is going to look
different if you
care about the
order!
Array Length Solutions (cont.)
2. Replace array with array of correct length
Array Length Solutions (cont.)
3. Replace with larger array only when necessary
Array Length Solutions (cont.)
4. Use an ArrayList!

More on this topic next week (and in project 1.1)


Exercise together: RemovingElement
• Make an array with values: {1,2,3,4,5,6,7,8,0,0}
• Declare a variable toDelete indicating which element to delete
• Declare a variable length that will act as the valid length of the
array
• Delete the requested element in the array
Exercise together: DeleteFromArray
• Make an array with values: {1,2,3,4,5,6,7,8,0,0}
• Declare a variable toDelete indicating which element to delete

• Produce a new array with all elements except the deleted one
More Shortcuts use value,
then update
Using an index + updating

update
value, then
use
Even More Shortcuts (2)
Copying an array
Exercise together: MoreShortcuts
• Make three arrays:
- a: Initialize it with {1,2,3,4,5}
- b: int array of size 5
- c: int array of size 5

• Copy a into b with arraycopy


• Copy a into c with an assignment
• Print all three arrays and make sense of the differences
• Modify the contents of a[0] and print again
Arrays as parameters
Java is “pass-by-value”!?!

x … … a
Arrays as parameters (2)
Array references can be passed as parameters

x a
Side effects!

n ges
o c h a of
Als ntent
co x!!

x a
Exercise together: ArrayPassByValue
• Make an array initialized with {4, 8, 15, 16, 23, 42}
• Create a method public static void changeElement
(int elementArray) that assigns 10 to elementArray
• Create a method public static void changeElement
(int[] array) that assigns 10 to array[0]

• Invoke both methods and print the resulting array at every stage
Simple Array Algorithms
Initializing min with the value
Finding the minimum/maximum
in array[0] we skip one step in
the for loop
Simple Array Algorithms (2)
Conditional counting
Simple Array Algorithms (3)
Conditional selection
Simple Array Algorithms (4)
Finding a value

i
x

n steps
Simple Array Algorithms (5)
Finding a value with better performance

i
x

on average n/2 steps


Simple Array Algorithms (6)
Finding a value in a sorted array

Binary search, worst case O(log2(n)) steps


Sorting an Array
(Almost) a research topic on its own …
- Lots of algorithms to sort an array (you cover this in
detail in DSA course)
- We might see an example in some future homework
Summary
Arrays
• Declaration and Creation
• Referencing values
• Array lengths
• Array references as parameters
• Some (simple) algorithms
Coming up next!
Book: Check Canvas
Homework 5: 19 tasks available
Quiz 5
Practical session this Friday!
You can already start thinking about assignment 6
Q&A on Tuesday
Practice, practice ... practice!
- BAD NEWS: Complexity is increasing rapidly!!
- GOOD NEWS: We are reaching exam-level complexity!

You might also like