CORE JAVA IMPORTANT QUESTIONS - Part 6

This part mixes a few utility classes (GregorianCalendar, Runtime, Locale) with everyday language rules: what finally guarantees, what main() receives, how casting a double to a byte really works, and the difference between break and continue. There are also three old AWT questions, which I have kept but answered briefly with a note on what people use now.

Read each question and try to answer it out loud before you look at the answer. The casting and associativity questions are worth running yourself, because the outputs are not what most people guess the first time.

Q1. What does the GregorianCalendar class represent?

GregorianCalendar is a concrete subclass of java.util.Calendar that implements the Gregorian calendar, the one most of the world uses for civil dates. It knows about leap years and about the historical switch from the Julian calendar in 1582. You use it to add days, read the month or day of week, and so on.

It is a legacy class. Calendar and Date are mutable and have awkward APIs (months start from 0, for example). Since Java 8, new code uses java.time: LocalDate, LocalDateTime, ZonedDateTime, Period and Duration.

Q2. In AWT, which Container method makes a container recompute its layout and refresh?

validate(). When you add or remove components from an already visible container, you call validate() so the layout manager runs again and the components are positioned and redrawn. Swing code usually calls revalidate() followed by repaint() on a JComponent.

Plain AWT is rarely used for new desktop apps. Swing is still maintained, and JavaFX is the other common choice.

Q3. Why does Java have a Runtime class?

Runtime gives your program a handle to the JVM it is running in. You cannot create one; you get the single instance with Runtime.getRuntime(). Through it you can check memory (totalMemory(), freeMemory(), maxMemory()), count processors with availableProcessors(), register shutdown hooks, and request a garbage collection with gc().

It also has exec() for starting external processes, but ProcessBuilder is the cleaner way to do that today. Runtime.version() (Java 9+) tells you the exact Java version at runtime.

Q4. How many times can the garbage collector call finalize() on one object?

At most once. If finalize() "resurrects" the object by storing this somewhere reachable, and the object later becomes unreachable again, the JVM will not call finalize() a second time. It may also never be called at all, because there is no guarantee that the collector will run before the program exits.

finalize() has been deprecated since Java 9 and marked for removal since Java 18. For cleanup, use try-with-resources with AutoCloseable, or java.lang.ref.Cleaner for objects that hold native resources.

Q5. What is finally used for in a try-catch-finally block?

The finally block holds code that must run whether the try block finishes normally, throws an exception that is caught, or throws one that is not caught. Typical use is releasing something: closing a file, releasing a lock, returning a connection to a pool.

Even a return inside try does not skip finally; the finally block runs first, then the method returns. For resources, try-with-resources (Java 7) is shorter and safer than writing close() in finally yourself.

Q6. What parameter type does the main() method take?

The classic entry point is public static void main(String[] args). The parameter is an array of String holding the command-line arguments. You can also write it as String... args, which is the same type.

Java 25 finalised compact source files and instance main methods, so a simple program can now declare void main() with no parameter and no static. Interviewers still expect you to know the classic signature first.

Q7. Name a Java operator that groups from right to left.

The assignment operators (=, +=, -= and the rest) are right associative. That is why a = b = c = 5 works: it is read as a = (b = (c = 5)). The conditional operator ?: is right associative too, so chained ternaries group from the right. Unary operators such as !, ~, prefix ++ and casts also bind right to left.

int a, b, c;
a = b = c = 5;
int x = 7;
String size = x > 10 ? "big" : x > 5 ? "medium" : "small";
System.out.println(a + " " + b + " " + c + " " + size);   // 5 5 5 medium

Q8. What is the Locale class for?

A Locale identifies a language and region, such as en-IN or hi-IN. Classes that format output (NumberFormat, DateTimeFormatter, String.format with a locale argument) use it to follow local conventions for numbers, currency, dates and text.

For example, NumberFormat prints the same number as 1,234,567.5 for Locale.US and 1.234.567,5 for Locale.GERMANY, because Germans swap the roles of the comma and the dot. Create a locale with Locale.of("hi", "IN") on Java 19 and later, or Locale.forLanguageTag("hi-IN").

Q9. Is it legal to cast a double to a byte?

Yes, with an explicit cast. It is a narrowing conversion and happens in two steps: the double is first converted to an int (the fraction is dropped, and values outside the int range are clamped to Integer.MIN_VALUE or MAX_VALUE), then only the low 8 bits of that int are kept. NaN becomes 0.

