Dennis Komm
Programming and Problem SolvingArrays, Strings, and Methods
Spring 2019 – March 4, 2019
Arrays
Arrays
Declare array variables: int[] z; z
Create an array: z = new int[5];
z[1] z[2] z[3] z[4]z[0]
z is a reference to the array data,but only after the assignment to the created dataotherwise it points to nowhere: nullElements are indexedthe first index is 0 and the last index is array size− 1Element access: name[index]
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 1 / 50
Arrays
int[] b;int b[];
ï b is array variable, but array does not exist yet
b = new int[10];
ï With new memory is assigned to b
int[] b = new int[10];
ï Both can be combined
int[] b = {9,6,3,6,2,1,6,8,3};
ï Values can be given immediatelyProgramming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 2 / 50
Arrays are Dynamic Objects
Arrays are always created dynamically
int[] b;b = new int[10]; // 10 elements with index 0,...,9...b = new int[20]; // can be reassigned
Size of an array can be set at runtime
But an array does not grow automatically
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 3 / 50
Arrays are Dynamic Objects
int sq = new int[7];for (int i = 0; i < sq.length; ++i) {
sq[i] = i * i;}sq[8] = 64; java.lang.ArrayIndexOutOfBoundsException
// output array:for (int i = 0; i < a.length; ++i) {
Out.println("a[" + i + "]=" + a[i]);}
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 4 / 50
Array Assignments
When assigning arrays, references are being copied, not data
int[] z = new int[5];
for (int i=0; i < z.length; ++i) {z[i] = i*i;
}
int[] x = z;
int j = x[2];
x[1] = 99;
z
0 1 4 9 16
x
4
j
99
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 5 / 50
Idea – Counting Digits
6 5 4 2 4 5 7 8 9 1 1 3 2 4 5
0
0
0
1
0
2
0
3
0
4
0
5
0
6
0
7
0
8
0
9
1111 2 2 1 1 112 12 3 3
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 6 / 50
Exercise – Counting Digits
Write an algorithm that
takes an (unsorted) array xcontaining numbers from the range[0, . . . , 9]outputs for each number, how manytimes it occurs in x
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 7 / 50
Counting Digits
public class CountNumbers {public static void main(String[] args) {
int[] numbers = {6, 5, 4, 2, 4, 5, 7, 8, 9, 1, 1, 3, 2, 4, 5};int[] index = new int[10];
for (int i = 0; i < numbers.length ; i++) {index[numbers[i]]++;
}
for (int i = 0; i < index.length ; i++) {Out.println("Count (" + i + ")=" + index[i]);
}}
}Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 8 / 50
ArraysMultidimensional Arrays
Multidimensional Arrays
double[][] matrix = new double[4][4];
m
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 9 / 50
Multidimensional Arrays
double[][] matrix = new double[4][4];
// Identity matrixfor (int r=0; r < matrix.length; ++r) {
for (int c=0; c < matrix[r].length; ++c) {if (r==c) {
matrix[r][c] = 1;} else {
matrix[r][c] = 0;}
}}
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 10 / 50
Multidimensional arrays
A two-dimensional array is an array of references to a one-dimensional array
double[][] matrix = ...;
for (int r = 0; r < matrix.length; ++r) {double[] vector = matrix[r];for (int c = 0; c < vector.length; ++c) {
Out.print(vector[c] + " ");}Out.println();
}
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 11 / 50
Multidimensional arrays
Even the following is possible
double[][] m = new double[5][];for (int r = 0; r < m.length; ++r) {
m[r] = new double[r+1];}
m
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 12 / 50
ArraysArray Comparisons
Array Comparisons
Arrays are references
double[] x = {1,2,3};double[] y = x;double[] z = {1,2,3};
if (y == x) {...} // y==x is trueif (z == x) {...} // z==x is false
if (z.equals(x)) {...} // z.equals(x) is also falseif (Arrays.equals(x,z)) {...} // Arrays.equals(x,z) is true
Attention when using Arrays.equals on multidimensional arrays
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 13 / 50
Strings
Strings
Strings are objects that store character arrays
String name = "Informatics";String university = "ETH";String lecture = name + " at " + university;int x = 3;int y = 5;String coordinates = "(" + x + "," + y + ")"; // "(3,5)"
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 14 / 50
Strings
Evaluation order
int x = 3;int y = 5;String s1 = x + y + "X"; // s1 = "8X"String s2 = "X" + x + y + ""; // s2 = "X35"
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 15 / 50
Characters
Elements of strings can be accessed by index (but not replaced)
String info = "Informatics";char c = info.charAt(3); // c = ’o’
Strings are references as well
info
I
0
n
1
f
2
o
3
r
4
m
5
a
6
t
7
i
8
c
9
s
10
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 16 / 50
StringsString Comparisons
String Comparisons
The comparison with “==” again compares references, not content
String n1 = In.readWord();String n2 = In.readWord();if (n1 == n2) {
Out.println(n1 + "==" + n2);} else {
Out.println(n1 + "!=" + n2);}
Input: Info, Info
Output: Info != Info
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 17 / 50
String Comparisons
The comparison with “equals” compares the content (this does not apply toarrays)
String n1 = In.readWord();String n2 = In.readWord();if (n1.equals(n2)) {
Out.println(n1 + " equals " + n2);} else {
Out.println(n1 + " does not equal " + n2);}
Input: Info, Info
Output: Info equals Info
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 18 / 50
Methods
Methods
Code fragments can be assembled in methods
Advantages
Define once – use several times
Clearer, more readable code, easier to comprehend
Code in methods can be tested easier
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 19 / 50
Example – Cookie Calculator
public class Keksrechner {public static void main(String[] args) {
Out.print("Kinder: ");int kinder = In.readInt();
Out.print("Kekse: ");int kekse = In.readInt();
Out.println("Jedes Kind kriegt " + kekse / kinder + " Kekse");Out.println("Papa kriegt " + kekse % kinder + " Kekse");
}}
We want to make sure that kinder is positive and that each child gets atleast one cookie
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 20 / 50
Cookie Calculator – Check Input
From this . . .
Out.print("Kinder: ");int kinder = In.readInt();
. . . we go to this
int kinder;do {
Out.print("Kinder: ");kinder = In.readInt();if (kinder < 1) {
Out.println("Wert zu klein. Mindestens " + 1);}
} while (kinder < 1);
Analogously, we have to check that kekse >= kinderProgramming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 21 / 50
Cookie Calculator – Getting Complicated
public class Keksrechner {public static void main(String[] args) {
int kinder;
do {Out.print("Kinder: ");kinder = In.readInt();if (kinder < 1) {
Out.println("Wert zu klein. Mindestens " + 1);}
} while (kinder < 1);
int kekse;
do {Out.print("Kekse: ");kekse = In.readInt();if (kekse < kinder) {
Out.println("Wert zu klein. Mindestens " + kinder);}
} while (kekse < kinder);
Out.println("Jedes Kind kriegt " + kekse / kinder + " Kekse");Out.println("Papa kriegt " + kekse % kinder + " Kekse");
}}
Read and check num-ber of children
Read and check num-ber of cookies
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 22 / 50
Cookie Calculator – Takeaway
The two code fragments are nearly identical
The following aspects are different:The prompt, i.e., "Kinder: " vs. "Kekse: "The minimum, i.e., “1” vs. “kinder”
We can outsource the code fragment into a method and thus feature reuse
We have to parameterize the different aspects
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 23 / 50
MethodsDeclaration of a Method
Declaration of a Method
private static int checkInt(String prompt, int min) {...}
modifiers
return type of the method
name of the method
parameter list
implementation
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 24 / 50
Declaration of a Method
Modifiers: Will be treated later
Return type: Data type of the return value; if the method does not return avalue, this type is void
Name: A valid name; should be starting with a lower letter
Parameter list: List of parameters surrounded by parentheses, declared bydata type and name; parameters are set when method is called; can be usedlike local variables
Implementation: The code that is executed when the method is called
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 25 / 50
Method Signature
private static int checkInt(String prompt, int min) { ...}
Signature of the method
Signature is unique within a class
It is thus possible to have several methods with the same name but differentnumbers or types of parameters. – not recommended
Return type is not part of the signature; it is not possible to have severalmethods that are only distinguishable by their return type
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 26 / 50
MethodsPass by Value
Method Call – Pass By Value
A method call is an expression with the return value of the method
In Java we always have pass by value semantics
Pass by value means that argument values are copied into theparameters upon method call
This corresponds to the same principle as the assignment to a variable
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 27 / 50
Method Call – Pass By Value
// Methodenaufrufint kekse = checkInt( "Kekse: " , kinder );
private static int checkInt( String prompt , int min ) {// ...
}
K e k s e :
prompt
copy of the reference
5
5
min
copy of the value
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 28 / 50
Back to the Example – Method checkInt
private static int checkInt(String prompt, int min) {int number;do {
Out.print(prompt);number = In.readInt();if (number < min) {
Out.println("Wert zu klein. Mindestens " + min);}
} while (number < min);return number;
}
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 29 / 50
MethodsReturn Values
Return Values of Methods
Return type = void: The evaluation of the method can be ended with thestatement return
Return type 6= void: The evaluation of the method must happen via“return value”. The value is passed back to the calling method.
Important
In the second case every possible finite execution path must contain areturn statement
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 30 / 50
Return Values on All Execution Paths
Correct
private static int checkInt(String prompt, int min) {int number;do {
Out.print(prompt);number = In.readInt();if (number < min) {
Out.println("Wert zu klein. Mindestens " + min);}
} while (number < min);
return number;}
Is reached always if the method termi-nates at all.
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 31 / 50
Return Values on All Execution Paths
Solution identical with regards to content
private static int checkInt(String prompt, int min) {
int number;while (true) {
Out.print(prompt);
number = In.readInt();
if (number >= min) return number;
Out.println("Wert zu klein. Mindestens " + min);
};}
Compiler understands the infinite loop and accepts
that “return” can only occur here.
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 32 / 50
Return Values on All Execution Paths
Solution identical with regards to content
private static int checkInt(String prompt, int min) {
int number;do {
Out.print(prompt);
number = In.readInt();
if (number >= min) return number;
Out.println("Wert zu klein. Mindestens " + min);
} while (number < min);return 0;
}
Fulfills the “return” on each path. Actually
that cannot be reached. (. . . Why not?)
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 33 / 50
Cookie Calculator – More Comprehensible
public class Keksrechner {public static void main(String[] args) {
int kinder = checkInt("Kinder: ", 1);int kekse = checkInt("Kekse: ", kinder);
Out.println("Jedes Kind kriegt " + kekse/kinder + " Kekse");Out.println("Papa kriegt " + kekse % kinder + " Kekse");
}
private static int checkInt(String prompt, int min) {// ... see previous slidereturn number;
}}
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 34 / 50
MethodsPre- and Postconditions
Pre- and Postconditions
characterize (as complete as possible) what a Method does
document the method for users and programmers (we or other people)
make programs more readable: we do not have to understand how themethod works
are ignored by the compiler
Pre and postconditions render statements about the correctness of a programpossible – provided they are correct
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 35 / 50
pow
public static double pow(double b, int e) {double result = 1.0;if (e < 0) { // b^e = (1/b)^(-e)
b = 1.0/b;e = -e;
}for (int i = 0; i < e; ++i) {
result *= b;}return result;
}
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 36 / 50
Scope of Formal Arguments
public static double pow(double b, int e) {double r = 1.0;if (e
Preconditions
Precondition
What is required to hold when the method is called?
Defines the domain of the method
Examples
0e is undefined for e < 0
// PRE: e >= 0 || b != 0.0
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 38 / 50
Postconditions
Postcondition
What is guaranteed to hold after the method call?
Specifies value and effect of the method call
Example
Here only value, no effect
// POST: return value is b^e
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 39 / 50
Pre- and Postconditions
should be correct
if the precondition holds when the method is called then also thepostcondition holds after the call
Example
Method pow works for all numbers b 6= 0
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 40 / 50
Pre- and Postconditions
We do not make a statement about what happens if the precondition does nothold
Examples
Method pow: division by 0
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 41 / 50
Pre- and Postconditions
Pre-condition should by as weak as possible (large domain of definition)
Post-condition should be as strong as possble (detailled statement)
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 42 / 50
Example – pow
// PRE: e >= 0 || b != 0.0// POST: return value is b^epublic static double pow(double b, int e) {
double result = 1.0;if (e < 0) { // b^e = (1/b)^(-e)
b = 1.0/b;e = -e;
}for (int i = 0; i < e; ++i) {
result *= b;}return result;
}
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 43 / 50
Example – xor
// post: returns l XOR rpublic static boolean xor(boolean l, boolean r) {
return l && !r || !l && r;}
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 44 / 50
Example – harmonic
// PRE: n >= 0// POST: returns nth harmonic number// computed with backward sumpublic static float harmonic(int n) {
float res = 0;for (int i = n; i >= 1; --i) {
res += 1.0f / i;}return res;
}
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 45 / 50
Example – min
// POST: returns the minimum of a and bpublic static int min(int a, int b) {
if (a= 0 || b != 0.0// POST: return value is b^e
is formally incorrect
Overflow if e or b are too large
be potentially not representable as a double (holes in the domain)
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 47 / 50
White Lies. . . are Allowed
// PRE: e >= 0 || b != 0.0// POST: return value is b^e
The exact pre- and postconditions are platform-dependent and oftencomplicated
We abstract away and provide the mathematical conditions
ï Compromise between formal correctness and lax practice
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 48 / 50
Checking Preconditions. . . with Asserts
Preconditions are only comments
How can we ensure that they hold when the method is called?
// PRE: e >= 0 || b != 0.0// POST: return value is b^epublic static double pow(double b, int e) {
assert e >= 0 || b != 0 : "division by zero";double result = 1.0;...
}
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 49 / 50
Postconditions with Asserts
The result of “complex” computations is often easy to check
Then the use of asserts for the postcondition is worthwhile
// PRE: the discriminant p*p/4 - q is nonnegative// POST: returns larger root of the polynomial x^2 + p x + qpublic static double root(double p, double q) {
assert(p*p/4 >= q); // preconditiondouble x1 = - p/2 + sqrt(p*p/4 - q);assert(equals(x1*x1+p*x1+q,0)); // postconditionreturn x1;
}
Programming and Problem Solving – Arrays, Strings, and Methods Spring 2019 Dennis Komm 50 / 50
ArraysMultidimensional ArraysArray Comparisons
StringsString Comparisons
MethodsDeclaration of a MethodPass by ValueReturn ValuesPre- and Postconditions
Top Related