Part 5 covers the catch-or-declare rule, thread priority and start versus run, anonymous classes, the exact ranges of short and char, finalization, and the difference between & and &&. The AWT menu and event-class questions from the original list are here too, answered briefly, since they mostly appear in written tests now.
Try to answer each question in under thirty seconds, out loud, before reading. For the thread and operator questions, run the snippets and change one line to see what breaks. That is the fastest way to make these answers your own.
Q1. What is the catch-or-declare rule?
If code inside a method can throw a checked exception, the method must do one of two things: handle it with a try/catch, or declare it with throws in its signature so the caller deals with it. If it does neither, the code does not compile. The rule applies only to checked exceptions, not to RuntimeException subclasses or Error.
A small detail interviewers like: try-with-resources counts too. If the resource's close() throws a checked exception, that exception must also be caught or declared.
Q2. How is CheckboxMenuItem different from MenuItem?
CheckboxMenuItem extends MenuItem and adds an on/off state, shown as a tick next to the text. You read and change it with getState() and setState(), and you listen with an ItemListener instead of only an ActionListener. In Swing the equivalents are JMenuItem and JCheckBoxMenuItem.
Q3. What is thread priority, and does the scheduler always respect it?
Each Java thread has a priority from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY), and a new thread takes its creator's priority, which is 5 (NORM_PRIORITY) for threads started from main. The idea is that higher priority threads get CPU time first.
In practice it is only a hint. Java threads run on OS threads, and the operating system may map, flatten or ignore Java priorities. Virtual threads (Java 21) always have normal priority and setPriority has no effect on them. Never rely on priorities for correct behaviour.
Q4. Which class sits at the top of the AWT event hierarchy?
java.awt.AWTEvent is the root of all AWT event classes such as ActionEvent, MouseEvent and KeyEvent. It itself extends java.util.EventObject, which is the general base class for events in Java and holds the event source.
Q5. What state is a thread in right after you create it and call start()?
Before start() it is NEW. After start() it becomes RUNNABLE. Old books split this into "ready" and "running", but Java's Thread.State has only RUNNABLE for both, meaning the thread is either running or eligible to run when the CPU is free.
Q6. Can an anonymous class extend a class and implement an interface at the same time?
No. An anonymous class is written as new SomeType() { ... }, and that single type is either the class it extends or the one interface it implements. It cannot do both, and it cannot implement two interfaces. If you need that, write a named local or nested class.
For interfaces with a single abstract method, a lambda usually replaces the anonymous class completely, as in Runnable r = () -> System.out.println("hi");.
Q7. What is the range of the short type?
A short is a signed 16-bit integer, so its range is -215 to 215 - 1, which is -32768 to 32767. These limits are available as Short.MIN_VALUE and Short.MAX_VALUE.
Q8. What is the range of the char type?
A char is an unsigned 16-bit value, from 0 to 216 - 1, which is 0 to 65535 ('\u0000' to ''). It is Java's only unsigned primitive type. Each char is a UTF-16 code unit, so characters outside that range, like many emoji, take two chars.
public class RangeDemo {
public static void main(String[] args) {
System.out.println(Short.MIN_VALUE + " to " + Short.MAX_VALUE);
System.out.println((int) Character.MIN_VALUE + " to " + (int) Character.MAX_VALUE);
short s = Short.MAX_VALUE;
s++;
System.out.println(s);
}
}
-32768 to 32767
0 to 65535
-32768
The last line shows overflow wrapping around, the same as with int.
Q9. In which package are most AWT event classes defined?
Most of them, like ActionEvent, MouseEvent and WindowEvent, along with listener interfaces and adapter classes, live in java.awt.event. The base class AWTEvent is in java.awt. Swing adds its own events in javax.swing.event.
Q10. What is the direct superclass of Menu?
java.awt.Menu extends MenuItem. That is what lets you put a menu inside another menu to make a submenu: a Menu is itself a kind of menu item.
Q11. What was finalization meant for, and should you use it?
Finalization gave an object one last chance to release resources (like a file handle) before the garbage collector reclaimed it, by overriding Object.finalize(). The problems: there is no guarantee when, or even whether, it runs; it slows down garbage collection; and a finalizer can make the object reachable again.
It has been deprecated for removal since Java 18 (JEP 421). Release resources explicitly with try-with-resources, and use java.lang.ref.Cleaner only as a backup for objects that wrap native resources.
Q12. What is the direct superclass of MenuComponent?
java.lang.Object. MenuComponent is the root of AWT's menu classes (MenuBar, MenuItem, Menu) and is separate from Component, because menus were drawn by the native OS rather than inside a container.
Q13. Who calls a thread's run() method?
The JVM does. When you call start(), the JVM creates a new thread of execution, and that new thread calls run(). If you call run() yourself, it is just a normal method call on the current thread, and no new thread is created. This is a classic interview trap.
public class StartVsRun {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> System.out.println("running in " + Thread.currentThread().getName());
Thread t = new Thread(task, "worker");
t.run();
t.start();
t.join();
}
}
running in main
running in worker
Q14. What is the difference between & and && on boolean values?
&& is the short-circuit AND. It evaluates the left side first, and if that is false, it skips the right side because the result is already known. & on booleans is the logical AND that always evaluates both sides. The same goes for || versus |.
Short-circuiting is what makes s != null && s.length() > 3 safe. With &, the second part would run even when s is null and throw NullPointerException. On int values, & is the bitwise AND, which is a different use.
public class AndDemo {
static boolean check(String name) {
System.out.println("evaluated " + name);
return true;
}
public static void main(String[] args) {
boolean r1 = false & check("right side of &");
boolean r2 = false && check("right side of &&");
System.out.println(r1 + " " + r2);
}
}
evaluated right side of &
false false
Q15. Name three subclasses of java.awt.Component.
Any three of Button, Label, Canvas, Checkbox, Choice, List, Scrollbar, TextComponent and Container. Container is the interesting one: Panel, Window, Frame and all Swing components (through JComponent) come from it.
Quick revision
- Checked exceptions must be caught or declared with
throws; unchecked ones need not be. - Thread priority is 1 to 10, default 5, and only a hint to the OS.
- Calling
run()directly runs on the current thread; onlystart()creates a new one. - short: -32768 to 32767. char: 0 to 65535, the only unsigned primitive.
&&and||skip the right side when the answer is already known;&and|do not.- An anonymous class extends one class or implements one interface, never both.
Frequently asked questions
Which questions from this part matter most for interviews?
start versus run, & versus &&, and the catch-or-declare rule. They are short, easy to test with a quick code question, and many candidates still get them wrong.
Do I need to memorise all primitive ranges?
Know the sizes (byte 8, short 16, char 16, int 32, long 64 bits) and you can work out the ranges. Remember that only char is unsigned, and that int's maximum is a little over 2.1 billion.
How should I practise output-prediction questions like these?
Write the expected output on paper first, then run the program. Whenever you were wrong, note down why. A page of your own mistakes is worth more than any question bank.
Comments
Post a Comment