Java Keywords


Java Keywords Interview with follow-up questions

1. What is the purpose of the 'final' keyword in Java?

final marks something as unchangeable, with a meaning that depends on where it's applied:

  • Variable — can be assigned only once; it becomes a constant reference. For a primitive, the value can't change; for an object, the reference can't be reassigned (but the object's internal state can still mutate).
  • Method — cannot be overridden by subclasses.
  • Class — cannot be subclassed (e.g. String, Integer are final).
  • Parameter — can't be reassigned inside the method.
final List names = new ArrayList<>();
names.add("Ada");      // OK — object state changes
// names = new ArrayList<>();   // compile error — can't reassign

The gotchas interviewers love: final ≠ immutable — a final reference to a mutable object still lets you mutate that object (true immutability needs final fields and no mutators, like a record or defensive copies). Also, final is required for variables captured by a lambda or anonymous class (they must be final or "effectively final").

A current note: for restricting a class hierarchy more precisely than "no subclasses at all," modern Java offers sealed classes/interfaces (Java 17+), which permit only an explicit list of subtypes — a more expressive alternative to final when you want a closed set of implementations.

↑ Back to top

Follow-up 1

What is a final class and how does it differ from a regular class?

A final class is a class that cannot be subclassed. When a class is declared as final, it means that it cannot be extended by any other class. This is useful when you want to prevent any further modification or extension of a class. A regular class, on the other hand, can be subclassed unless it is explicitly marked as final.

Follow-up 2

Can you modify a final variable?

No, a final variable cannot be modified once it has been assigned a value. Any attempt to modify a final variable will result in a compilation error.

Follow-up 3

What is a final method?

A final method is a method that cannot be overridden by subclasses. Once a method is declared as final in a superclass, it cannot be modified or overridden in any subclass. This is useful when you want to ensure that a method's implementation remains the same across all subclasses.

2. What does the 'static' keyword signify in Java?

static means a member belongs to the class itself, not to any instance — there's one copy shared by all objects, accessible via the class name without creating an object.

  • Static variable (class field) — one shared value across all instances (e.g. a counter, a constant static final).
  • Static method — called on the class (Math.max(...)); can't use this or access instance members directly.
  • Static block — runs once when the class is loaded, for static initialization.
  • Static nested class — a nested class that doesn't hold a reference to an outer instance.
class Counter {
    static int count = 0;            // shared
    Counter() { count++; }
    static int total() { return count; }   // Counter.total()
}

Gotchas interviewers probe: a static method can't be overridden (it's hidden, resolved by reference type at compile time, not polymorphic); static members are initialized when the class is loaded; and shared mutable static state is a thread-safety hazard (and complicates testing). Best practice is to reserve static for constants (static final), pure utility methods, and factory methods — not as a substitute for proper dependency injection of shared state.

↑ Back to top

Follow-up 1

Can you access a static method using an object?

Yes, a static method can be accessed using an object of the class. However, it is recommended to access static methods using the class name itself, as accessing them through an object can be misleading and may give the impression that the method is non-static.

Follow-up 2

What is a static block and when is it used?

A static block in Java is a block of code that is executed only once when the class is loaded into memory. It is used to initialize the static variables of the class or to perform any other one-time initialization tasks. The static block is executed before the constructor of the class.

Follow-up 3

What is a static class in Java?

In Java, a static class is a nested class that is defined with the 'static' keyword. A static class cannot access non-static members of the outer class, but it can be instantiated without creating an instance of the outer class. Static classes are commonly used for grouping related utility methods or for creating helper classes that do not require an instance of the enclosing class.

3. How does the 'native' keyword function in Java?

native marks a method whose implementation is written in another language (typically C/C++) rather than Java. You declare the signature with native and no body; the actual code lives in a compiled native library, linked at runtime via JNI (Java Native Interface).

public class Sensor {
    static { System.loadLibrary("sensor"); }   // load the native lib
    public native double readValue();           // implemented in C/C++
}

It's used to access platform-specific features, reuse existing native libraries, or do performance-critical low-level work. Much of the JDK itself uses native methods (e.g. parts of System, Thread, I/O).

The 2026 detail that signals current knowledge: JNI is verbose, fragile, and unsafe, so modern Java provides the Foreign Function & Memory (FFM) API (java.lang.foreign, finalized in Java 22, JEP 454) as the recommended replacement. FFM lets you call native code and access off-heap memory directly from Java — type-safe, no C glue code, no native boilerplate. So while native/JNI still exists and underpins legacy interop, a strong answer notes that new native interop should use the FFM API, not hand-written JNI.

↑ Back to top

Follow-up 1

Can you provide an example of a native method?

Sure! Here's an example of a native method declaration in Java:

public class NativeExample {
    public native void nativeMethod();
}

In this example, the nativeMethod() is declared as native, indicating that its implementation will be provided in a language other than Java.

Follow-up 2

Why would you use native methods in Java?

There are several reasons why you might use native methods in Java:

  1. Accessing platform-specific features: Native methods allow you to access features that are specific to the underlying platform or operating system, which may not be available through standard Java APIs.

  2. Interfacing with existing libraries: Native methods can be used to interface with existing libraries written in other languages, such as C or C++, allowing you to leverage the functionality provided by those libraries.

  3. Performance optimization: In some cases, implementing certain operations in a lower-level language can provide performance benefits compared to implementing them in Java.

