← Back to quizzesFree quiz

Core Java Fundamentals

Welcome to this comprehensive course on Core Java Fundamentals. Whether you are preparing for a certification exam, a technical interview, or simply want to solidify your Java knowledge,…

10 questions~5 min
Core Java Fundamentals — Qwi
0 / 10
Score: 0%
1

Which keyword is used to refer to the current object's member variables when they are shadowed by parameters?

2

In Java, which of the following statements about method overriding is correct?

3

A Java program creates a Thread by extending the Thread class. Which of the following statements about its start() method is true?

4

Which of the following collections maintains insertion order and allows duplicate elements?

5

When implementing a custom exception class, which of the following is the most appropriate superclass to extend?

6

In the AWT/Swing event delegation model, which component typically implements the Listener interface to handle an event?

7

Which of the following statements about Java's static methods is FALSE?

8

Consider the following code snippet: ```java int[] arr = new int[5]; System.out.println(arr[5]); ``` What type of exception will be thrown at runtime?

9

Which of the following best describes the purpose of the 'final' keyword when applied to a method?

10

In Java Swing, which container is typically used as the top-level window for a standalone application?

Core Java Fundamentals: Mastering Essential Concepts

Welcome to this comprehensive course on Core Java Fundamentals. Whether you are preparing for a certification exam, a technical interview, or simply want to solidify your Java knowledge, this module covers the most frequently tested concepts in a clear, SEO‑friendly format. Each section expands on a quiz question, explains the underlying principle, and provides practical examples you can run in your IDE.

1. Understanding the this Keyword

One of the first hurdles for new Java developers is learning how to differentiate between instance variables and method parameters that share the same name. The keyword this is used to refer to the current object's members when they are shadowed.

  • Syntax: this.variableName
  • Typical use case: In constructors or setters where a parameter name matches a field name.

Example:

public class Person {
    private String name;
    public Person(String name) {
        // "name" refers to the parameter, "this.name" refers to the field
        this.name = name;
    }
}

Using this improves readability and prevents accidental assignment to the wrong variable.

2. Method Overriding Rules

Method overriding enables polymorphism, allowing a subclass to provide a specific implementation of a method declared in its superclass. Several rules govern valid overrides:

  • The overriding method cannot have a more restrictive access modifier than the method it overrides. For instance, a protected method in a superclass cannot be overridden as private in a subclass.
  • The return type must be the same or a covariant type (a subclass of the original return type).
  • Checked exceptions thrown by the overriding method must be the same or subclasses of those declared by the original method.
  • Static methods are not subject to overriding; they are hidden instead.

Correct example:

class Animal {
    public void speak() throws IOException { /* ... */ }
}
class Dog extends Animal {
    @Override
    public void speak() throws FileNotFoundException { /* ... */ }
    // Access modifier stays public – not more restrictive
}

Attempting to narrow the access level (e.g., from public to protected) will cause a compile‑time error.

3. Thread Lifecycle: The Role of start()

Creating a thread by extending java.lang.Thread is a classic approach. The crucial method that transitions a thread from the new state to the runnable state is start().

  • Calling start() spawns a new call stack and invokes the run() method on that new thread.
  • Directly invoking run() executes the code on the current thread, defeating concurrency.
  • Each Thread instance can be started only once; subsequent calls throw IllegalThreadStateException.

Example:

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Running in: " + Thread.currentThread().getName());
    }
}
public class Demo {
    public static void main(String[] args) {
        MyThread t = new MyThread();
        t.start(); // Correct – runs in a new thread
    }
}

4. Collections that Preserve Insertion Order

Java’s Collections Framework offers many implementations, each with distinct characteristics. When you need a list that maintains the order in which elements were added and also permits duplicates, the ArrayList is the go‑to choice.

  • ArrayList: Backed by a dynamically resizing array, provides O(1) random access, maintains insertion order, and allows duplicate entries.
  • LinkedHashSet: Maintains insertion order but does not allow duplicates.
  • TreeMap: Orders entries based on keys (natural ordering or comparator) and does not preserve insertion order.
  • HashSet: No ordering guarantee and disallows duplicates.

