Uploaded by svetko_l

Programming practice exam

advertisement
Erasmus School of Economics
FEB22012X– Programming
Personal information student
Name:
Student number:
Written examination
General information
Date examination:
Lecturer:
Time examination:
Type examination:
Number of questions:
Number of pages:
Practice Exam
dr. P. Bouman
Three Hours
Closed book
4 questions
12 pages (incl. cover sheet – 3 for the exam, 3 for the appendix and 5 for the reference)
Instructions ESE
ˆ You are not allowed to use a calculator (types FX-82SX Plus / FX-82MS / FX-350MS /
TI-30Xa / TI-30XS Multiview).
ˆ You are not allowed to use a programmable calculator.
ˆ You are not allowed to use notes.
ˆ You are not allowed to use books.
ˆ You are not allowed to use a dictionary.
ˆ Scrap paper, examination assignments or other examination related documents must stay in
the examination room during the examination and after the examination has finished.
ˆ You are not allowed to take with you the answers nor may you copy answers in any way.
ˆ It is not allowed to keep a watch within reach during the examination. Watches need to be
stored in your coat or bag.
ˆ Any kind of mobile devices or (potential) data media must be switched off during the
examination. All devices need to be stored in your coat or bag.
Additional information
ˆ Motivate your answers as completely as possible.
ˆ Exam grade:
number of obtained points
.
10
Good luck!
THIS IS A PRACTICE EXAM!
No part of this examination may be reproduced, stored in a retrieval system or transmitted in any form or any means,
without permission of the author or, when appropriate, of the Erasmus University Rotterdam.
Programming —
Question 1
FEB22012X —
Practice Exam
(20 points)
Answer the following four theory questions. Keep your answers as concise as possible.
a. Explain in which situations a NullPointerException can occur in java. Name a different
way than using try-catch to avoid NullPointerExceptions.
b. Explain how a try-catch construct works, and under which circumstances the catch part
of the try-catch is executed.
c. A programmer created a class Student with header public class Student. Is it possible
to call the method toString() on objects of type Student? Explain why this is or is not
possible
d. Mention two intermediate operations for the Stream interface and explain what they can be
used for.
Pay attention: In Question 2 and Question 4 you have to write pieces of code. You are not
required to write commentary, but this is allowed. You don’t need to write import statements and
you can assume that the methods will not be called with nonsensical arguments. Small writing errors
such as a forgotten semicolon will not directly lead to a reduction of your score, unless the mistake
introduces ambiguity or has a large impact on the correctness of your program. Try to write your
program as correct as possible.
Unless specified otherwise, all methods and classes available in the standard Java library can be
used, including those described in the reference attached to this exam.
Question 2
(20 points)
a. The class Math contains a number of useful static methods for various tasks, such as computing powers and goniometric functions. Suppose the programmers of the Math class want
to add an additional method repeatOperator that has three input arguments: a BigInteger
startValue, a UnaryOperator<BigInteger> operator and a int repetitions. The method
repeatOperator should repeatedly apply the operator to the startValue and return the
result as a BigInteger. The number of repetitions is given by repetitions. Write this
method as it could be written inside a class such as Math. Example: suppose the start value is
BigInteger.valueOf(3), the operator is (BigInteger bi -> bi.multiply(BigInteger.valueOf(2))
and the number of repetitions is 3, than repeatOperator should return a BigInteger with
value equal to ((3 × 2) × 2) × 2 = 24, which is the number 3 multiply by 2 for three times.
b. The Collection interface and therefore the List interface have a method addAll that can
be used to add all elements from another Collection to the local Collection. Classes
that implement these interfaces, such as ArrayList, have to give an implementation of the
method. Suppose the programmers of the ArrayList class implemented all methods from
the List and Collections interfaces, except the addAll method. Write the implementation
of the addAll method as it could be written in the class ArrayList. Note: the types of
elements that are stroed in the local ArrayLsit and in the argument Collection is E.
The exam continues on the next page.
Programming —
Question 3
FEB22012X —
Practice Exam
(30 points)
a. A programmer is working on a project and has defined a number of new classes A, B, C, D, E
and F, each with a constructor that accepts zero elements. There are some subtype-supertype
relations between these types. The goal of this question is to create a class hierarchy diagram
showing these relations. It is known that the following code can be compiled without error:
1
2
3
4
5
C
A
D
F
f
c
a
D
f
=
= new A () ;
= new D () ;
= new F () ;
= new B () ;
new E () ;
If any one of the following lines is added to the code, the compiler produces an incompatible
types error:
1
2
B b = new E () ;
E E = new B () ;
Deduce the relations between the types and create a diagram. A relation between a subtype
and supertype has to be drawn in the following manner:
Supertype
Subtype
b. Each of the following two code fragments contains an error. This can be either a compiler
error, a runtime error or a logical error. Find and explain the error in each fragment and
indicate which type of error it is.
Both methods are supposed to sum up a list of BigInteger objects and should produce the
result as a BigInteger.
Fragment 1
1
2
3
4
5
6
7
public BigInteger sum ( List < BigInteger > numbers )
{
BinaryOperator plus = ( BigInteger other ) -> other . add () ;
Stream < BigInteger > stream = numbers . stream () ;
Optional < BigInteger > result = stream . reduce ( plus ) ;
return result . orElse ( BigInteger . valueOf (0) ) ;
}
Fragment 2
1
2
3
4
5
6
7
8
9
public BigInteger sum ( List < BigInteger > numbers )
{
BigInteger sum = BigInteger . valueOf (0) ;
for ( BigInteger number : numbers )
{
sum . add ( number ) ;
}
return sum ;
}
The exam continues on the next page.
Programming —
Question 4
FEB22012X —
Practice Exam
(30 points)
The appendix contains the source code of classes which are used to model an inventory that contains
different assets. The classes provide the following functionality:
Inventory models the inventory of a company. There is a list of assets and a Map<Asset,Integer>
inventory that keeps track of how many copies of each asset are owned by the company.
Asset models an asset with an identifiable name, belonging to a certain category of assets. Each
asset also has a price.
In the following exercises you have to write additional methods for these classes. You are allowed
(but not always required) to add methods to other classes to solve the questions. Indicate to which
classes you add the methods. The questions can be answered independently.
a. Write a method countAssets in the class Inventory that has no arguments. This method
should count how many assets there are in the inventory. For this, it is necessary to add
up the numbers in the inventory map. This number should be returned as an int. The
appendix gives an example.
b. For the accountant it is helpful to receive a list with the total inventory. Add a method
writeInventory to the Inventory class that has an argument File output. This method
should first write a line with “Inventory” to this file. Afterwards, for each asset in the
inventory, it should write the following line to the file: ‘<<n>> times <<name>>” where <<n>>
is the number of copies of the asset in the inventory, and <<name>> is the name of the asset.
The appendix contains an example.
c. It is important to know the total value of the inventory to create a yearly balance. Add a
method computeValue to the Inventory class that has a String category as input argument,
and compute the total value of assets in this category. It is required to consider all assets
in the inventory, check if the asset has the correct category and if yes, take the number of
copies in the inventory, multiply this by the price of the asset, and at it to the total value.
The appendix contains an example.
d. In order to obtain a better overview over the assets in the inventory, the accountant wants to
define an natural order on the assets. It is important to order assets first by the alphabetic
order of their category. If the category is equal, the alphabetic order of the names of the
assets should be used. If the category and name of the assets are equal, the asset with the
highest price should come first (thus at the lowest index of a sorted list). Explain how you
must adapt the class Asset to define this natural order. The appendix contains an example
of how this natural order is supposed to work in practice.
End of exam. The appendix starts on the next page.
Programming —
FEB22012X —
Practice Exam
Appendix Question 4
Inventory.java
public class Inventory
{
private List<Asset> assets;
private Map<Asset,Integer> inventory;
public Inventory()
{
this.assets = new ArrayList<>();
this.inventory = new HashMap<>();
}
public void addAsset(Asset a, int count) {
if (!inventory.containsKey(a)) {
assets.add(a);
}
int current = inventory.getOrDefault(a, 0);
inventory.put(a, current + count);
}
public int countAssets()
{
Question 4a
Question 4a
}
public void writeInventory(File output)
{
Question 4b
Question 4b
}
public double computeValue(String category)
{
Question 4c
Question 4c
}
Question 4a/b/c/d
}
Appendix continues on the next page.
Programming —
FEB22012X —
Practice Exam
Asset.java
public class Asset
Question 4d
{
private String name;
private double price;
private String category;
public Asset(String name, double price, String category) {
this.name = name;
this.price = price;
this.category = category;
}
Question 4a/b/c/d
}
4a) Suppose we execute the following code:
Asset chair = new Asset("Chair", 150, "Furniture");
Asset chair2 = new Asset("Chair", 200, "Furniture");
Asset fridge = new Asset("Fridge", 500, "Appliances");
Asset oven = new Asset("Oven", 1200, "Appliances");
Inventory inventory = new Inventory();
inventory.addAsset(chair, 20);
inventory.addAsset(chair2, 5);
inventory.addAsset(fridge, 2);
inventory.addAsset(oven, 1);
System.out.println(inventory.countAssets());
The following should be printed:
28
4b) Suppose we execute the following code after 4a:
inventory.writeInventory(new File("inventory.txt"));
After the execution of this program, the file model.txt should contain
the following content:
Inventory
20 times Chair
5 times Chair
2 times Fridge
1 times Oven
Appendix continues on the next page.
Programming —
FEB22012X —
Practice Exam
4c) Suppose we execute the following code after 4a:
System.out.println(inventory.computeValue("Appliances"));
The following should be printed:
2200.0
4d) Suppose we execute the following code after 4a and changing
Asset.java:
List<Asset> lst = Arrays.asList(chair, chair2, fridge, oven);
Collections.sort(lst);
System.out.println(lst.get(0)==fridge);
System.out.println(lst.get(1)==oven);
System.out.println(lst.get(2)==chair2);
System.out.println(lst.get(3)==chair);
The following should be printed:
true
true
true
true
End of Appendix. Reference starts on the next page.
Java Class Reference
class Object
This is the official reference available during the FEB22012X examinations. Some
liberties were taken to simplify some aspects of the classes presented here. Type
constraints have been omitted and some intermediary classes have been left out.
This has been done in such a way that code written based on this reference should
be compatible with the full Java language.
Exceptions thrown by constructors in the java.io library and Scanner are not
indicated: you should take this into account.
String
boolean
int
toString
equals
hashCode
()
(Object other)
()
run
()
interface Runnable
void
class String implements Comparable<String>
java.lang
interface Comparable<E>
int
compareTo
(E o)
class Double extends Number implements Comparable<Double>
static
constructor
double
Double
parseDouble
(double d)
(String s)
class Integer extends Number implements Comparable<Integer>
static
constructor
int
Integer
parseInt
(int n)
(String s)
iterator
forEach
()
(Consumer<T> action)
interface Iterable<E>
default
Iterator<E>
void
static
static
static
static
static
static
static
static
static
static
static
static
static
static
static
static
static
static
double
double
int
double
double
double
double
double
double
int
double
double
int
double
long
double
double
double
PI
E
abs
abs
ceil
cos
exp
floor
log
max
max
min
min
pow
round
sin
sqrt
tan
(int n)
(double
(double
(double
(double
(double
(double
(int i,
(double
(double
(int i,
(double
(double
(double
(double
(double
d)
d)
d)
d)
d)
d)
int j)
i, double j)
i, double j)
int j)
base, double power)
d)
d)
d)
d)
equalsIgnoreCase
compareTo
length
substring
substring
concat
charAt
indexOf
toUpperCase
toLowerCase
split
contains
endsWith
startsWith
trim
replaceAll
(String s)
(String s)
()
(int from)
(int from, int to)
(String s)
(int pos)
(char c)
()
()
(String pattern)
(String pat)
(String suffix)
(String prefix)
()
(String pat, String rep)
InputStream
PrintStream
long
in
out
currentTimeMillis
()
class System
static
static
static
class Math
boolean
int
int
String
String
String
char
int
String
String
String []
boolean
boolean
bolean
String
String
java.math
class BigInteger extends Number implements Comparable<BigInteger>
static
BigInteger
BigInteger
BigInteger
BigInteger
BigInteger
BigInteger
BigInteger
BigInteger
BigInteger
BigInteger
BigInteger
BigInteger
abs
add
divide
max
min
mod
multiply
negate
pow
remainder
subtract
valueOf
()
(BigInteger
(BigInteger
(BigInteger
(BigInteger
(BigInteger
(BigInteger
()
(BigInteger
(BigInteger
(BigInteger
(int val)
abstract class Number
abstract
abstract
double
int
doubleValue
intValue
()
()
Reference continues on the next page.
Reference continues on the next page.
val)
val)
val)
val)
mod)
val)
val)
val)
val)
java.util
interface Deque<E> extends Queue<E>
void
void
E
E
E
E
class ArrayList<E> implements List<E>
constructor
constructor
ArrayList<E>
ArrayList<E>
()
(Collection<? extends E> c)
interface Collection<E> extends Iterable<E>
default
boolean
boolean
void
boolean
boolean
boolean
boolean
boolean
boolean
Stream<E>
int
add
addAll
clear
contains
containsAll
isEmpty
remove
removeAll
retainAll
stream
size
(E e)
(Collection<E>
()
(Object o)
(Collection<?>
()
(Object o)
(Collection<?>
(Collection<?>
()
()
c)
<E> List<E>
<K,V> Map<K,V>
<E> Set<E>
int
<E> E
<E> E
void
void
<E> void
<E> void
<E> List<E>
<K,V> Map<K,V>
<E> Set<E>
(E e)
(E e)
()
()
()
()
class HashMap<K,V> implements Map<K,V>
constructor
constructor
HashMap<K,V>
HashMap<K,V>
()
(Map<K,V> m)
c)
class HashSet<E> implements Set<E>
constructor
constructor
c)
c)
HashSet<E>
HashSet<E>
()
(Collection<E> c)
hasNext
next
remove
()
()
()
interface Iterator<E>
boolean
E
void
class Collections
static
static
static
static
static
static
static
static
static
static
static
static
static
addFirst
addLast
getFirst
getLast
removeFirst
removeLast
emptyList
emptyMap
emptySet
frequency
max
min
reverse
shuffle
sort
sort
unmodifiableList
unmodifiableMap
unmodifiableSet
()
()
()
(Collection<?>
(Collection<E>
(Collection<E>
(List<?> list)
(List<?> list,
(List<E> list)
(List<E> list,
(List<E> list)
(Map<K,V> map)
(Set<E> set)
(T o1, T o2)
()
(Comparator<T> other)
(Function<T,Comparable> keyExtractor)
(Function<T,U> keyExtractor,
Comparator<U> keyComparator)
(Function<T,Comparable> keyExtractor)
(Function<T,V> keyExtractor,
Comparator<U> keyComparator)
()
()
class LinkedList<E> implements List<E>, Deque<E>
constructor
constructor
c, Object o)
c, Comparator<E> cmp)
c, Comparator<E> cmp)
LinkedList<E>
LinkedList<E>
()
(Collection<E> c)
interface List<E> extends Collection<E>
Random rnd)
Comparator<E> cmp)
default
void
E
int
E
E
void
List<E>
add
get
indexOf
remove
set
sort
subList
(int index, E element)
(int index)
(Object o)
(int index)
(int index, E element)
(Comparator<E> c)
(int from, int to)
clear
containsKey
containsValue
forEach
get
getOrDefault
isEmpty
keySet
merge
put
putAll
remove
size
values
()
(Object key)
(Object value)
(BiConsumer<K,V> action)
(Object key)
(Object key, V defaultValue)
()
()
(K key, V value, BinaryOperator<V> op)
(K key, V value)
(Map<K,V> m)
(Object key)
()
()
interface Comparator<T>
default
default
default
int
Comparator<T>
Comparator<T>
Comparator<T>
compare
reversed
thenComparing
thenComparing
default
<U> Comparator<T>
thenComparing
static
<T> Comparator<T>
<T,U>
Comparator<T>
<T> Comparator<T>
<T> Comparator<T>
comparing
static
static
static
comparing
naturalOrder
reverseOrder
Reference continues on the next page.
interface Map<K,V>
default
default
default
void
boolean
boolean
void
V
V
boolean
Set<K>
V
V
void
V
int
Set<V>
Reference continues on the next page.
class Otional<T>
static
static
static
class TreeMap<K,V> implements SortedMap<K,V>
<T> Optional<T>
T
void
boolean
<T> Optional<T>
<T> Optional<T>
T
empty
get
ifPresent
isPresent
of
ofNullable
orElse
()
()
(Consumer<T> action)
()
(T value)
(T value)
(T alternative)
constructor
constructor
constructor
TreeMap<K,V>
TreeMap<K,V>
TreeMap<K,V>
()
(Comparator<K> comparator)
(Map<K,V> m)
class TreeSet<E> implements SortedSet<E>
constructor
constructor
constructor
interface Queue<E> extends Collection<E>
TreeSet<E>
TreeSet<E>
TreeSet<E>
()
(Collection<E> c)
(Comparator<E> comparator)
accept
andThen
(T t, U u)
(BiConsumer<T,U> after)
apply
andThen
(T t, U u)
(Function<R,V> after)
java.util.function
class Random
constructor
constructor
boolean
double
double
int
Random
Random
nextBoolean
nextDouble
nextGaussian
nextInt
()
(long seed)
()
()
()
(int n)
Scanner
Scanner
Scanner
hasNext
hasNextBoolean
hasNextDouble
hasNextInt
nextBoolean
nextDouble
nextInt
nextLine
(File source)
(InputStream source)
(String source)
()
()
()
()
()
()
()
()
interface Set<E> extends Collection<E>
firstKey
headMap
lastKey
subMap
tailMap
()
(K toKey)
()
(K fromKey, K toKey)
(K fromKey)
interface SortedSet<E> extends Set<E>
E
SortedSet<E>
E
SortedSet<E>
SortedSet<E>
first
headSet
last
subSet
tailSet
()
(E toElement)
()
(E fromElement, E toElement)
(E fromElement)
R
BiFunction<T,U,V>
interface BinaryOperator<T> extends BiFunction<T,T,T>
static
static
T
BinaryOperator<T>
BinaryOperator<T>
apply
maxBy
minBy
(T t1, T t2)
(Comparator<T> comp)
(Comparator<T> comp)
accept
andThen
(T t)
(Consumer<T> after)
apply
andThen
compose
identity
(T t)
(Function<R,V> after)
(Function<V,T> before)
()
test
and
negate
or
isEqual
(T t)
(Predicate<T> other)
()
(Predicate<T> other)
(Object targetRef)
get
()
interface Consumer<T>
default
void
Consumer<T>
interface Function<T,R>
R
Function<T,V>
Function<V,R>
Function<T,T>
interface Predicate<T>
default
default
default
static
boolean
Predicate<T>
Predicate<T>
Predicate<T>
Predicate<T>
interface Supplier<T>
T
interface UnaryOperator<T> extends Function<T,T>
static
Reference continues on the next page.
void
BiConsumer<T,U>
interface BiFunction<T,U,R>
default
default
static
interface SortedMap<K,V> extends Map<K,V>
K
SortedMap<K,V>
K
SortedMap<K,V>
SortedMap<K,V>
default
default
class Scanner implements Iterator<String>, Closeable
constructor
constructor
constructor
boolean
boolean
boolean
boolean
boolean
double
int
String
interface BiConsumer<T,U>
T
UnaryOperator<T>
apply
identity
(T t)
()
Reference continues on the next page.
java.util.stream
java.io
interface Stream<T>
interface Closeable
static
static
static
static
boolean
boolean
<R,A> R
long
Stream<T>
Stream<T>
Optional<T>
Optional<T>
void
Stream<T>
<R> Stream<R>
Optional<T>
Optional<T>
boolean
Optional<T>
Stream<T>
Stream<T>
Stream<T>
<T> Stream<T>
Stream<T>
Stream<T>
Stream<T>
allMatch
anyMatch
collect
count
distinct
filter
findAny
findFirst
forEach
limit
map
max
min
noneMatch
reduce
skip
sorted
sorted
concat
generate
iterate
of
(Predicate<T> predicate)
(Predicate<T> predicate)
(Collector<T,A,R> collector)
()
()
(Predicate<T> predicate)
()
()
(Consumer<T> action)
(long maxSize)
(Function<T,R> mapper)
(Comparator<T> comparator)
(Comparator<T> comparator)
(Predicate<T> predicate)
(BinaryOperator<T> op)
(long n)
()
(Comparator<T> comparator)
(Stream<T> a, Stream<T> b)
(Supplier<T> s)
(T seed, UnaryOperator<T> op)
(T... values)
void
close
()
class BufferedReader extends Reader
constructor
String
BufferedReader
readLine
(Reader in)
()
class DataInputStream extends InputStream
constructor
boolean
char
double
int
DataInputStream
readBoolean
readChar
readDouble
readInt
(InputStream in)
()
()
()
()
class DataOutputStream extends OutputStream
constructor
void
void
void
void
DataOutputStream
writeBoolean
writeChar
writeDouble
writeInt
(OutputStream out)
(boolean v)
(char c)
(double v)
(int v)
class File implements Comparable<File>
class Collectors
static
<T,?,Long>*
static
static
static
groupingBy
<T,?,Map<K,List<T>>*
<String,?,String>* joining
<String,?,String>* joining
static
<String,?,String>*
joining
static
static
static
static
<T,?,Optional<T>>*
maxBy
minBy
toList
toSet
<T,?,Optional<T>>*
<T,?,List<T>>*
<T,?,Set<T>>*
counting
constructor
boolean
boolean
boolean
()
(Function<T,K> classifier)
()
(String delimiter)
(String delimiter, String prefix,
String suffix)
(Comparator<T> comparator)
(Comparator<T> comparator)
()
()
File
exists
isDirectory
isFile
(String pathname)
()
()
()
class FileInputStream extends InputStream
constructor
constructor
FileInputStream
FileInputStream
(File file)
(String name)
class FileOutputStream extends OutputStream
constructor
constructor
FileOutputStream
FileOutputStream
(File file)
(String name)
FileReader
FileReader
(File file)
(String filename)
* Note:
The return types of the Collectors class are all a Collector<T,?,R>, but only the generic
part of the type is given to avoid the return types do not fit in the table. For example: if <T,?,Long>
is indicated for the counting method, the actual return type is Collector<T,?,Long>.
class FileReader extends Reader
constructor
constructor
abstract class InputStream implements Closeable
abstract
int
read
()
class LineNumberReader extends BufferedReader
constructor
int
Reference continues on the next page.
LineNumberReader
getLineNumber
(Reader in)
()
Reference continues on the next page.
Exceptions
abstract class OutputStream implements Closeable
void
write
(int b)
Note: all classes in this section have constructors similar to Throwable.
class PrintStream extends OutputStream
constructor
constructor
constructor
void
void
class Throwable
PrintStream
PrintStream
PrintStream
print
println
(File file)
(OutputStream out)
(String filename)
(String s)
(String s)
PrintWriter
PrintWriter
PrintWriter
print
println
(File file)
(OutputStream out)
(String filename)
(String s)
(Strng s)
class PrintWriter extends Writer
constructor
constructor
constructor
void
void
constructor
constructor
constructor
Throwable
Throwable
Throwable
()
(String message)
(String message, Throwable cause)
class Error extends Throwable
class VirtualMachineError extends Error
class OutOfMemoryError extends VirtualMachineError
class StackOverflowError extends VirtualMachineError
abstract class Reader implements Closeable
abstract
int
read
()
class IOException extends Exception
abstract class Writer implements Closeable
abstract
void
write
class Exception extends Throwable
(int v)
class FileNotFoundException extends IOException
class RuntimeException extends Exception
class IllegalArgumentException extends RuntimeException
class NumberFormatException extends IllegalArgumentException
class NullPointerException extends RuntimeException
class IndexOutOfBoundsException extends RuntimeException
class UnsupportedOperationException extends RuntimeException
End of reference and examination materials.
End of reference and examination materials.
Download