CORE JAVA IMPORTANT QUESTIONS - Part 10

This is the last part of the Core Java set. It covers while versus do-while, the Collection interface, modifiers for local classes, static versus instance variables, the File class, rethrowing exceptions, Math.abs(), multithreading on one CPU, default constructors, finally and protected access. Four questions are about AWT layouts and painting, kept short.

A good way to use this part is as a final check. Most answers here link back to topics from earlier parts (exceptions, access modifiers, threads), so if one feels shaky, go back and revise that area before your interview rather than memorising the line here.

Q1. How does a while loop differ from a do-while loop?

A while loop checks its condition before each iteration, so if the condition is false at the start, the body never runs. A do-while loop checks after the body, so the body always runs at least once. Remember the semicolon after the closing while (...) of a do-while.

int n = 10;
while (n < 5) {
    System.out.println("while body");          // never printed
}
do {
    System.out.println("do body, n = " + n);   // printed once
} while (n < 5);

do-while fits cases like "show the menu, then ask again until the user picks exit".

Q2. How does GridBagLayout place its components?

GridBagLayout uses a grid of rows and columns, but unlike GridLayout the cells do not have to be the same size. Each component gets a GridBagConstraints object that says which cell it starts in, how many rows or columns it spans, how it fills its area, its padding and how extra space is shared (weightx, weighty). It is flexible but verbose.

Many Swing developers use MigLayout or GroupLayout (what GUI builders generate) instead, and JavaFX has GridPane.

Q3. Why does Java use layout managers instead of fixed pixel positions?

Fonts, screen resolutions, DPI scaling and native widget sizes differ across operating systems. If you place a button at exact pixel coordinates, it may be cut off or overlap on another platform. A layout manager calculates positions and sizes at runtime from each component's preferred size and the space available, so the same UI adapts to different systems and window sizes.

The same principle is behind CSS flexbox and grid on the web.

Q4. What does the Collection interface represent?

Collection is the root interface for groups of objects in java.util. On its own it models a general "bag" of elements: it does not promise any order and does not forbid duplicates. It defines the shared operations: add(), remove(), contains(), size(), isEmpty(), iterator() and, since Java 8, stream() and removeIf().

The JDK provides no direct implementation; you use its sub-interfaces List, Set and Queue. Map is not a Collection. Java 21 added SequencedCollection for collections that have a defined order, with getFirst(), getLast() and reversed().

Q5. Which modifiers are allowed on a local class?

A local class (declared inside a method body) can be final or abstract, and that is all. It cannot be public, private, protected or static, because it is only visible inside its block anyway. Since Java 17 it also cannot be sealed or non-sealed.

Java 16 did allow local records, enums and interfaces. These are implicitly static, so they cannot capture local variables from the method.

Q6. How do static variables differ from instance variables?

A static variable belongs to the class. There is one copy, created when the class is loaded, and every object shares it. An instance variable belongs to an object, so each object has its own copy, created with the object. A counter of how many objects were created is a typical static field; a student's name is an instance field.

Static methods cannot access instance variables directly, because there is no "this" object. Mutable static fields are also shared across threads, so they need care.

Q7. What is the difference between paint() and repaint()?

paint(Graphics g) contains the code that draws the component. You override it, but you do not normally call it yourself. repaint() is the method you call when the display needs updating. It does not draw immediately; it asks the painting system to schedule a redraw, which later calls paint() (in AWT, through update()) on the event thread. Several repaint() calls in a row may be merged into one.

In Swing you override paintComponent() and still call repaint().

Q8. What is the File class for?

java.io.File represents a path to a file or directory. It does not hold the file's contents. With it you can check exists(), isDirectory(), length(), list a directory, create directories, rename and delete. Reading and writing data is done with streams or readers.

Since Java 7, java.nio.file.Path and the Files class are the better choice. Files.readString(), Files.writeString(), Files.walk() and Files.delete() throw clear exceptions instead of returning false, which makes problems easier to debug.

