CORE JAVA IMPORTANT QUESTIONS - Part 2

Part 2 is a mix: resource bundles for translations, the transient keyword, the Collections API and Iterator, a second look at abstract classes versus interfaces, a few thread questions (blocking, synchronization, class locks, the deprecated stop/suspend/resume) and some older AWT layout questions that still appear in college vivas and MCQ tests.

The AWT questions are answered briefly with a note on what is used today. Spend most of your time on transient, synchronization and the class lock question, since those come up in real interviews. Try answering each one aloud first, then compare.

Q1. What is a resource bundle in Java?

A resource bundle is a set of key and value pairs that holds locale-specific text, so the same program can show messages in English, Hindi or French without changing code. Usually it is a family of .properties files with the same base name, such as messages.properties, messages_hi.properties and messages_fr.properties.

You load it with ResourceBundle.getBundle("messages", locale) and read text with getString("greeting"). If there is no file for the exact locale, Java falls back to a more general one and finally to the default file. Since Java 9, properties-based bundles are read as UTF-8, so you no longer need escape codes for non-English text.

Q2. What does marking a field transient do?

A transient field is skipped when the object is serialized. Its value is not written to the byte stream. When the object is deserialized, the field gets its type's default value: null for references, 0 for numbers, false for booleans. It does not become null in every case, which is a common slip.

import java.io.*;

class User implements Serializable {
    String name;
    transient String password;
    transient int loginCount;

    User(String name, String password, int loginCount) {
        this.name = name;
        this.password = password;
        this.loginCount = loginCount;
    }
}

public class TransientDemo {
    public static void main(String[] args) throws Exception {
        var bytes = new ByteArrayOutputStream();
        try (var out = new ObjectOutputStream(bytes)) {
            out.writeObject(new User("asha", "s3cret", 7));
        }
        try (var in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
            User u = (User) in.readObject();
            System.out.println(u.name + " " + u.password + " " + u.loginCount);
        }
    }
}
asha null 0

Q3. What is the Collection API?

It is the set of interfaces and classes in java.util for storing and working with groups of objects. It arrived in Java 1.2 and replaced ad hoc use of arrays, Vector and Hashtable with one consistent design. The core interfaces are Collection, List, Set, Queue, Deque and Map. Common implementations are ArrayList, LinkedList, HashSet, TreeSet, HashMap and TreeMap.

Because code is written against the interfaces, you can swap ArrayList for LinkedList without touching the callers. Later versions added generics (Java 5), streams (Java 8), factory methods like List.of (Java 9) and sequenced collections with getFirst() and reversed() (Java 21).

Q4. Is Iterator a class or an interface, and what is it for?

java.util.Iterator is an interface. Each collection returns its own implementation from iterator(). It gives you a uniform way to walk through any collection with hasNext() and next(), without knowing whether it is backed by an array, a linked list or a hash table.

It also has remove(), which is the safe way to delete the current element while looping. The enhanced for loop uses an Iterator behind the scenes for any Iterable.

Q5. What do abstract classes and interfaces have in common, and where do they differ?

Similarities: neither can be instantiated with new, both can declare abstract methods that subclasses or implementing classes must fill in, both can have static methods, and both can be used as a reference type for polymorphism.

Differences: a class extends at most one abstract class but can implement many interfaces. Abstract classes can have constructors, instance fields and protected or package-private methods. Interface methods are public unless marked private (Java 9+), and interface fields are always constants. You may read in old notes that interface calls are slower. With modern JIT compilers the difference is negligible, so do not pick one over the other for speed.

A good rule: use an interface to define what something can do, and an abstract class when several related classes should share actual code and state.

Q6. How is a transient field different from a static field during serialization?

Both are left out of the serialized bytes, but for different reasons. A static field belongs to the class, not to the object, so it is never part of an object's serialized state in the first place. After deserialization you see whatever value the class currently has in that JVM. A transient field belongs to the object, and you are explicitly asking Java to skip it, so it comes back with its default value.

Use transient for data that is sensitive (passwords, tokens), can be recomputed (a cached total), or cannot be serialized at all (a thread or a database connection). Writing transient static is legal but adds nothing.

Q7. Which AWT containers use BorderLayout by default?

Window, Frame and Dialog use BorderLayout by default. It splits the area into five regions: NORTH, SOUTH, EAST, WEST and CENTER. In Swing, the content pane of a JFrame also uses BorderLayout. Desktop UIs today are mostly built with JavaFX or Swing, and most Java jobs are server side, so treat this as viva knowledge.

Q8. Why does a thread block when it does I/O?

Reading from a disk, socket or keyboard is very slow compared to the CPU. With classic blocking I/O, a call like inputStream.read() does not return until data arrives, so the thread waits there and the OS gives the CPU to other threads in the meantime. Nothing is wasted, but that thread can do no other work.

