Download as pdf or txt
Download as pdf or txt
You are on page 1of 89

Csci 1933: Introduction to

Algorithms and Data Structures


Spring 2022
Overview
• Last time:
– Variables, Primitives/primitive operations,
Math in Java, Input/output operations,
Conditionals and loops

• Today:
• Finish loops example, variable scope, strings,
string operations

• Announcements:
• Project 1 assigned (see Canvas); due 2/11
(before 7pm) Get started now!
• Lab 2 due this Friday (last office hours)
Brief review of key concepts covered last time
Variables in Java
• Variable declaration: necessary before the first use of a
variable—need to tell Java what types your variables are
so it knows how to store them in memory, what are the
possible operations
o Assignment statements: ‘=’ operator
o Initialization: always initialize, either when you
declare or when you use
o Examples:
o Name joe = new Name();
o int k=10;
Two variable types in Java
• Reference variables: Class types, either defined by
you or using the Java built-in classes
• Primitive variables:
int, char, float, double, boolean, long,
short, byte

Primitive examples: Reference variable example:

int i; Name joe = new Name();


char grade = ’A’; joe.setName(“Joseph”,”Brown”);
i = 5;
i = i + 7;

Important exception: primitive variables are not objects in Java!


Primitives vs. objects: how are they
stored in memory?
joe variable stores a reference,
or memory address (in bits)
Name joe = new Name();
00100111 joe.setFirst("Joseph");
joe.setLast("Brown");
joe first: “Joseph”
last: “Brown”
Memory address: 00100111

Variable i (primitive data type)


stores the actual value (in bits) int i;
i = 5;
00000101
i The assignment operator (=) changes the
value stored in memory
More sophisticated math in Java
• Java has a built-in “Math” class with a whole
range of math functions: cos, sin, exp, pow,
log, and many more
• Example use:
double num = 2*Math.PI;
double result = Math.sin(num);
double result2 = Math.exp(result);

What’s different about how we


used the Math class here?
See complete specification here:
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Math.html
Static Fields and Methods
• When specified static, a method is still a
member of the class
– However, does not need an object as a prefix to
the call
• Call with the name of the class

int maximum = Math.max(2, 3);


double root = Math.sqrt(4.2);

Carrano and Henry, Data Structures and Abstractions with Java


Output operations in Java
(standard out + file output)
System.out.println(myString);
System.out.println(myString+"--something extra");
System.out.println(myString+"--Lucky number:"+13);
System.out.println(myString+"--Lucky number:"+7+6);
System.out.println(myString+"--Lucky number:"+(7+6));

File f = new File("myoutput.txt");


PrintStream outfile = new PrintStream(f);
outfile.println(myString);
outfile.println(myString+"--something extra");
outfile.println(myString+"--Lucky number:"+13);
outfile.println(myString+"--Lucky number:"+7+6);
outfile.println(myString+"--Lucky number:"+(7+6));

System.out and outfile are both of the same type, so we can


interact with them in exactly the same way!
Input operations in Java
(standard in + file input)
Scanner keyboard = new Scanner(System.in);

System.out.println("Please enter your age:");


int age = keyboard.nextInt();

File f = new File("SARS_CoV2_MN2020.fasta");

Scanner fileInput = new Scanner(f);


String input = fileInput.next();

Once you know how to use a Scanner object, you know how to do both!
Conditionals example #1

int testscore = 70;

if (testscore >= 90) {


System.out.println("Grade = at least A");
}
else if (testscore >= 80) {
System.out.println("Grade = at least B");
}
else if (testscore >= 70) {
System.out.println("Grade = at least C");
}
else if (testscore >= 60) {
System.out.println("Grade = at least D");
}
else {
System.out.println("Grade = F");
}
Logical combinations of Boolean
expressions
• And- &&
• OR- ||
• NOT- !
• Examples if ((pressure > min) && (pressure < max)) {
System.out.println("Pressure is OK.");
}
else {
System.out.println("Warning: Pressure is out of range.");
}

if ((salary > expenses) || ((salary + savings) > expenses)) {


System.out.println("Solvent");
}
else {
System.out.println("Bankrupt"); }