Q9. Is it possible to rethrow an exception?

Yes. Inside a catch block you can write throw e; to pass the same exception up, for example after logging it. More often you wrap it in another exception that makes sense at your layer, passing the original as the cause so the stack trace is not lost.

static void start() {
    try {
        readConfig();   // throws IOException("config.yml not found")
    } catch (IOException e) {
        throw new IllegalStateException("Could not start app", e);
    }
}
// caller sees: Could not start app
// e.getCause().getMessage(): config.yml not found

Since Java 7, rethrowing a caught exception that is effectively final lets the compiler track its precise checked types, even if the catch parameter is declared as Exception.

Q10. Which Math method returns the absolute value of a number?

Math.abs(). It is overloaded for int, long, float and double. One edge case is worth knowing: Math.abs(Integer.MIN_VALUE) is still Integer.MIN_VALUE, because the positive value does not fit in an int. Java 15 added Math.absExact(), which throws ArithmeticException in that case instead.

Q11. How can multiple threads run on a machine with a single CPU core?

Through time-slicing. The operating system scheduler gives each runnable thread a short slice of CPU time, then switches to another, saving and restoring their state each time. The switching is fast enough that the threads appear to run at the same time. This is concurrency, not true parallelism.

It still helps on one core because many threads spend time waiting for disk, network or a database. While one waits, another can use the CPU. Java 21's virtual threads take this further by letting thousands of blocking tasks share a few OS threads.

Q12. When does the compiler add a default constructor?

Only when the class declares no constructor at all. The compiler then adds a no-argument constructor with the same access as the class, which simply calls super(). As soon as you write any constructor, even one with parameters, the default is not generated, so new MyClass() stops compiling unless you add a no-arg constructor yourself.

Frameworks like JPA need a no-arg constructor, which is why you see one added explicitly in entity classes.

Q13. When does the finally block of a try statement run?

After the try block (and any matching catch block) completes, however it completes: normally, with an exception, or through return, break or continue. A return inside try does not skip it.

static int test() {
    try {
        return 1;
    } finally {
        System.out.println("finally runs before the method returns");
    }
}
// prints the message, then test() returns 1

It does not run, or does not finish, if the JVM stops first: System.exit(), a crash, the process being killed, or an infinite loop or deadlock inside try. If finally itself throws, the rest of it is skipped and its exception replaces the original one, so avoid throwing or returning from finally.

Q14. What is the direct superclass of AWT's Container?

java.awt.Component. A Container is a Component that can hold other Components. Panel, Window and ScrollPane extend Container. In Swing, JComponent extends Container, so every Swing component can technically contain others.

Q15. Where can a protected method be accessed?

From any class in the same package, and from subclasses in other packages. There is a subtle rule for the second case: a subclass in a different package can call the protected method through its own type (or this), but not on an arbitrary instance of the parent class.

ModifierSame classSame packageSubclass, other packageEverywhere
privateyesnonono
(none)yesyesnono
protectedyesyesyesno
publicyesyesyesyes

Quick revision

  • do-while always runs its body at least once; while may run it zero times.
  • Collection is the root for List, Set and Queue; Map is separate.
  • Local classes can only be final or abstract.
  • Prefer java.nio.file.Files and Path over java.io.File in new code.
  • When rethrowing, wrap with the original exception as the cause.
  • The default constructor appears only if you write no constructor at all.

Frequently asked questions

How should I revise all ten parts before an interview?

Do not reread everything. Go through the quick revision lists of each part, mark anything you could not explain in two sentences, and spend your time only on those.

Which exception topics are asked most?

Checked versus unchecked, try-with-resources, custom exceptions, finally behaviour with return, and exception chaining. Be ready to write a small custom exception class from memory.

Is protected access asked with tricky examples?

Yes, sometimes with two packages and a subclass calling the method on a parent object. Remember the rule from Q15 and you will handle it.

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 9
See everything in one place: Interview Preparation Hub

Comments

Answered 0/0Correct 0