Top

Java Programming

71.

What are Text Blocks?

Ans:

Text Blocks, standardized in Java 15, provide a more convenient and readable way to write multi-line string literals in Java.

Before Text Blocks:

Creating a multi-line string, like a JSON or SQL query, required a lot of concatenation, new-line characters (`\n`), and escape sequences, making it ugly and hard to read.

String json = "{\n" +
              "  \"name\": \"John\",\n" +
              "  \"age\": 30\n" +
              "}";

With Text Blocks:

You can write the string in a much more natural way using three double-quote characters (`"""`) as the opening and closing delimiters.

String json = """
              {
                "name": "John",
                "age": 30
              }
              """;

The compiler automatically handles the line endings and removes incidental leading white space, making the code for embedding formatted text significantly cleaner.

72.

Explain the new `switch` expressions in Java.

Ans:

Switch Expressions, standardized in Java 14, evolve the traditional `switch` statement into a more powerful and less error-prone expression that can return a value.

Key Improvements:

  • Arrow Syntax: You can use `case L -> ...` syntax, which eliminates the need for `break` statements and prevents accidental fall-through errors.
  • Returns a Value: The entire `switch` expression can be used to assign a value to a variable.
  • Multiple Case Labels: You can group multiple constants in a single case label, separated by commas.
  • Exhaustiveness: When used as an expression, the compiler enforces that all possible cases must be handled (or a `default` case must be present), making the code safer.

Example (Traditional `switch` statement):

int numLetters;
switch (day) {
    case MONDAY:
    case FRIDAY:
    case SUNDAY:
        numLetters = 6;
        break;
    case TUESDAY:
        numLetters = 7;
        break;
    default:
        throw new IllegalStateException("Invalid day: " + day);
}

Example (Modern `switch` expression):

int numLetters = switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> 6;
    case TUESDAY                -> 7;
    default                     -> throw new IllegalStateException("Invalid day: " + day);
};

73.

What is the `Externalizable` interface?

Ans:

The Externalizable interface provides a mechanism for custom serialization. It gives a class complete control over the format and contents of its serialized form.

It extends the `Serializable` interface and declares two methods:

  • void writeExternal(ObjectOutput out) throws IOException: The class implements this method to explicitly write the state of its object to the stream.
  • void readExternal(ObjectInput in) throws IOException, ClassNotFoundException: The class implements this method to explicitly read the data from the stream and restore the state of its object.

Differences from `Serializable`:

  • Control: With `Serializable`, the process is mostly automatic. With `Externalizable`, you have full manual control over what is written and read, and in what format.
  • Constructor: During deserialization of an `Externalizable` object, its public no-argument constructor is always called first before `readExternal()` is invoked. This is not the case for `Serializable`.
  • Performance: `Externalizable` can often provide better performance because you can choose an optimized format for your data.

It is used when the default serialization mechanism is not suitable, for example, if you need to handle complex data structures or ensure compatibility across different versions of a class.

74.

What is a `PreparedStatement` and why is it preferred over a `Statement`?

Ans:

Both are interfaces in the JDBC API used to execute SQL queries. However, `PreparedStatement` offers significant advantages.

A Statement is used to execute simple, static SQL queries. The query string is concatenated with variable values, which is inefficient and insecure.

A PreparedStatement is used to execute a pre-compiled SQL query with parameter placeholders (`?`).

Why `PreparedStatement` is preferred:

  1. Prevents SQL Injection Attacks: This is the most important reason. When you use a `PreparedStatement`, user-supplied input is treated as literal values, not as executable SQL code. The database driver handles the proper escaping of characters, making it impossible for an attacker to inject malicious SQL commands. Using a simple `Statement` with string concatenation is highly vulnerable to SQL injection.
  2. Better Performance: The SQL query is pre-compiled by the database management system (DBMS) only once. If you execute the same query multiple times with different parameters, the DBMS can reuse the pre-compiled execution plan, which is much faster than compiling the query every single time.
  3. Easier to Use: It provides setter methods (e.g., `setString()`, `setInt()`) to set the values for the parameters, which is cleaner and less error-prone than string concatenation.
// Insecure Statement example
String query = "SELECT * FROM users WHERE username = '" + userInput + "'";