System.out.println((byte) 300.7);   // 44   (300 keeps its low 8 bits)
System.out.println((byte) -129.9);  // 127
System.out.println((byte) 1e10);    // -1   (clamped to Integer.MAX_VALUE first)

Q10. How is break different from continue?

break exits the nearest enclosing loop or switch completely, and control moves to the statement after it. continue skips only the rest of the current iteration; the loop then checks its condition (and in a for loop, runs the update part) and carries on.

for (int i = 1; i <= 6; i++) {
    if (i == 3) continue;   // skip 3
    if (i == 5) break;      // stop at 5
    System.out.print(i + " ");
}
// prints: 1 2 4

Both can take a label to act on an outer loop, which is covered in Part 8.

Q11. What does a class have to do to implement an interface?

It names the interface in an implements clause and provides bodies for all of the interface's abstract methods. If it leaves any of them out, the class must be declared abstract. Methods it implements must be public, because interface methods are public.

Since Java 8, interfaces can have default and static methods with bodies, so a class only has to implement the abstract ones. It can still override a default method if it wants different behaviour.

Q12. Which method actually starts a new thread of execution?

start() on a Thread object. It asks the JVM to create a new thread, and that new thread calls run(). If you call run() directly, the code just runs on the current thread like any normal method call. Calling start() twice on the same Thread throws IllegalThreadStateException.

Thread t = new Thread(() ->
    System.out.println("running in " + Thread.currentThread().getName()), "worker");
t.run();    // running in main
t.start();  // running in worker

In current Java you will more often submit tasks to an ExecutorService, and Java 21 added virtual threads through Thread.ofVirtual() and Executors.newVirtualThreadPerTaskExecutor().

Q13. Name two classes that extend AWT's TextComponent.

TextField (a single line of editable text) and TextArea (multiple lines). TextComponent holds the shared parts, such as getText(), setText() and setEditable().

In Swing the equivalents are JTextField and JTextArea, which extend JTextComponent.

Q14. Why is the event-delegation model better than the older event-inheritance model?

In the old Java 1.0 model, a component handled events by being subclassed and overriding methods like handleEvent(), and unhandled events were passed up the container chain. The delegation model (Java 1.1) lets any object register as a listener for a specific event type on a component.

  • Separation: the code that reacts to an event lives in its own class, not inside the component, so UI and logic stay apart.
  • Performance: events are delivered only to objects that registered for them, so the system does not keep passing unhandled events up the hierarchy.

The same listener idea is used everywhere today, from Swing and JavaFX to Android click listeners.

Q15. Which AWT container can hold a MenuBar?

Frame. You attach one with frame.setMenuBar(menuBar). Other containers such as Panel or Dialog cannot hold an AWT MenuBar. In Swing, JFrame, JDialog and JApplet could take a JMenuBar through setJMenuBar().

Quick revision

  • Use java.time, not GregorianCalendar or Date, in new code.
  • Runtime.getRuntime() is your window into the JVM: memory, CPUs, shutdown hooks.
  • finalize() runs at most once, may never run, and is deprecated for removal.
  • finally runs even when try returns; prefer try-with-resources for closing things.
  • Assignment and ?: are right associative, so a = b = 5 works.
  • (byte) on a double first truncates to int, then keeps only the low 8 bits.

Frequently asked questions

Do I need to learn AWT for Java interviews in 2026?

For most backend and full-stack roles, no. Know what AWT and Swing are and understand the listener model, since that idea shows up everywhere. Spend the saved time on threads, exceptions and collections.

How should I practise casting questions?

Write tiny programs that cast edge values (negative numbers, values just past a type's range, very large doubles) and predict the output before running them. After ten or fifteen of these, the rules stick.

Are questions on finalize() still asked?

Sometimes, but usually as a trap. The answer they want is that it is unreliable and deprecated, and that you would use try-with-resources or Cleaner instead.

Core Java Important Questions: Part 1 | Part 2 | Part 3 | Part 4 | Part 5 | Part 6 | Part 7 | Part 8 | Part 9 | Part 10
← Previous: Part 5  |  Next: Part 7 →
See everything in one place: Interview Preparation Hub

Comments

Answered 0/0Correct 0