Sample usage:

List list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Apple"); // duplicate allowed
System.out.println(list); // [Apple, Banana, Apple]

5. Crafting Custom Exceptions

When your application needs to signal an error condition that is not covered by Java’s built‑in exceptions, you create a custom exception class. The most appropriate superclass to extend is Exception, which makes your new type a checked exception.

  • Extending Exception forces callers to handle or declare the exception, promoting robust error handling.
  • If you want an unchecked exception, extend RuntimeException instead.
  • Never extend Error unless you are defining a serious system‑level problem.

Example of a custom checked exception:

public class InsufficientFundsException extends Exception {
    public InsufficientFundsException(String message) {
        super(message);
    }
}

6. Event Delegation in AWT/Swing

Graphical user interfaces in Java rely on the event‑delegation model. The pattern separates the event source (e.g., a button) from the object that handles the event (the listener). The source registers a listener object that implements the appropriate Listener interface.

  • Common listeners: ActionListener, MouseListener, KeyListener.
  • Registration syntax: button.addActionListener(myListener);
  • The listener’s actionPerformed (or equivalent) method is invoked when the event occurs.

Example:

JButton btn = new JButton("Click Me");
btn.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Button clicked!");
    }
});

7. Static Methods: What They Can and Cannot Do

Static methods belong to the class itself, not to any particular instance. This design leads to several important characteristics:

  • They can be called directly using the class name: Math.max(5, 10).
  • Static methods cannot access instance (non‑static) fields or methods without an explicit object reference.
  • They are not subject to polymorphic overriding. Declaring a static method with the same signature in a subclass hides the superclass method rather than overriding it.

Because static methods cannot be overridden, the statement "Static methods can be overridden in subclasses" is FALSE.

8. Runtime Exceptions: Array Index Errors

Java performs bounds checking on array accesses. Attempting to read or write an index outside the valid range triggers an ArrayIndexOutOfBoundsException, a subclass of RuntimeException. This exception is unchecked, meaning the compiler does not require explicit handling.

int[] arr = new int[5];
System.out.println(arr[5]); // throws ArrayIndexOutOfBoundsException

Best practices to avoid this error include:

  • Always use arr.length when iterating.
  • Consider using enhanced for‑loops (for (int value : arr) { … }) which hide the index entirely.

9. Putting It All Together: Mini‑Project

To reinforce the concepts, build a small console application that:

  1. Defines a BankAccount class with private fields balance and owner. Use this in the constructor.
  2. Implements a custom checked exception InsufficientFundsException (see section 5).
  3. Provides a withdraw method that throws the custom exception when the balance is too low.
  4. Creates a separate BankThread class extending Thread. Its run method attempts to withdraw money and prints the result. Start the thread using start().
  5. Uses an ArrayList to store multiple BankThread objects, preserving the order they were added.

Running the program will demonstrate proper use of this, custom exceptions, thread start semantics, and collection ordering.

10. Quick Review Checklist

  • this – reference current object’s members.
  • Method overriding – cannot narrow access, can’t change static/instance nature, respects covariant returns.
  • Thread.start() – launches a new thread; run() runs in current thread.
  • Insertion‑order collection with duplicates – ArrayList.
  • Custom exception base class – extend Exception for checked, RuntimeException for unchecked.
  • Event delegation – source registers a listener implementing the appropriate interface.
  • Static methods – cannot be overridden; they belong to the class.
  • Array index out‑of‑bounds – throws ArrayIndexOutOfBoundsException.

By mastering these core concepts, you’ll be well‑prepared for Java interviews, certification exams, and real‑world development tasks. Keep practicing, experiment with the code snippets, and refer back to this guide whenever you need a quick refresher.