When should we use this annotation? How can we prevent heap pollution?
Continue reading “@SafeVarargs and Heap Pollution”Category: Java Interview Questions
There are many lists of interview questions. Often with wrong answers. I’ll try to explain why they are so wrong.
Note: In the category “Java Misnomers” are some more posts that could be helpful while preparing for job interviews.
Recursive FizzBuzz
FizzBuzz in two lines of code.
The only import you need is one for System.out
:
import static java.lang.System.out;
Simple two-liner:
static void f(int a, int z) {
out.println(a % 15 < 1 ? "FizzBuzz" : a % 3 < 1 ? "Fizz" : a % 5 < 1 ? "Buzz" : a);
if (a < z) f(1 + a, z);
}
Without using the literal “FizzBuzz”:
static void g(int a, int z) {
int x = 0;
if (a % 3 < 1) { out.print("Fizz"); ++x; }
if (a % 5 < 1) { out.print("Buzz"); ++x; }
if (x < 1) out.print(a);
out.println();
if (a < z) g(1 + a, z);
}
Note that I use x<1 instead of x==0 to save a single character.
Does Java support Multiple Inheritance?
This is probably often asked at interviews. But the question is incomplete.
== versus equals()
Most answers on the internet are incomplete and some are even plain wrong. I’ll try to list all differences.
Why is String immutable?
This has been answered a million times (I get a million results on google). But my answer is the most bestest!
Continue reading “Why is String immutable?”Is a Constructor a Method?
Why a constructor is not a method.
No, it’s not. In reflection both extend Executable
, but Constructor
does not extend Method
. It is a common misconception that constructors are methods and often asked about at job interviews.
Is Java object-oriented?
This is often asked at interviews. I’ll explain when to answer “yes” and when to answer “no”.
Continue reading “Is Java object-oriented?”