Part 4 covers wrapper classes, what garbage collection can and cannot promise, where the package statement goes, finalization, thread scheduling, native methods, operator precedence and default values. A few AWT questions (Applet, Dialog, painting, clipping) are included because they still appear in older question banks; those get short answers and a note on what replaced them.
Before reading each answer, say yours aloud and try to add one example or one "what changed in modern Java" point. Interviewers remember candidates who add that second sentence.
Q1. What are wrapper classes in Java?
Wrapper classes let you treat a primitive value as an object. Each primitive has one: int has Integer, char has Character, boolean has Boolean, and so on for byte, short, long, float and double. You need them because collections and generics only work with objects, so a List<int> is not allowed but List<Integer> is.
Since Java 5, autoboxing and unboxing convert between the two automatically. Two traps to mention: unboxing a null throws NullPointerException, and comparing wrappers with == compares references. Values from -128 to 127 are cached by Integer.valueOf, so == happens to work for small numbers and then fails for larger ones. Always use equals().
public class WrapperDemo {
public static void main(String[] args) {
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b);
System.out.println(c == d);
System.out.println(c.equals(d));
}
}
true
false
true
Q2. If Java has garbage collection, can a program still run out of memory?
Yes. The garbage collector only frees objects that are no longer reachable. If your code keeps references to objects it no longer needs, they are still reachable and cannot be collected. Typical causes are a static Map used as a cache that never removes entries, listeners that are registered but never removed, or a ThreadLocal left set in a thread pool.
A program can also simply need more memory than the heap allows, for example by loading a huge file into one list. In both cases the JVM throws OutOfMemoryError. GC removes the need to free memory by hand, not the need to think about memory.
Q3. Where must the package statement appear in a source file?
It must be the first statement in the file. Only comments and blank lines may come before it. Imports come after it, then the type declarations. A file can have at most one package statement, and if it has none, its classes go into the unnamed default package, which you should avoid in real projects. The folder structure should match the package name, so com.shop.cart lives in com/shop/cart/.
Q4. Can finalize() run on an object that is still reachable?
The garbage collector will not call finalize() on a reachable object. It only considers finalizing objects it has found unreachable. But finalize() is just a protected method, so your own code can call it directly at any time, reachable or not. Doing that does not free the object.
Finalization has been deprecated for removal since Java 18 because it is slow, unpredictable and can bring objects back to life. Use try-with-resources with AutoCloseable for cleanup, and java.lang.ref.Cleaner as a safety net if you really need one.
Q5. What is the direct superclass of Applet, and what layouts were used with it?
java.applet.Applet extends java.awt.Panel, so an applet was a panel that a browser could host, and its default layout was FlowLayout. The common AWT layout managers are:
FlowLayout: places components in a row and wraps to the next line.BorderLayout: five regions, NORTH, SOUTH, EAST, WEST and CENTER (not nine, as some notes say).GridLayout(rows, cols): equal-sized cells in a grid.CardLayoutandGridBagLayoutfor stacked cards and flexible grids.
Browsers dropped applet support years ago, the Applet API was deprecated in Java 9 and has since been removed from the JDK. Web front ends today are built with HTML and JavaScript frameworks talking to a Java backend.
Q6. What is the difference between preemptive scheduling and time slicing?
With preemptive scheduling, a running thread can be interrupted at any moment when a higher priority thread becomes ready. The high priority thread runs until it finishes, blocks or is itself preempted. With time slicing, each ready thread gets a small slice of CPU time, and when the slice ends it goes back to the ready queue and another thread runs, even if no higher priority thread showed up.
Modern operating systems use both together. Java itself does not fix the policy. Java threads map to OS threads, so the OS scheduler decides, and Java thread priorities are only hints. Code that depends on a particular scheduling order is broken.
Q7. Name some AWT Component subclasses you can paint on.
Canvas, Panel, Frame and (historically) Applet. In AWT you override paint(Graphics g) and draw with the Graphics object. In Swing you would extend JPanel and override paintComponent(Graphics g) instead, calling super.paintComponent(g) first. JavaFX uses a Canvas node with a GraphicsContext.
Q8. What does readLine() return at the end of a file?
BufferedReader.readLine() returns null when there is nothing left to read. It does not throw an exception and it does not return an empty string (an empty string means an empty line). That is why the standard loop checks for null.
import java.io.*;
public class ReadLineDemo {
static String label;
public static void main(String[] args) throws IOException {
var reader = new BufferedReader(new StringReader("first\nsecond"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
System.out.println(reader.readLine());
System.out.println(label);
}
}
first
second
null
null
For whole files, Files.readAllLines(path) or Files.lines(path) are shorter. The last line of output belongs to Q15.
Q9. What is the direct superclass of Dialog?
java.awt.Dialog extends java.awt.Window, the same as Frame. A Dialog is a top-level window that has an owner and can be modal, meaning it blocks input to its owner until closed. Swing's JDialog extends Dialog.
Q10. What is clipping in graphics?
Clipping limits drawing to a certain region. Anything painted outside the clip area is simply not shown. In AWT you set it with Graphics.setClip(...) or narrow it with clipRect(...). The toolkit also uses clipping during repaints so that only the damaged part of a window is redrawn, which saves work.
Q11. What is a native method?
A native method is declared in Java with the native keyword and has no body. Its implementation is written in another language, usually C or C++, compiled into a platform library and connected through JNI. Many JDK internals are native, for example System.currentTimeMillis() and Object.hashCode().
For new code that needs to call native libraries, Java 22 finalised the Foreign Function and Memory API, which avoids writing JNI glue code.
Q12. Can a for loop run forever?
Yes. All three parts of a for header are optional, so for (;;) { ... } loops until something inside it calls break, return, throws an exception or the program exits. It is the same as while (true). Server loops and game loops are written this way, always with a clear exit path inside.
Q13. What are operator precedence and associativity?
Precedence decides which operator binds first when different operators are mixed. * has higher precedence than +, so 2 + 3 * 4 is 14, not 20. Associativity decides the order when operators of the same precedence appear together. Most binary operators are left-associative, so 20 - 5 - 3 is (20 - 5) - 3, which is 12. Assignment is right-associative, so x = y = 7 sets y first, then x.
public class PrecedenceDemo {
public static void main(String[] args) {
int a = 2 + 3 * 4;
int b = 20 - 5 - 3;
int x, y;
x = y = 7;
System.out.println(a + " " + b + " " + x + " " + y);
}
}
14 12 7 7
Precedence does not change evaluation order of operands: Java always evaluates operands left to right. When in doubt, add brackets. Readers will thank you.
Q14. What state is a thread in while it is blocked on I/O?
Older textbooks say "waiting" or "blocked". Conceptually that is right: the thread cannot continue until data arrives. But if you call getState() or look at a thread dump, a platform thread stuck in a socket or file read usually shows as RUNNABLE, because from the JVM's point of view it is running native code. BLOCKED is reserved for waiting on a monitor lock, and WAITING/TIMED_WAITING for calls like wait(), join() or sleep().
Mentioning this difference shows you have actually read a thread dump. With virtual threads (Java 21), blocking I/O usually parks the virtual thread and frees its carrier thread.
Q15. What is the default value of a String variable?
A String field (instance or static) that you do not initialise gets null, like every other reference type. It does not get an empty string. Local variables are different: they get no default at all, and the compiler refuses to let you read one before you assign it. The label field in the Q8 snippet printed null for this reason.
Quick revision
- Compare wrapper objects with
equals();==only works by luck for cached values -128 to 127. - GC frees unreachable objects only; leaks through live references still cause
OutOfMemoryError. - The package statement comes first, before imports, with only comments above it.
- finalize() is deprecated for removal; use try-with-resources or Cleaner.
readLine()returns null at end of stream.- Fields default to null/0/false; local variables have no default.
Frequently asked questions
How do I explain a memory leak in Java in an interview?
Give one concrete case, like a static HashMap cache that only grows, and say how you would find it: a heap dump analysed in Eclipse MAT or VisualVM, looking for the biggest retained objects. Then give the fix, such as a size-limited cache or removing entries.
Are precedence questions usually asked as MCQs?
Yes, mostly in written tests with tricky expressions mixing ++, + and ?:. Practise by predicting the output, then running the code. Keep a small table of the top ten operators in your notes.
Should I mention virtual threads if the interviewer did not ask?
Briefly, when it fits, like in the I/O blocking question. One sentence is enough. If they are interested, they will ask more.
Comments
Post a Comment