Comments: always use parentheses to group when in doubt! Good idea to keep statements as simple
as possible
Loops
• Loops are one of the most useful and
important constructs in most languages: they
enable repetition

• Three important pieces:


– Initialization of any variables
– “body” of the loop (the repeated set of
statements)
– stop condition
While loops
• Basic structure:
<initialization statements>
while( <boolean expression> ) {
<loop body: block of statements>
}

Example:
Output:
What’s1the output?
2
int number = 10; 3
int count = 1; 4
while (count <= number) 5
{ 6
System.out.println(count); 7
count++; 8
} // end while 9
10
Note: for while loops, we typically need to include an increment statement at the end
(count++) to move the loop along.
While loops
• Basic structure:
<initialization statements>
while( <boolean expression> ) {
<loop body: block of statements>
}

Example:
Output:
1
2
int number = 10; 3
int count = 1; 4
while (count <= number) 5
{ 6
System.out.println(count); 7
count++; 8
} // end while 9
10
Note: for while loops, we typically need to include an increment statement at the end
(count++) to move the loop along.
The “do-while” loop
Basic structure:
do
{
<block of statements>
} while(<boolean expression>);

Example:

int number, count;


number=1;
count=1;
do
{
System.out.println(count);
count++;
} while(count <= number);
For loops
• Basic structure:
for(<initialize>; <test>; <update>) {
<block of code>

} update operation happens here at the end


of the block, each iteration

Example:
int count, number;
number = 10;
for (count=1; count <= number; count++) {
System.out.println(count);
}

• Main difference from while: initialization and update operations are built in to
loop construct
• Note initialize, test, update + syntax (no semi-colon after update)
For loops (2)
• Test condition and the update operation are
flexible, e.g. Output:
For:0
For:2
number = 10; For:4
for (count=0; count < number; count+=2) { For:6
What’s the output?
System.out.println(“For:”+count); For:8
}
Output:
number = 10; For:10
for (count=10; count > 0; count--) { For:9
System.out.println(“For:”+ count); For:8the output?
What’s
} For:7
For:6
For:5
For:4
For:3
For:2
For:1
For loops (2)
• Test condition and the update operation are
flexible, e.g. Output:
For:0
For:2
number = 10; For:4
for (count=0; count < number; count+=2) { For:6
System.out.println(“For:”+count); For:8
}
Output:
number = 10; For:10
for (count=10; count > 0; count--) { For:9
System.out.println(“For:”+ count); For:8
} For:7
For:6
For:5
For:4
For:3
For:2
For:1
New material
Overview of today’s material

• More Java programming basics:


