Interview questions
What's the difference between the JDK, JRE and JVM?
How I'd answer:
"The JVM is the virtual machine that runs Java bytecode — it interprets it, JIT-compiles hot code to machine code, and manages memory with
the garbage collector. The JRE is the runtime environment: the JVM plus the standard class libraries, which is what you need to run a Java
program. The JDK is the development kit: the JRE plus the compiler javac and tools like the debugger — what you need to write programs.
Since Java 11 there's no separate JRE download; you install a JDK. Bytecode is why Java is portable: the same .class file runs on any
OS or CPU with a JVM."
Combines: Ch 1; How Computers Work Ch 8.
Is Java pass-by-value or pass-by-reference?
How I'd answer: "Always pass-by-value. When you call a method, the value in each argument variable is copied into the parameter. For primitives, that value is the number itself, so the method can't change the caller's variable. For arrays and objects, the variable holds a reference, so what's copied is the reference — the method can modify the object it points to, and the caller sees that. But if the method reassigns its parameter to a new object, the caller's variable is unaffected, which proves it isn't pass-by-reference."
Combines: Ch 7, 8. (Objects in full: Classes, Objects and Memory.)
What does this print, and why?" int a = 5; System.out.println(a++ + " " + ++a + " " + a / 2);
How I'd answer:
"a++ gives 5 and then makes a 6. ++a makes a 7 and gives 7. Then a / 2 is 7 / 2, integer division, which is 3. So it prints
5 7 3. In real code I'd avoid mixing increments into expressions like this because it's easy to misread."
Combines: Ch 3.
Why is (low + high) / 2 a bug in binary search, and what's the fix?
How I'd answer:
"If low and high are both large ints, their sum can exceed Integer.MAX_VALUE, about 2.1 billion, and overflow silently into a
negative number, giving a negative index. The fix is low + (high - low) / 2, which never exceeds high. Alternatively, (low + high) >>> 1
uses an unsigned shift, which also works for non-negative indexes."
Combines: Ch 2, 3; How Computers Work Ch 4.1. (Shifts: Bit Manipulation (coming soon).)
Your solution passes small tests but gets Time Limit Exceeded on big inputs on Codeforces, and the algorithm is right. What might be wrong?
How I'd answer:
"In Java a common cause is slow I/O. Scanner parses input with regular expressions and is slow for hundreds of thousands of tokens, and
calling System.out.println in a loop makes many small writes. I'd switch to BufferedReader with StringTokenizer for input and collect
output in a StringBuilder, printing once at the end. That usually cuts I/O time several-fold. If it's still slow, I'd look for hidden
costs inside loops, like building strings with +."
Combines: Ch 9; Operating Systems Ch 2 (system call cost).