It's important to note that the use of native methods should be limited to cases where it is necessary and justified, as it introduces additional complexity and potential for errors.

Follow-up 3

What are the advantages and disadvantages of using native methods?

Advantages of using native methods in Java:

  • Access to platform-specific features and libraries
  • Potential for performance optimization

Disadvantages of using native methods in Java:

  • Increased complexity: Native methods introduce additional complexity to the codebase, as they require linking Java code with code written in other languages.
  • Platform dependency: Native methods are platform-dependent, meaning that the native code needs to be compiled separately for each platform or operating system.
  • Potential for bugs and security vulnerabilities: Native code is typically written in lower-level languages, which can introduce bugs and security vulnerabilities if not handled carefully.

It's important to carefully consider the trade-offs before deciding to use native methods in Java.

4. What is the role of the 'abstract' keyword in Java?

abstract declares something incomplete, meant to be extended:

  • Abstract class — cannot be instantiated directly; it's a base for subclasses. It can mix abstract methods (no body, subclasses must implement) with concrete methods, fields, and constructors.
  • Abstract method — a method signature with no implementation; any concrete subclass must override it.
abstract class Shape {
    abstract double area();              // must be implemented by subclasses
    void describe() { System.out.println("area=" + area()); }  // shared logic
}
class Circle extends Shape {
    double r;
    double area() { return Math.PI * r * r; }
}

The distinction interviewers always probe — abstract class vs interface: use an abstract class when subtypes share state/fields and common implementation and form an "is-a" hierarchy (single inheritance); use an interface for a capability/contract that unrelated types can implement (multiple inheritance of type). The line has blurred since interfaces gained default/static methods (Java 8) and private methods (Java 9), so interfaces can now carry behavior too — but only abstract classes hold instance state and constructors.

A current note: to constrain which classes may extend an abstract base, combine it with sealed (Java 17+) for an exhaustive, pattern-match-friendly hierarchy.

↑ Back to top

Follow-up 1

Can you instantiate an abstract class?

No, you cannot instantiate an abstract class in Java. Since an abstract class is incomplete and contains one or more abstract methods, it cannot be instantiated directly. However, you can create objects of concrete subclasses that extend the abstract class.

Follow-up 2

What is an abstract method?

An abstract method is a method that is declared without an implementation in an abstract class. It is meant to be overridden by the subclasses. Subclasses of an abstract class must provide an implementation for all the abstract methods declared in the abstract class. Abstract methods are used to define a common interface for all the subclasses, while allowing each subclass to provide its own implementation.

Follow-up 3

Can an abstract class have a constructor?

Yes, an abstract class can have a constructor in Java. The constructor of an abstract class is called when an object of a concrete subclass is created. The constructor of the abstract class is responsible for initializing the common state of the subclass. However, you cannot directly instantiate an abstract class, so the constructor of the abstract class is typically called implicitly by the constructor of the concrete subclass.

5. What does the 'volatile' keyword do in Java?

volatile is a lightweight thread-safety tool that addresses visibility and ordering for a shared variable. Declaring a field volatile guarantees:

  • Visibility — reads/writes go to/from main memory, so a write by one thread is immediately visible to others (no stale cached copies).
  • Ordering — it establishes a happens-before relationship and prevents the compiler/CPU from reordering around it.
private volatile boolean running = true;   // safe flag across threads
public void stop() { running = false; }    // other threads see it promptly

The crucial limitation interviewers want: volatile does NOT provide atomicity for compound actions. count++ is read-modify-write — volatile alone won't make it thread-safe; two threads can still interleave and lose updates. For atomic counters use AtomicInteger/AtomicLong (or synchronized); for mutual exclusion of multi-step operations use synchronized or a Lock.

So the rule: use volatile for simple flags/state signals and the safe publication of a single value (e.g. a one-time-set reference, the classic double-checked-locking singleton), and use locks/atomics when you need compound atomic updates. Mentioning that distinction — visibility vs atomicity — is exactly what separates a correct answer from a hand-wave.

↑ Back to top

Follow-up 1

When should you use the volatile keyword?

You should use the 'volatile' keyword in Java when a variable is shared between multiple threads and you want to ensure that changes made by one thread are visible to all other threads. It is commonly used for flags or status variables that are accessed by multiple threads. By using the 'volatile' keyword, you can avoid potential visibility and ordering issues that can occur when multiple threads access the same variable.

Follow-up 2

Can you provide an example of the volatile keyword being used?

Sure! Here's an example of using the 'volatile' keyword in Java:

public class VolatileExample {
    private volatile boolean flag = false;

    public void setFlag(boolean value) {
        flag = value;
    }

    public void printFlag() {
        System.out.println(flag);
    }
}

In this example, the 'flag' variable is declared as volatile. This ensures that any changes made to the 'flag' variable by one thread will be immediately visible to all other threads. Without the 'volatile' keyword, there is no guarantee that changes made by one thread will be visible to other threads.

Follow-up 3

What is the difference between a volatile and a non-volatile variable?

The main difference between a volatile and a non-volatile variable in Java is how their values are accessed and stored by threads. When a variable is declared as volatile, its value is always read from and written to the main memory, ensuring visibility across all threads. On the other hand, non-volatile variables are typically stored in each thread's cache, which can lead to visibility and ordering issues when multiple threads access the same variable. Additionally, the use of the 'volatile' keyword also prevents certain compiler optimizations that can affect the ordering of operations on the variable.

Live mock interview

Mock interview: Java Keywords

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.