CORE JAVA IMPORTANT QUESTIONS - Part 9

Part 9 covers the System class, the eight primitive types, reflection with the Class class, what is allowed in a switch case, interface modifiers, and a group of event-handling questions from AWT. A couple of small trick questions (&&= and whether "abc" is a primitive) are in here too.

The switch question has changed the most since these questions first went around. Java 7, 14 and 21 each added something to it, so read that answer carefully and try the snippet. For the AWT questions, focus on the listener idea rather than the class names.

Q1. What is java.lang.System used for?

System is a final utility class that connects your program to its environment. It gives you the standard streams (System.in, System.out, System.err), environment variables through getenv(), system properties through getProperty(), the clock through currentTimeMillis() and nanoTime(), fast array copying with arraycopy(), and exit() to stop the JVM.

You never create a System object; everything on it is static. For measuring elapsed time, use nanoTime(), not currentTimeMillis(), because the wall clock can jump.

Q2. In AWT, how do you make a TextComponent read-only?

Call setEditable(false). The user can still select and copy the text, but cannot change it. isEditable() tells you the current setting. Swing's JTextComponent has the same method.

This is mostly an exam question now, since new desktop UIs are built with Swing or JavaFX.

Q3. How does CardLayout arrange its components?

CardLayout stacks components on top of each other like a deck of cards, and only one is visible at a time. You switch between them with methods like next(), previous(), first(), last() or show(container, name). It was the usual way to build wizards and tabbed-style screens in AWT and Swing.

In Swing, JTabbedPane often does the job with less code.

Q4. Does Java have a &&= operator?

No. Writing ok &&= false is a syntax error. Java does have &= and |=, and they work on booleans, but they are not short-circuit: the right-hand side is always evaluated, even when the result is already decided.

static boolean check(String name) {
    System.out.println("checking " + name);
    return true;
}

boolean ok = false;
ok &= check("disk");   // prints "checking disk" even though ok is already false
System.out.println(ok); // false

If you need short-circuiting, write it out: ok = ok && check("disk");.

Q5. List Java's eight primitive types.

TypeSizeHolds
byte8 bits-128 to 127
short16 bits-32,768 to 32,767
int32 bitsabout plus or minus 2.1 billion
long64 bitsvery large whole numbers
float32 bitssingle-precision decimal
double64 bitsdouble-precision decimal
char16 bitsa UTF-16 code unit, 0 to 65,535
booleannot fixed by the spectrue or false

Each has a wrapper class (Byte, Short, Integer, Long, Float, Double, Character, Boolean), and autoboxing converts between them.

Q6. Which class lets you inspect the structure of an object at runtime?

java.lang.Class. Every object can give you its Class through getClass(), and you can also write String.class directly. From a Class you can read the name, superclass, interfaces, fields, methods, constructors and annotations. This is the entry point to reflection, which frameworks like Spring, Hibernate and JUnit depend on.

Since Java 9, strong encapsulation of modules means reflection into JDK internals is blocked unless a package is opened, so you may see "InaccessibleObjectException" in older libraries.

Q7. How are clipping and repainting connected in AWT?

When part of a window needs redrawing (because it was uncovered, resized or repaint() was called on a region), the painting system sets the clip of the Graphics object to just that damaged area before calling paint(). Your code can draw the whole component, but only pixels inside the clip are actually changed.

That makes repainting cheaper. For better performance, you can read g.getClipBounds() and skip drawing anything outside it.

Q8. Is "abc" a primitive value?

No. "abc" is a string literal, and it evaluates to a reference to a String object. String is a class, even though Java gives it special syntax (literals and the + operator). Literals with the same content are stored once in the string pool and shared, which is safe because Strings are immutable.

A quick check: "abc".getClass().getName() prints java.lang.String.

Q9. How are an event-listener interface and an adapter class related?

A listener interface declares the callback methods for one kind of event. For example, MouseListener has five methods. An adapter class, such as MouseAdapter, implements that interface with empty method bodies. You extend the adapter and override only the method you care about, instead of writing four empty methods yourself.