This is why a server using one platform thread per request needs large thread pools. Java 21 virtual threads change the picture: when a virtual thread blocks on most I/O, the JVM unmounts it and the underlying carrier thread runs another virtual thread. You keep simple blocking code but can handle many more concurrent requests.

Q9. How do Observer and Observable work?

They implemented the observer pattern. A class extended java.util.Observable to become the subject, and objects implementing java.util.Observer registered with addObserver(). When the subject's state changed, it called setChanged() and then notifyObservers(), which called each observer's update() method.

Both were deprecated in Java 9 because the design was weak (Observable is a class, so you burn your one superclass, and it is not thread safe in a useful way). Today you write your own listener interface, use java.beans.PropertyChangeListener, or use a reactive library or an event bus.

Q10. What is synchronization, and why does a multithreaded program need it?

Synchronization controls how threads access shared mutable data. Without it two threads can read and write the same field at the same moment and corrupt it. A simple count++ is really read, add, write, so two threads can both read 5 and both write 6, losing one update. This is a race condition.

Synchronization gives two things: mutual exclusion (one thread at a time in the critical section) and visibility (changes made inside are seen by the next thread that takes the same lock). Tools include synchronized, ReentrantLock, volatile for visibility only, and atomic classes like AtomicInteger.

public class CounterDemo {
    private static int count = 0;

    private static synchronized void increment() {
        count++;
    }

    public static void main(String[] args) throws InterruptedException {
        Runnable task = () -> {
            for (int i = 0; i < 10_000; i++) increment();
        };
        Thread a = new Thread(task);
        Thread b = new Thread(task);
        a.start(); b.start();
        a.join(); b.join();
        System.out.println(count);
    }
}
20000

Remove synchronized and run it a few times. You will often see a number below 20000.

Q11. Can a thread lock a class rather than an object?

Yes. Every class has one Class object in its class loader, and that object has a monitor like any other. A static synchronized method locks it, and so does synchronized (MyClass.class) { ... }.

The class lock and an instance lock are separate. One thread can be inside a static synchronized method while another is inside an instance synchronized method of the same class, because they hold different locks. Interviewers like this follow-up.

Q12. What happened to Thread's stop(), suspend() and resume() methods?

All three were deprecated back in JDK 1.2 because they are unsafe. stop() kills a thread wherever it is and releases its locks, which can leave shared objects half updated. suspend() pauses a thread while it still holds its locks, which easily causes deadlock, and resume() only exists to undo suspend.

In current Java they no longer work at all: since Java 20 calling any of them throws UnsupportedOperationException, and suspend and resume have since been removed from the class. The correct way to stop a thread is cooperative: call interrupt() and have the thread check isInterrupted() or handle InterruptedException, or cancel a Future from an ExecutorService.

Q13. Is null a keyword in Java?

No. null is a literal, just like true and false are boolean literals. You still cannot use any of them as a variable name, because the language reserves them. null can be assigned to any reference type but never to a primitive, so int x = null; does not compile.

Q14. What is a component's preferred size?

It is the size a component would like to be to show its content properly, for example a button just big enough for its label plus padding. You read it with getPreferredSize(). Layout managers like FlowLayout use it when placing components, while others like BorderLayout's center region may stretch the component and ignore it. Components also have a minimum and maximum size, and the preferred size sits between them. Same AWT/Swing note as above: useful for desktop UI and vivas, rare in backend interviews.

Q15. Which method sets the layout manager of a container?

setLayout(LayoutManager), for example panel.setLayout(new GridLayout(2, 3)). Passing null switches to absolute positioning, where you place each component yourself with setBounds. In JavaFX there is no setLayout; you choose a layout pane such as VBox, HBox or GridPane instead.

Quick revision

  • ResourceBundle maps keys to locale-specific text, usually from .properties files.
  • transient fields are skipped in serialization and come back as default values (null, 0, false).
  • Iterator is an interface; use its remove() to delete while looping.
  • count++ is not atomic; synchronization gives both mutual exclusion and visibility.
  • static synchronized locks the Class object, which is separate from any instance lock.
  • stop, suspend and resume are dead; stop threads by interrupting them.

Frequently asked questions

Do companies still ask AWT layout questions?

Product and service companies hiring for backend or full stack roles rarely do. They still show up in university exams, vivas and some aptitude MCQ rounds, so learn the default layouts once and move on.

What thread questions should I prepare after this part?

Thread states, wait/notify versus sleep, volatile, deadlock with an example, ExecutorService, and virtual threads in Java 21. Be able to write the synchronized counter above from memory.

Is it fine to say "I would use JSON instead of Java serialization"?

Yes, as long as you first answer the question asked. Explain transient and serialVersionUID, then mention that most real services exchange JSON and why. That sounds like someone who has worked on actual systems.

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 1  |  Next: Part 3 →
See everything in one place: Interview Preparation Hub

Comments

Answered 0/0Correct 0