// Secure PreparedStatement example
String query = "SELECT * FROM users WHERE username = ?";
PreparedStatement pstmt = connection.prepareStatement(query);
pstmt.setString(1, userInput);
ResultSet rs = pstmt.executeQuery();

75.

Explain the classloader delegation model in Java.

Ans:

The classloader delegation model is a core principle of the Java classloading mechanism. It defines how a classloader finds and loads a class.

Java has a hierarchy of classloaders:

  1. Bootstrap Classloader: The root of the hierarchy. It loads the core Java API classes from `rt.jar` (e.g., `java.lang.*`). It is written in native code and is not a Java class itself.
  2. Extension Classloader: It is a child of the Bootstrap classloader and loads classes from the JDK's extension directory.
  3. Application (or System) Classloader: It is a child of the Extension classloader and loads the classes from the application's classpath.

The Delegation Model works as follows:

  1. When a classloader receives a request to load a class, it first delegates the request to its parent classloader.
  2. The parent classloader then delegates to its parent, and so on, all the way up to the Bootstrap classloader.
  3. If a classloader in the hierarchy finds the class (e.g., the Bootstrap loader finds `java.lang.String`), it loads it.
  4. If a parent classloader cannot find the class, the request delegates back down to the child classloader, which will then try to load the class from its own path.

This model ensures that:

  • Core Java classes are always loaded by the trusted Bootstrap classloader, preventing malicious code from replacing them (e.g., you can't create your own `java.lang.String`).
  • A class is loaded only once by a single classloader, avoiding class loading conflicts.

76.

What is the difference between PermGen and Metaspace?

Ans:

Both are memory areas in the JVM used to store class metadata, but Metaspace replaced PermGen in Java 8.

PermGen (Permanent Generation):

  • This was the memory area used in Java 7 and earlier to store class metadata (like the runtime representation of classes and methods), interned strings, and static variables.
  • It was part of the Java Heap and had a fixed maximum size.
  • This fixed size was a common source of problems. If an application loaded a large number of classes (e.g., during hot deployment in an application server), it could run out of PermGen space, causing an `OutOfMemoryError: PermGen space`.

Metaspace:

  • Introduced in Java 8, Metaspace is the new area for storing class metadata.
  • The key difference is that Metaspace is allocated from native memory, not the Java Heap.
  • By default, Metaspace can grow automatically, limited only by the available native memory of the operating system.
  • This largely eliminates the `OutOfMemoryError` related to class metadata, making applications more robust.
  • Interned strings were moved from PermGen into the main Java Heap in Java 7.

77.

How would you profile a Java application to find a memory leak?

Ans:

Profiling a memory leak involves using specialized tools to analyze the application's heap usage over time.

A memory leak in Java occurs when objects are no longer being used by the application, but the Garbage Collector is unable to remove them from memory because they are still being referenced. This causes the heap to grow continuously until an `OutOfMemoryError` occurs.

The general steps are:

  1. Connect a Profiling Tool: Use a tool like JVisualVM (which comes with the JDK), JProfiler, or YourKit to connect to the running Java application.
  2. Monitor Heap Usage: Observe the heap memory graph over time while the application is under load. A healthy application's heap usage should look like a sawtooth pattern (memory grows, then GC runs and it drops). If the memory usage consistently trends upwards without dropping back to a stable baseline, a leak is likely.
  3. Take Heap Dumps: A heap dump is a snapshot of all the objects in the heap at a specific moment. You should take at least two heap dumps: one at the beginning as a baseline, and another after the memory usage has grown significantly.
  4. Analyze the Heap Dumps: Load the heap dumps into an analysis tool like Eclipse MAT (Memory Analyzer Tool) or the profiler itself. These tools can:
    • Compare the two heap dumps to show which objects have grown in number.
    • Calculate the 'retained size' of objects to identify which objects are holding on to large amounts of memory.
    • Show the 'dominator tree' to find the objects that are preventing large object graphs from being garbage collected.
    • Find the reference chain (path to GC roots) that is keeping the suspected leaking objects alive.
  5. Identify and Fix the Code: Once you've identified the object type that is leaking and the reference chain holding it in memory, you can examine the source code to find the bug (e.g., a collection that is never cleared, an unclosed resource, or a listener that is never deregistered) and fix it.

Loading…
Tags: Java Programming Interview Questions and Answers || Java Programming Sort Questions and Answers || Java Programming Detailed Questions and Answers || Java Programming Tutorial