Starting today, I am going to publish one article with 3 tricky Java interview questions every week. The questions will be addressed in English and no answer will be provided for them. In addition, for this kind of articles, comments are disabled by default.
Let's start...
Q1: What's the output printed by running method main?
public class Main {
public static void main(String[] args) {
System.out.println(testTryCatchFinally());
}
public static int testTryCatchFinally() {
int i = 1;
try {
return ++i / 0;
} catch (Exception e) {
// Silent catch. Not recommended.
} finally {
return i++;
}
}
}
Q2: What's the output printed by running method main?
public class Main {
public static void main(String[] args) {
testFloatingPoint();
}
public static void testFloatingPoint() {
double value = 1.000000001d; // 8 zeros
if (value >= 1.0) {
value = 0.999999999999f; // 12 digits after comma
}
if (value >= 1.0) {
throw new IllegalArgumentException("Value is greater or equal than 1.0");
}
System.out.println(value);
}
}
Q3: Take a look over the existing code and provide an answer to multiple questions
- What's the output printed by running method main?
- There is any way to improve performance of given piece of code?
public class Main {
public static void main(String[] args) {
printAllEligibleCandidates();
}
public static void printAllEligibleCandidates() {
List<Candidate> candidates = Arrays.asList(new Candidate("Alin", 18),
new Candidate("Anca", 24),
new Candidate("Dana", 17)
);
candidates.parallelStream()
.filter(candidate -> candidate.getAge() >= 18)
.filter(candidate -> candidate.getName().startsWith("A"))
.forEach(System.out::println);
}
public static class Candidate {
private String name;
private int age;
public Candidate(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Candidate{" + "name='" + name + '\'' + ", age=" + age + '}';
}
}
}