– Practice with loops/conditionals
– Variable scope
– Strings/string operations
– Start on arrays
Other useful loop concepts
• “Break” statement
- loop immediately ends when a break
statement is encountered
Example:
Scanner keyboard = new Scanner(System.in);
int i=0;
while(true) {
System.out.println("Enter a number:");
if(keyboard.hasNextInt()) {
int currInt = keyboard.nextInt();
System.out.println("Square = "+(currInt*currInt));
}
else {
System.out.println("Sorry, you didn’t enter a
number- GAME OVER!");
break;
}
}

See CondLoopDemo.java
Labeled “break” example
Note: break applies to
innermost loop unless you
label it otherwise
Other useful loop concepts
• “Continue” statement: loop skips to the next
iteration immediately upon encountering this
statement
Example:

int j,sum=0;
for(j =0; j < 20; j++) {
if(j%2 == 1) { continue; }

System.out.println("Adding "+j);
sum += j;
}
Note: continue applies to
What does this do? innermost loop unless you
label it otherwise
Note about break and continue
statements
• Use them carefully!
• They alter the normal execution of loops and
make your programs harder to interpret later
• Avoid using them if possible, but they can be
convenient in some cases
Nested loops
• Additional loops can be included inside blocks
of statements just like anything other
statements (“nested” loops)

int x = 50;
int y = 5;

for(int m=0; m<y; m++) {


for(int n=0; n<x;n++) {
System.out.print("*");
}
System.out.println();
}

What does this do?


Nested loops
int width = 50;
int height = 5;

for(int m=0; m<height; m++) {


for(int n=0; n<width;n++) {
System.out.print("*");
}
System.out.println();
}

Output:
**************************************************
**************************************************
**************************************************
**************************************************
**************************************************
Another nested loop example
System.out.print("\t");
for(i=1; i <= 8; i++) {
System.out.print(i+"\t");
}
System.out.println();

for(i=1; i <= 8; i++) {


System.out.print(i+"\t");
for(j=1; j<=8; j++) {
System.out.print((i*j)+"\t");
}
System.out.println();
}

See CondLoopDemo.java
For practice: use loops to draw this

**
**** Triangle, base = 40, height =40
******
********
**********
************
**************
****************
******************
********************
**********************
************************
**************************
****************************
******************************
********************************
**********************************
************************************
**************************************
****************************************
**************************************
************************************
**********************************
********************************
******************************
****************************
**************************
************************
**********************
********************
******************
****************
**************
************
**********
********
******
****
***
Loop exercise

• Write a function (assume we’re adding it to


the Math class) that performs the factorial
operation
Specs: Name: factorial; input type: int; output
type: int;
• Implement two ways:
– Using a loop (while, for, …)
– Using recursion

(you can assume non-negative integers as input)


Work on loop implementation
Loop implementation of the
factorial operation

public static double loopFactorial(int x) {


double result=1;

for(int i=1; i <= x; i++) {


result *= i;
}

return result;
}
Reminders about solving problems
with recursion
Recursive solution: an operation that can be defined in
terms of itself
– Solving a problem using recursion depends on solving
smaller occurrences of the same problem

Two necessary components:


– base case: a simple occurrence that can be answered
directly

– recursive case: a more complex occurrence of the problem


that cannot be directly answered, but can be described in
terms of smaller occurrences of the same problem
Work on recursive implementation
Two implementations of the
factorial operation
public static double loopFactorial(int x) {
double result=1;

for(int i=1; i <= x; i++) {


result *= i;
}

return result;
}

public static double recurseFactorial(int x) {

double result;
if(x <= 1) { result=1;}
else {
result = x*recurseFactorial(x-1);
}
return result;
}
Benchmarking the factorial implementations
int x=150;
int N=5000000;

System.out.println("Running loop version...");


long starttime = System.currentTimeMillis();
double result1=0;

for(int i=0; i < N; i++) {


result1=loopFactorial(x);
}

long endtime = System.currentTimeMillis();


System.out.println("Loop version: result="+result1+", Time="+(endtime-
starttime) +" milliseconds");

System.out.println("Running recursive version...");


starttime = System.currentTimeMillis();
double result2=0;
for(int i=0; i < N; i++) {
result2=recurseFactorial(x);
}
endtime = System.currentTimeMillis();
System.out.println("Recursive version: result="+result2+", Time="+(endtime-
starttime)+" milliseconds");
Overview of today’s material

• More Java programming basics:


– Practice with loops/conditionals
– Variable scope
– Strings/string operations
– Start on arrays
Variable scope
Variable scope
• Scope: the part of your program where a variable is
visible
• Rules:
– When declared within a statement block (e.g. inside a
while or for block)
• Visible: only within that block or additional blocks
nested within
– When declared as parameters of a method or constructor
• Visible: only within that method or constructor
– When declared within a class definition as data members
• Visible: through-out the class definition, methods,
sometimes from object references (depending on
public vs. private)
Variable defined within a statement block: example #1
public static void main(String[] args) {
for (int x = 0; x < 5; x++) {
System.out.println(x);
}
double y = Math.sqrt(x); //is this ok?
}

public static void main(String[] args) {


int x=0;
for (x = 0; x < 5; x++) {
System.out.println(x);
}
double y = Math.sqrt(x); //is this ok?
}

public static void main(String[] args) {


int x=0;
for (x = 0; x < 5; x++) {
System.out.println(x);
int z = x*2;
}
double y = Math.sqrt(z); //is this ok?
}
Example from: http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm
Variable declared within a statement block: example #1

public static void main(String[] args) {


for (int x = 0; x < 5; x++) {
System.out.println(x); No!
}
double y = Math.sqrt(x); //is this ok?
}

public static void main(String[] args) {


int x=0;
for (x = 0; x < 5; x++) {
Yes! System.out.println(x);
}
double y = Math.sqrt(x); //is this ok?
}

public static void main(String[] args) {


int x=0;
for (x = 0; x < 5; x++) {
System.out.println(x);

}
int z = x*2; No!
double y = Math.sqrt(z); //is this ok?
}
Example from: http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm
Variable declared within a statement block:
example #2

public class MainClass {

public static void main(String[] args) {


for (int x = 0; x < 5; x++) {
for (int y = 0; y < 3; y++) {
System.out.println(x); Sub-block:
System.out.println(y); Note x is still visible
}
}

Example from: http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm


Variable declared as parameter of a method or
constructor
public class MyMath {
public double factorial(double x) {
double result=1;

for(double i=1; i <= x; i++) { What’s


result *= i;
}
wrong with
this code?
return result;
}

public double linearFunction(double m, double b, double y) {


double result=0;
result = m*y+b;
result += x;
return result;

}
Main points:
• parameters passed into a method are visible throughout the method
• parameter variables are not visible in other methods of the class
Variable declared as parameter of a method or
constructor
public class MyMath {

public double factorial(double x) {


double result=1;

for(double i=1; i <= x; i++) {


result *= i;
}

return result;
}

public double linearFunction(double m, double b, double x) {


double result=0;
result = m*x+b;
return result;

Note that I can use “x” in two different methods, and they
have nothing to do with one another
Variable declared within a class definition as a
data member
public class MyMath {
private double x=100;

public double factorial(double x) {


double result=1;

for(double i=1; i <= x; i++) {


result *= i;
}

return result;
}

public double linearFunction(double m, double b, double x) {


double result=0;
result = m*x+b;

System.out.println("x:"+ x +" this.x=" + this.x);


x=3;
System.out.println("x:"+ x + " this.x=" + this.x);

return result;
} What’s the output of this code?
Output: MyMath calculator = new MyMath();
} x:1.0 this.x=100.0 double result =
x:3.0 this.x=100.0 calculator.linearFunction(10,0,1);
result=10.0 System.out.println(“result=“+result);
Class data member example
public class MyMath {
private double count=0;

public double factorial(double x) {


double result=1;

for(double i=1; i <= x; i++) {


result *= I; }
count++;
return result;
}

public double linearFunction(double m, double b, double x) {


double result=0;
result = m*x+b;

count++;
return result;
Code in main program:
} MyMath calculator = new MyMath();

calculator.linearFunction(10,0,1);
public double getNumCalls() { double sum=0;
return count; for(int i=1; i < 100; i++) {
} sum += calculator.factorial(i);
}
} System.out.println("NumCalls="+calculator.get
NumCalls());
Review of variable scope

• Variables declared in methods are visible inside the


current code block or any nested blocks

• Parameter variables are visible only inside the


associated method

• Class member variables are visible throughout the


entire class
• if there’s a local variable with the same name, the
local variable has precedence— use
“this.<variable name>” to refer to the class
data member
Overview of today’s material

• More Java programming basics:


– Practice with loops/conditionals
– Variable scope
– Strings/string operations
– Start on arrays
Strings
Strings in Java
• Strings are another built-in class (java.lang
package)
• Strings are immutable—once they’re created,
they can’t be modified
• Otherwise, they’re just objects, like everything
else we’ve talked about

String className = "UMN:CSCI:1933:Sec010";


//this also works but the top one is preferred
String className2 = new String("UMN:CSCI:1933:Sec010");

System.out.println(className);
String example: comparison

String str1 = new String("string1");


String str2 = new String("string1");

if(str1 == str2) { System.out.println("Strings are


equal!"); }
else { System.out.println("Strings not equal!");}

Output:
Strings not equal!

What will happen?


String example: comparison
str1 = new String("string1");
str2 = str1;

if(str1 == str2) { System.out.println("Strings are


equal!"); }
else { System.out.println("Strings not equal!");}

Output:
Strings are equal!

What about now? Why?

Answer: you’re comparing references, not the data associated with


the String objects!
String example: comparison
str1 = "string1";
str2 = "string1";

if(str1 == str2) { System.out.println("Strings are


equal!"); }
else { System.out.println("Strings not equal!");}

Output:
Strings are equal!

What about now? Why?

Answer: there is a single string object "string1“ – both


variables refer to this object. (Java string constant pool)
What’s the right way to compare Strings?
• Strings are objects just like most other things we’ve covered
• They have a defined set of methods for interacting with them, e.g.
char charAt(int index)
Returns the char value at the specified index.
String concat(String str)
Concatenates the specified string to the end of this string.
boolean equals(Object anObject)
Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character,
starting the search at the specified index.
int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring,
starting at the specified index.
int length()
Returns the length of this string.
String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with
the given replacement.
String[] split(String regex)
Splits this string around matches of the given regular expression.

See https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html for many more


Comparing strings
• “equals” method:
String str1 = "string1";
String str2 = "string1"; Output:
Strings are equal!
if(str1.equals(str2)) {
System.out.println("Strings are equal!");
}
else { System.out.println("Strings not equal!");}

String str1 = new String("string1“);


String str2 = new String("string1“); Output:
Strings are equal!
if(str1.equals(str2)) {
System.out.println("Strings are equal!");
}
else { System.out.println("Strings not equal!");}

(Also equalsIgnoreCase() method – treats upper and lower case the same)
Comparing strings (2)
• compareTo method
• compares two Strings to see which is alphabetically first
• returns an integer
• negative  string you’re comparing is alphabetically before the
string passed
• positive  string you’re comparing is alphabetically after the
string passed
• 0  the two Strings are equal

• case-sensitive— with lower-case letters considered to be after upper-


case ones
String letterA = "A";
String lettera = "a"; Output:
String letterb = "b"; -33
32
System.out.println(letterA.compareTo(letterb));
System.out.println(lettera.compareTo(letterA));

(Also compareToIgnoreCase() method – treats upper and lower case the same)
String concatenation

str1 = "string1";
str2 = "string2";

str1 = str1 + str2;


System.out.println("Concatenated strings:"+str1);

str1 += str2;
System.out.println("Concatenated strings:"+str1);
Searching within strings
• int indexOf(char c): finds first occurrence of character c

• int indexOf(char c, int p): finds the first occurrence of


character c at or beyond position p.

• int indexOf(String s): finds the first occurrence of String s, and


returns the position of the first character of s, if any.

• int indexOf(String s, int p): finds the first occurrence of


String s at or beyond position p.

String className = "UMN:CSCI:1933:Sec001";


System.out.println(className.indexOf("CSCI"));
Output:
System.out.println(className.indexOf(":",4));
4
8
Another useful string class
StringTokenizer
• StringTokenizer is a class that’s built for splitting up
strings
Typical use:
StringTokenizer st = new StringTokenizer(<string>,<delimiter>);
(default delimiter– space)

• Example:
String className = "UMN:CSCI:1933:Sec001";
StringTokenizer st = new Output:
StringTokenizer(className,":"); 1:UMN
2:CSCI
int count=1; 3:1933
while(st.hasMoreTokens()) {
4:Sec001
System.out.println(count+":"+st.nextToken());
count++;
}
String exercise #1
• Write a short program to reverse a string
called “revString”

Hint: Use “charAt” method, which takes an index as


input and returns the corresponding character at
that index
For more practice:
• Write a short program that will receive an
input string from the user, count the number
of words in the string, and print the total to
the screen
• Write a short program that will receive a
comma-delimited list of words from a user,
sort them in alphabetical order, and print
them
Overview of today’s material

• More Java programming basics:


– Practice with loops/conditionals
– Variable scope
– Strings/string operations
– Start on arrays
Arrays
Arrays

A Java array is a list of items of a single type: homogeneous

Example:
int mondayTemperature=50;
int tuesdayTemperature=55;
int wednesdayTemperature=75;
int thursdayTemperature=45;
int fridayTemperature=40;
int saturdayTemperature=35;
int sundayTemperature=65;

vs.
int[] temperatures = {50,55,75,45,40,35,65};
Array declarations
• Declaration/initialization of arrays:

Primitives Arrays

Declaration int myInt; int[] myArray;

myArray = new int[7];


myInt = 5;
OR
Initialization OR
int[] myArray = new
int myInt=5;
int[7];
Array Indexing

Now that the array exists, how can we access it?

Bracket notation:
int[] temperatures = new int[7];
temperatures[0] = 35;
Sometimes it’s useful to use variables as array indices:

int monday = 0;
temperatures[monday] = 35;
Indexing details

In java, array indexing starts with zero

The first element is myArray[0]

Index can be any expression resulting in an int:

int monday =0;

temperatures[monday+1] = temperatures[monday] + 15;

This can be dangerous if not done carefully! (watch your


indices)
Looping over arrays

Standard loop structure:


for(int i = 0; i < myArray.length; i++){
if(i == 0){
myArray[i] = 0;
}else if(i == 1){
myArray[i] = 1;
}else{
myArray[i] = myArray[i-1]
}
}

• What kind of thing is length?


Initializations

As seen before, we can explicitly initialize array:

int[] myArray = {30, 50, 40, 33, 12};

This is a good feature but tedious for most cases where arrays
are useful
Arrays exercise
Linear search

int[] myArray = {30, 50, 40, 33, 12};

public static int linearSearch(int[] a, int key)

Find max element

int[] a = new int[]{23, 565, 21, 56, 22,1000,675, 123, 676, 87};
Assignment operators
For array elements, "=" is a copy operation:

temperatures[monday] = temperatures[sunday];

For array references, "=" is an alias operation:

int[] b = new int[10];


int[] a = b;
a[0] = 5;
b[0] = 3;
System.out.println(“a[0] = “ + a[0]);
More looping on arrays
• One useful type of loop that can help you avoid out
of range indexing
• For-each loop
for(<local var. declaration> : <array>) {
<block of code>
}

Output:
Ashlee
Austin
String[] TAs ={“Ashlee",“Austin",“Alice",“Isaac"}; Alice
for (String curr : TAs) { Isaac
System.out.println(curr);
}
Output:
int[] intArray = {1,2,3,4}; 1
for(int curr : intArray) { 2
System.out.println(curr); 3
} 4
Passing arrays to functions
public static double calcMean(int[] a) {
double result=0;

for(int i=0; i < a.length; i++) {


result += a[i];
}

return(result/a.length);
}

In main program:
int arr[] = {10, 90, 49, 2, 1, 5, 23};
System.out.println("Mean: "+calcMean(arr));
Passing arrays to functions (2)
public static void negateArray(int[] arr) {
for(int i=0; i < arr.length; i++) {
arr[i]=-arr[i];
}

In main program:
int arr[] = {10, 90, 49, 2, 1, 5, 23};
negateArray(arr);
System.out.println("Negated element: "+arr[0]);

The variable arr is a reference that points to an array!


Returning arrays from functions
public static int[] getZeros(int length) {
int[] newarr = new int[length];

for(int i=0; i < newarr.length; i++) {


newarr[i]=0;
}

return(newarr);
}

In main method:
int[] zeroArray = getZeros(10);
System.out.println("Length: "+zeroArray.length+",
first element: "+zeroArray[0]);

Note zeroArray is only declared, we don’t need to allocate memory


because we are getting a reference to an already constructed array
Practice with arrays
What’s wrong with this code?

Circle[] circleArray = new Circle[10];


int count=0;
Scanner keyboard = new Scanner(System.in);
while(true) {
System.out.println("Enter radius or ‘N’ to quit:");

if(keyboard.hasNextInt()) {
circleArray[count++] = new Circle(0,0,keyboard.nextInt());
} else { break; }
}
What’s wrong with this code?

Circle[] circleArray = new Circle[10];


int count=0;
Scanner keyboard = new Scanner(System.in);
while(true) {
System.out.println("Enter radius or ‘N’ to quit:");

if(keyboard.hasNextInt()) {
circleArray[count++] = new Circle(0,0,keyboard.nextInt());
} else { break; }
}

Throws ArrayIndexOutOfBoundsException!

We’re trying to index beyond the end of circleArray


Important: Java arrays are of fixed size
Indexing out of bounds
• Java throws an exception: tells you that
something unexpected happened your
program is stopped
• Lesson: design your code to avoid out of
bounds indexes
• Sometimes this means anticipating
“dangerous” user input— this can be a major
issue!
(More about exceptions later)
A little history: the Morris worm
• Robert Morris (grad. student Cornell), 1988
• One of the first computer worms
– Purpose: count how many computers were connected
to the internet
– Check if computer was infected, if not, replicate; 1 in 7
times replicate anyway
– Buffer overflow exploit:
• Extra data goes somewhere in memory beyond the end of
an array
• If you design the overflow data right, you can take control of
the computer (data interpreted as binary instruction)
Morris worm

• Infected ~10% of the internet (~60k total


computers at the time)
• Sentence: 3 yrs probation, 400 hrs community
service, $10k fine
• Now: a professor at MIT
• Moral of the story
– Be careful with indexing arrays (check bounds, etc.)!
(not: it’s ok to write worms that take down the internet)
Back to the Circle array example
Circle[] circleArray = new Circle[100];
int count=0;
Scanner keyboard = new Scanner(System.in);
while(count < 100) {
System.out.println("Enter radius or ‘N’ to quit:");

if(keyboard.hasNextInt()) {
circleArray[count++] = new
Circle(0,0,keyboard.nextInt());
} else { break; }
}

• I’ve fixed the out of bound indexing problem, but


• How can we resize this array to remove wasted space if the user
doesn’t take it all?
• Remember: arrays are technically fixed size

Exercise: Write a function called resize that can compact our array
Resize function

public static Circle[] resize(Circle[] array, int count) {


Circle[] newArray = new Circle[count];
for(int i=0; i < count; i++) {
newArray[i] = array[i];
}
return newArray;
}
Multi-dimensional arrays
• Data is often structured in multi-dimensional
tables, e.g.
– a grade spreadsheet with students on the rows
and homework assignments on the columns
– an gray-scale image (a matrix of pixels, e.g.
500x1700 pixels)
– a color image (500x1700x3, 3 color values/pixel)
• Java also allows multi-dimensional arrays
double[][] grades = new double[120][6];
for(int i=0; i < 120; i++) {
for(int j=0; j < 6; j++) {
grades[i][j]=100;
}
}
Multidimensional arrays
double[][] grades = new double[120][6];

for(int i=0; i < grades.length; i++) {


for(int j=0; j < grades[i].length; j++) {
grades[i][j]=100;
}
}

• What is grades.length?
• How about grades[0].length?

Don’t have to stop at 2 dimensions– can go as


far as we want
Operations on arrays

• Useful functions for arrays:


– Built-in class Array (java.util.Arrays)
– Useful (static) methods:
• equals(int[] a, int[] b), equals(double[] a, double[] b), …
• fill(int[] a, int val), fill(double[] a, double val), …
• sort(int[] a)…toString(int[] a), …
• binarySearch(int[] a, int key), …
• toString(int[] a), …
• copyOf(int[] a, int length), ....

(https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html )
Example: array operations

int[] numArray = new int[100];

Random randomNumGenerator = new Random();


for(int i=0; i < numArray.length; i++) {
numArray[i] = randomNumGenerator.nextInt(100);
}

System.out.println("Original:");
System.out.println(Arrays.toString(numArray));

System.out.println("Sorted:");
Arrays.sort(numArray);
System.out.println(Arrays.toString(numArray));
Example 2: array operations
int[] numArray = new int[100];

Random randomNumGenerator = new Random();


for(int i=0; i < numArray.length; i++) {
numArray[i] = randomNumGenerator.nextInt(100);
}

System.out.println("Original:");
System.out.println(Arrays.toString(numArray));

System.out.println("Sorted:");
Arrays.sort(numArray);
System.out.println(Arrays.toString(numArray));

int result = Arrays.binarySearch(numArray,5);


//Must be sorted first!!

if(result > 0) {
System.out.println("Found! Index:"+result);
} else {
System.out.println("Not found! Index:"+result);
}
Important reminders

• Lab 2: Check off milestones with TA by last office


hours on Friday (tomorrow)

• Project 1 due 2/11 by 7pm! (see Canvas)

You might also like