1) Co vypíše následující kód?
Kód: Vybrat vše
public class A {
public static void appendToString(String s) {
s = s + " world";
}
public static void main(String[] args) {
String s = "Hello";
appendToString(s);
System.out.println(s);
}
}
2) Co vypíše následující kód?
Kód: Vybrat vše
public class A {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6};
System.out.println(array[1] + array[3]);
}
}
3) Co udělá následující kód, pokud jsou zaplé asserty?
Kód: Vybrat vše
public class A {
public static void setInterval(int i) {
assert i > 0;
//...
}
public static void main(String[] args) {
setInterval(-1);
}
}
4) Co vypíše následující kód, pokud metoda someMethod vyhodí MyException?
Kód: Vybrat vše
public class A {
public static void main(String[] args) {
try {
someMethod();
} catch (MyException e) {
System.out.println("MyException");
} catch (Exception e) {
System.out.println("Exception");
} finally {
System.out.println("finally");
}
}
}
5) Mějme 3 interfaces:
Kód: Vybrat vše
interface Callable<T> {
T call();
}
interface Supplier<T> {
T get();
}
interface Predicate<T>{
boolean test(T t);
}
Kód: Vybrat vše
Supplier<Boolean> su = () -> { return true; };
Callable<Boolean> sa = () -> { return true; };
Predicate<Boolean> pr = () -> { return true; };
6) Doplňte kód tak, aby se přeložil bez chyby. Chyba je na 2. a 3. řádku.
Kód: Vybrat vše
enum Answer {
NO,
YES;
private boolean isYes;
private Answer(boolean isYes) {
this.isYes = isYes;
}
}
7) Ke kterému objektu se vztahuje keyword this?
Kód: Vybrat vše
public class A {
public void someMethod() {
Thread t = new Thread(() -> System.out.println(this));
}
}
8) Napište čítač (long) s metodami inc() a get(), který bude thread-safe.
Odpověď: Metody musí být synchronized.
Kód: Vybrat vše
public class Counter {
private long counter = 0;
public synchronized void inc() {
counter++;
}
public synchronized long get() {
return counter;
}
}
Odpověď: Nezapomenout na dělení ve float-point aritmetice.
Kód: Vybrat vše
public class TaxCalculator {
public double calculateTax(int gross, int taxPercentage) throws MyException {
if(gross < 0 || taxPercentage < 0 || taxPercentage > 100) throw new MyException();
return gross * (taxPercentage / 100.0);
}
}
Kód: Vybrat vše
interface Iterator<T> {
boolean hasNext();
T next();
}
public class A {
int[] elements;
int numElements;
public static void main(String[] args) {
Iterator<Integer> it = // doplňte kód
}
}
Kód: Vybrat vše
public class A {
int[] elements;
int numElements;
public static void main(String[] args) {
Iterator<Integer> it = new Iterator<Integer>() {
private int i = 0;
@Override
public boolean hasNext() {
return i < numElements;
}
@Override
public Integer next() {
if(hasNext) return elements[i++];
else throw new NoSuchElementException();
}
};
}
}