Since Java 8, single-method listeners like ActionListener are usually written as lambdas, so adapters matter mainly for multi-method listeners.

Q10. What is allowed as a case label in a switch?

In a classic switch on a value, each case label must be a compile-time constant, all labels must be distinct, and their types must be assignable to the selector's type. The selector can be char, byte, short, int, their wrappers, an enum, or (since Java 7) a String. long, float, double and boolean are not allowed as selectors.

Modern Java adds more. Java 14 made arrow labels and switch expressions standard, with several constants per case and no fall-through. Java 21 added pattern matching, so a case can match a type, and a switch over a sealed interface does not need a default.

sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}

static double area(Shape s) {
    return switch (s) {
        case Circle c -> Math.PI * c.r() * c.r();
        case Square q -> q.side() * q.side();
    };
}

String type = switch ("SAT") {
    case "SAT", "SUN" -> "weekend";
    default -> "weekday";
};

Q11. Which modifiers can you put on an interface declaration?

A top-level interface can be public or package-private (no modifier). It is always abstract, so writing abstract is allowed but adds nothing. Since Java 17 it can also be sealed or non-sealed. strictfp is still accepted, but since Java 17 it has no effect and javac warns about it.

A nested interface can additionally be private, protected or static (it is implicitly static anyway). An interface can never be final, because its whole purpose is to be implemented.

Q12. Is a class considered a subclass of itself?

This one depends on what is meant. By the Java Language Specification, no: the subclass relationship is strict, and a class that tried to extend itself would fail with "cyclic inheritance". But in type compatibility checks a class is treated as compatible with itself. String.class.isAssignableFrom(String.class) returns true, and "abc" instanceof String is true.

In an interview, give both halves. It shows you understand the difference between the inheritance relationship and type assignability.

Q13. What is the top class of the event hierarchy in the delegation model?

java.util.EventObject. It holds the source of the event, returned by getSource(). AWT events extend it through java.awt.AWTEvent, and many non-UI libraries also build their own events on EventObject.

Q14. Which event is fired when a user clicks a button?

An ActionEvent. You handle it by registering an ActionListener with addActionListener() and implementing actionPerformed(). A click also produces lower-level MouseEvents, but ActionEvent is the one you normally listen for, because it also fires when the button is triggered from the keyboard.

In Swing with a lambda: button.addActionListener(e -> save());.

Q15. How can a component handle its own events?

The component class implements the listener interface itself and registers itself as the listener, for example addActionListener(this) inside its constructor. There is also the older approach of calling enableEvents() and overriding processEvent() or a method like processActionEvent().

Both work, but separate listeners or lambdas keep the code easier to test and change, which is why you rarely see self-listening components in modern code.

Quick revision

  • System gives static access to streams, properties, environment, time and exit().
  • Eight primitives: byte, short, int, long, float, double, char, boolean.
  • There is no &&=; &= on booleans exists but does not short-circuit.
  • switch accepts String since Java 7, arrow labels since 14, and type patterns since 21.
  • Interfaces are implicitly abstract, can be sealed since Java 17, and are never final.
  • A button click produces an ActionEvent handled by an ActionListener.

Frequently asked questions

Which new switch features should I know for interviews?

Know switch expressions with arrow labels, multiple constants in one case, yield, and pattern matching with sealed types. Be ready to explain why the arrow form avoids fall-through bugs.

How much reflection do I need to know?

Enough to explain what it is, name getClass() and Class.forName(), and say how frameworks like Spring use it to create beans and read annotations. Writing heavy reflection code by hand is rarely asked.

Are primitive sizes asked even for experienced candidates?

Often, as a warm-up. Also be ready for the follow-up on why 0.1 + 0.2 is not exactly 0.3 with double, and when to use BigDecimal 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 8  |  Next: Part 10 →
See everything in one place: Interview Preparation Hub

Comments

Answered 0/0Correct 0