Part 8 looks at casting to interfaces, how garbage collection decides what to free, integer division, what happens when a thread cannot get a lock, character streams versus byte streams, catch clauses, default access, constructors and labelled statements. Window, Frame, Font and SimpleTimeZone also make a short appearance.
Several of these questions have a "gotcha" in them. For each one, try to say not only the answer but also the edge case: when the cast compiles but fails at runtime, which way integer division rounds for negatives, which thread state a blocked thread is in. That is usually what the interviewer is really testing.
Q1. When is it allowed to cast an object reference to an interface type?
The compiler is generous here. If the reference's static type is a class that is not final, a cast to any interface compiles, because some subclass might implement it. The check happens at runtime: if the actual object does not implement the interface, you get a ClassCastException.
If the class is final and does not implement the interface, the compiler knows the cast can never succeed and rejects it ("incompatible types").
static class Dog {}
Object o = new Dog();
Runnable r = (Runnable) o; // compiles, throws ClassCastException at runtime
To cast safely, check first with pattern matching: if (o instanceof Runnable r) { r.run(); }.
Q2. How is an AWT Frame different from a Window?
Window is a top-level area with no border, title or menu bar. Frame extends Window and adds the things you expect from an application window: a title bar, a border, minimise and close buttons, and support for a MenuBar. A plain Window is used for things like splash screens or popups.
In Swing the matching classes are JWindow and JFrame.
Q3. Which class is the root of every Java class hierarchy?
java.lang.Object. A class with no extends clause extends Object automatically, so every class inherits methods like equals(), hashCode(), toString(), getClass(), and the wait() and notify() family. Arrays are objects too and also have Object as their superclass.
Primitives (int, double and so on) are not objects and do not extend anything; their wrapper classes do.
Q4. Can the garbage collector free an object that is still reachable?
No. An object is a candidate for collection only when no chain of strong references leads to it from a GC root (local variables on a thread's stack, static fields, and a few others). As long as your code can still reach it, it stays.
Being unreachable makes an object eligible, but there is no promise about when, or whether, it is actually collected. Weak and soft references (WeakReference, SoftReference) are the deliberate exception: they let you hold an object without stopping the collector from freeing it.
Q5. Which is the right syntax for the ternary operator: x : y ? z or x ? y : z?
x ? y : z. The condition comes first, then the value when it is true, then the value when it is false. For example, String label = marks >= 40 ? "pass" : "fail";.
When you are choosing between more than two values, a switch expression (Java 14+) is often easier to read than nested ternaries.
Q6. How do Font and FontMetrics differ?
Font describes a typeface you want to use: name, style (plain, bold, italic) and point size. FontMetrics tells you how that font actually renders on a particular device: ascent, descent, leading, line height and the pixel width of a string via stringWidth(). You need FontMetrics when you have to centre or align text precisely while drawing.
In Java2D the newer route is Font.getStringBounds() with a FontRenderContext, or TextLayout.
Q7. How does integer division round its result?
It truncates towards zero. The fractional part is simply dropped, so positive results round down and negative results round up. If you want flooring, use Math.floorDiv. If you want a decimal result, make at least one operand a double.
System.out.println(7 / 2); // 3
System.out.println(-7 / 2); // -3
System.out.println(Math.floorDiv(-7, 2)); // -4
System.out.println(7 / 2.0); // 3.5
Integer division by zero throws ArithmeticException, while floating-point division by zero gives Infinity or NaN.
Q8. What happens to a thread that tries to take a lock another thread already holds?
It stops and waits until the lock is released. For synchronized methods and blocks, the thread's state becomes BLOCKED (not WAITING; that state is for wait(), join() and park()). When the owner leaves the synchronized code, one of the blocked threads gets the lock and continues. There is no timeout and it cannot be interrupted while blocked.
If you need a timeout or the ability to give up, use ReentrantLock.tryLock(timeout, unit) or lockInterruptibly().
Q9. How do Reader/Writer differ from InputStream/OutputStream?
InputStream and OutputStream work with raw bytes. Use them for binary data such as images, zip files or network protocols. Reader and Writer work with characters, and they decode and encode text using a character set (UTF-8, for example). InputStreamReader and OutputStreamWriter are the bridges between the two worlds.
Always pass the charset explicitly, or rely on Java 18+ where UTF-8 is the default. For whole files, java.nio.file.Files.readString(), readAllLines() and newBufferedReader() are the simplest options today.
Q10. What kinds of exceptions can a catch clause handle?
Anything that is a Throwable. That includes checked exceptions (subclasses of Exception except RuntimeException), unchecked exceptions (RuntimeException and its subclasses) and Errors. A catch block for a parent type also catches all its subtypes, which is why more specific catch blocks must come first.
Catching Error (OutOfMemoryError, StackOverflowError) is legal but almost never sensible. Since Java 7 one block can handle several unrelated types with multi-catch: catch (IOException | SQLException e).
Q11. If a class has no access modifier, who can use it?
Only code in the same package. This is called package-private or default access. Classes in other packages, even subclasses, cannot refer to it. It is a good choice for helper classes that are an implementation detail of a package.
With the module system (Java 9+), even public classes are only visible outside a module if their package is exported.
Q12. What is SimpleTimeZone used for?
SimpleTimeZone is a concrete subclass of TimeZone meant for use with the Gregorian calendar. It describes a zone by a raw offset from UTC and, optionally, simple start and end rules for daylight saving time. It does not hold historical rule changes, which is why TimeZone.getTimeZone("Asia/Kolkata") normally gives you a different, data-driven implementation.
Modern code uses java.time.ZoneId and ZonedDateTime, which read the full time-zone database.
Q13. What is the Map interface?
Map is the collections framework's interface for key-value pairs. Each key maps to at most one value, keys are unique, and you look values up by key with get(). It replaced the old Dictionary class in Java 1.2. Note that Map does not extend Collection.
The common implementations are HashMap (fast, unordered), LinkedHashMap (keeps insertion order), TreeMap (sorted by key) and ConcurrentHashMap (for many threads). Java 8 added helpful defaults such as getOrDefault(), computeIfAbsent() and merge().
Q14. Are constructors inherited by subclasses?
No. Constructors are not members, so a subclass does not inherit them, and you cannot call new Child(x) just because Parent has a constructor taking x. What is true is that every constructor of a subclass calls a superclass constructor first, either explicitly with super(...) or implicitly with super() if you write nothing.
That implicit call is why a subclass fails to compile when the parent has no no-argument constructor and the child does not call super(...) with arguments.
Q15. Which statements is it useful to put a label on?
The language lets you label almost any statement, but a label is only useful on a statement that contains a break or continue referring to it. In practice that means loops, and occasionally a plain block. The usual reason is to break out of, or continue, an outer loop from inside a nested one.
int[][] grid = {{1, 2, 3}, {4, 42, 6}, {7, 8, 9}};
search:
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] == 42) {
System.out.println("found at " + r + "," + c); // found at 1,1
break search;
}
}
}
If you find yourself needing labels often, moving the loops into a method and using return is usually cleaner.
Quick revision
- Casting a non-final class to an interface compiles; the check happens at runtime.
- Only unreachable objects can be collected, and even then there is no timing guarantee.
- Integer division truncates towards zero: -7 / 2 is -3.
- A thread waiting to enter synchronized code is BLOCKED, not WAITING.
- Streams are for bytes, Readers and Writers for text with a charset.
- Constructors are never inherited, but every constructor calls a super constructor first.
Frequently asked questions
Why do interviewers ask such small syntax questions?
They are quick filters. A wrong answer about integer division or constructor inheritance often hints at gaps elsewhere. Answer briefly, then add the edge case to show depth.
How can I prepare for garbage collection questions?
Be clear on GC roots and reachability first. Then learn the names of the current collectors (G1 is the default, ZGC for low pause times) and what -Xmx controls. That covers most fresher and mid-level interviews.
Is it enough to read answers, or should I code them?
Code the ones with outputs, like Q1, Q7 and Q15. Seeing the ClassCastException or the -3 yourself makes the answer much easier to recall under pressure.
Comments
Post a Comment