100 Highly Rated Core Java Interview Questions

It is far more vital to grasp the Java Core Fundamentals in order to succeed in any interview. This post discusses the most commonly asked and highly rated Core Java Interview Questions for both newcomers and seasoned experts.

1. Classes/Interfaces

   – Collection of objects, methods, variable declarations, and definitions. Classes are the behavior of the program.

 Interfaces :

  • Interfaces can have methods and variables 
  • Methods should be abstract; only method declarations are allowed.
  • Interfaces inform the class about what to do and don’t.
  • Interfaces are the blueprints of classes.

What is the purpose of the main() method?

  • Answer: It’s the entry point for a Java application. Signature: public static void main(String[] args):
    • public: Accessible by JVM.
    • static: No object instantiation needed.
    • args: Command-line arguments.

What Is the Difference Between Serializable and Cloneable Interfaces in Java?

Serializable :

  • Under the IO Package, Serializable Interface is located.
  • This interface’s goal is to serialize the object, which involves saving the object’s state to a file. This object can be de-serialized whenever needed.
  • It is the process of transforming an object into a serializable byte stream.
  • This technique is platform-agnostic, which means we can deserialize the object on any platform once we’ve converted it to a stream.
  • The writeObject() method in the ObjectOutputStream class writes the object to a file, whereas readObject() in the ObjectInputStream class reads the item from the file.

Cloneable Interface : 

  • This interface is part of java.lang package. 
  • The purpose of this Interface is to clone the current object
  • The Class Object uses the clone() method to close the current object. The class must implement the Clonable interface. Otherwise, the runtime exception will be thrown as CloneNotSupportedException.

What is the transient Keyword?

This keyword is to make a variable transient, this means whichever variable holds this keyword, could not be serialized.

What are all the primitive data types?

  • char
  • int
  • float
  • boolean
  • long
  • double
  • short
  • byte

What are all the Non-Primitive Data Types?

  • String
  • Arrays
  • Class
  • Interface

What is the difference between primitive data types and non-primitive data types?

Primitive Data Type :

  • The Primitive Data Type has a value.
  • Primitive data types are always started with lower caps.
  • It is predefined in Java.
  • It does not support null values.

Non-Primitive Data Type :

  • The non-primitive data type has an object, This can have methods and is used to invoke methods and other objects.
  • Non-Primitive Data Types always start with a capital letter.
  • It is not predefined; it is defined by the programmer.
  • It can have null values.

What is the Marker Interface?

  • It is a plain empty interface.
  • It has no method to it
  • The purpose of the marker interface is that the compiler should treat the class differently if the class implements the marker interface.
  • Serializable, Clonable, and Remote are the marker interfaces in Java.

What is an assertion in Java?

In Java, the assertion is used as a pre-check parameter. To ensure that the variable has the desired property, we can assign the assertion to it. If the property fails to meet the expectations, an assertion exception is thrown.

When there is a logical situation that cannot be checked directly but must be checked to avoid a collision, the assertion is used.

Syntax :

assert expr1: expr2;

Example:

int itemValue = 20;
assert itemValue >= 50: "Item Limit is not enough.";

The above statement throws an assertion error because the item value is less than 50.

Assertions are disabled by default in disabled mode. This has to be enabled by configuring at run time.

java –enableassertions <Program Name>

What is Singleton Design Pattern?

Reusability is the most common term for Singleton. It does not always create object references. It only builds the object the first time; the second time, it makes the same object as the first.

Multi-threaded applications, logging, and the cache section all use singleton objects.

  • The following actions are required for Singleton Classes: Constructor must be configured as Private; instance method must be created using Single Object Creation Setup.

Example:

private SingletonObject() { }

static SingletonObject singletonObject =  null;
//Instance Method
  public static SingletonObject getInstance( ) {
     if(singletonObject == null)
           singletonObject = new SingletonObject();

      return singletonObject;
   }

Making the constructor private ensures that the function Object() { [native code] } is hidden from view and that the only method to build the object is to use getInstance(), which always returns existing objects. This pattern is known as “Singleton.”

Difference between ofNullable() and of() in Optional Class ?

  • Optional.of(T value):
    • Purpose: Creates an Optional containing a non-null value.
    • Behavior: Throws NullPointerException if the provided value is null.
    • Use Case: When you’re certain the value isn’t null.
    • Example: Optional.of(“hello”) → Optional[“hello”].
  • Optional.ofNullable(T value):
    • Purpose: Creates an Optional that may contain a value or be empty if the value is null.
    • Behavior: Returns Optional.empty() if the value is null; otherwise, wraps the value.
    • Use Case: When the value might be null, and you want to handle it safely.
    • Example: Optional.ofNullable(null) → Optional.empty(), Optional.ofNullable(“hello”) → Optional[“hello”].

List of frequently used Optional Class methods ?

  • of(T value): Creates an Optional with a non-null value; throws NullPointerException if null.
  • ofNullable(T value): Creates an Optional; returns Optional.empty() if value is null.
  • empty(): Returns an empty Optional.
  • isPresent(): Returns true if a value exists, false if empty.
  • isEmpty() (Java 11+): Returns true if empty, false if a value exists.
  • get(): Returns the value if present; throws NoSuchElementException if empty.
  • orElse(T other): Returns the value if present; otherwise, returns other.
  • orElseGet(Supplier<? extends T> supplier): Returns the value if present; otherwise, invokes supplier to get a value.
  • orElseThrow(Supplier<? extends X> exceptionSupplier): Returns the value if present; otherwise, throws an exception from supplier.
  • ifPresent(Consumer<? super T> consumer): Executes consumer with the value if present; does nothing if empty.
  • map(Function<? super T, ? extends U> mapper): Applies mapper to the value if present, returning a new Optional; returns Optional.empty() if empty.
  • filter(Predicate<? super T> predicate): Returns Optional with the value if it matches predicate; otherwise, Optional.empty().

How does HashMap work internally?

  • HashMap uses an array of buckets. Key’s hashCode() determines the index; collisions are handled with linked lists (or trees in Java 8+ if >8 entries).
  • Operations:
    • Put: Hash key → Index → Store as Entry.
    • Get: Hash key → Index → Compare with equals().

9. What’s the difference between final, finally, and finalize()?

  • final: Locks a variable/class/method (e.g., final int x = 10; can’t change).
  • finally: Block executed after try-catch, regardless of exception (e.g., resource cleanup).
  • finalize(): Deprecated method called by GC before object cleanup (rarely used).

10. What is the difference between String, StringBuilder, and StringBuffer?

  • String: Immutable, thread-safe by default (e.g., “abc” + “d” creates new object).
  • StringBuilder: Mutable, not thread-safe, faster for single-threaded use.
  • StringBuffer: Mutable, thread-safe (synchronized), slower due to locking.

What is the difference between Comparable and Comparator?

  • Comparable: Natural ordering, implemented by the class (e.g., compareTo() in String).
  • Comparator: External ordering, separate class or lambda (e.g., Comparator.comparing(Person::getAge)).
    • Example: Collections.sort(list, new MyComparator());.

What is String Interning?

  • Definition: String interning is the process of storing only one copy of each distinct string value in a shared pool, called the String Pool (or String Intern Pool), to reduce memory usage and enable efficient comparisons.
  • Location: The String Pool resides in the Heap Memory, specifically in the String Constant Pool .
  • Purpose: Saves memory by reusing immutable String objects and Speeds up string comparisons (== checks reference equality).
  • Default Behavior: When you create a string literal (e.g., “hello”), Java automatically interns it—placing it in the String Pool if it doesn’t already exist.
  • Manual Interning: You can explicitly intern a string using the intern() method, adding it to the pool or returning the pooled instance if it’s already there.
  • Immutability: Since String is immutable, interning is safe—shared instances won’t change unexpectedly.
public class StringInterningExample1 {
    public static void main(String[] args) {
        String s1 = "hello";    // Interned in String Pool
        String s2 = "hello";    // Reuses same pooled instance

        System.out.println(s1 == s2);       // true (same reference)
        System.out.println(s1.equals(s2));  // true (same content)
    }
}

Why Serializable id is important ?

The serialVersionUID is important because it ensures object compatibility during serialization and deserialization.

When a class is serialized, Java assigns it a serialVersionUID. If the class structure changes (e.g., adding/removing fields), and the serialVersionUID doesn’t match during deserialization, it throws:

InvalidClassException: Local class incompatible

With serialVersionUID (No Issues)

class User implements Serializable {
private static final long serialVersionUID = 1L; // Explicit UID
String name;
}

Even if you add a new field later, deserialization still works because the UID remains the same.

Without serialVersionUID (Risky)

class User implements Serializable {
String name;
}

If you modify the class (e.g., add int age;), Java generates a new UID, and old serialized objects become incompatible.

What Happens If You Try to Send a Java Object Through Web Services Without Serialization ?

If you try to send a Java object over a web service (REST/SOAP/RMI) without implementing Serializable, different issues arise depending on the method of transmission.

1. REST API (Spring Boot – JSON)

Works without Serializable!

  • RESTful web services don’t require Java serialization.
  • They use JSON/XML for transmission, which doesn’t rely on Serializable.

2. SOAP Web Services (XML)

May cause errors if using Java object transmission.

  • SOAP serializes objects to XML.
  • If the object is sent as a Java object, it needs to be Serializable.
  • But if you use JAXB (Java Architecture for XML Binding), serialization is not required.

3. Java RMI (Remote Method Invocation)

Will Fail Without Serializable!

  • RMI requires serialization to send objects between JVMs.
  • If an object isn’t Serializable, RMI throws an error.
MethodNeeds Serializable?Reason
REST API (JSON/XML) NoUses JSON/XML for transmission
SOAP Web Service️ SometimesRequired if sending Java objects, not XML
Java RMIYesRequires Java object serialization

Why is SOAP Preferred for Banking Services?

SOAP (Simple Object Access Protocol) is widely used in banking, finance, and enterprise applications due to its strict security, reliability, and transaction management capabilities.

1. High Security: WS-Security

  • Banking transactions involve sensitive data (credit card info, account details).
  • SOAP supports WS-Security, which provides message encryption, authentication, and integrity.
  • It allows digital signatures and token-based authentication (e.g., SAML).

2. ACID Compliance & Transaction Safety

  • Banks require Atomicity, Consistency, Isolation, and Durability (ACID) in transactions.
  • SOAP supports two-phase commit (2PC) for handling transactions securely.
  • If a transaction fails midway, SOAP ensures it is rolled back to maintain data integrity.

4. Reliability: Built-in Message Delivery & Error Handling

  • SOAP ensures messages are delivered exactly once, even in network failures.
  • Supports retry logic, making it more reliable for financial transactions.

5. Standardization & Compliance

  • Banks must comply with strict regulatory requirements (e.g., PCI DSS, GDPR).
  • SOAP’s structured format ensures standardization across different financial institutions.
  • Supports formal contracts (WSDL), making it easier to integrate with legacy systems.

5. Firewall & Enterprise Integration

  • SOAP works seamlessly with firewalls and proxies using HTTP+SSL or WS-Security.
  • Many legacy banking systems already support SOAP, making integration easier.

Conclusion: When to Use SOAP in Banking?

  • If you need high security (WS-Security, encryption, authentication).
  • If transactions must be atomic (ACID compliance, rollback support).
  • If reliability is critical (guaranteed delivery, error handling).
  • If regulatory compliance is required (standardized message format).
  • If integrating with legacy systems (many financial institutions still use SOAP).

SOAP vs REST API: 5 Key Differences ?

FeatureSOAP (Simple Object Access Protocol)REST (Representational State Transfer)
1. ProtocolStrict protocol (follows XML-based structure)Architectural style (flexible, uses multiple formats)
2. Data FormatOnly XMLJSON, XML, HTML, Text
3. Speed & PerformanceSlower (heavy XML + strict rules)Faster (lightweight JSON)
4. UsageUsed in Enterprise Applications (e.g., Banking, Payment)Used in Web & Mobile APIs (e.g., Social Media, E-commerce)
5. SecurityWS-Security for authentication/encryptionUses OAuth, JWT, HTTPS for security

When to Use?

SOAP: Best for secure, transaction-heavy services (e.g., Banking, Finance).
REST: Best for web & mobile applications (e.g., Social Media, E-commerce).

What are all the Isolation Levels in Spring Boot ?

Isolation levels determine how transactions interact with each other. Spring Boot allows setting different isolation levels using @Transactional(isolation = Isolation.LEVEL).

Isolation LevelDescriptionPrevents
READ_UNCOMMITTEDTransactions can see uncommitted changes from other transactions.Does not prevent dirty reads.
READ_COMMITTEDTransactions see only committed data.Prevents dirty reads, but allows non-repeatable reads.
REPEATABLE_READTransactions see the same data even if updated by others.Prevents dirty & non-repeatable reads, but allows phantoms.
SERIALIZABLETransactions fully isolated (executed sequentially).Prevents all anomalies (but slowest performance).

Example: Preventing Dirty Reads (READ_COMMITTED)

@Transactional(isolation = Isolation.READ_COMMITTED)
public Account getAccountBalance(Long accountId) {
    return accountRepo.findById(accountId).orElseThrow(() -> new RuntimeException("Account not found"));
}

Ensures the account balance is never read before it’s committed.

ACID Property Implementation in Spring Boot ?

  • Atomicity: The @Transactional annotation ensures that if an exception occurs (e.g., the simulated error), all changes (debit and credit) are rolled back.
  • Consistency: The balance check enforces a business rule, and JPA/database constraints (e.g., NOT NULL) ensure data integrity.
  • Isolation: By default, Spring uses the database’s default isolation level (e.g., READ_COMMITTED in H2), preventing dirty reads.
  • Durability: Once committed, H2 (or any ACID-compliant DB) ensures changes are persisted.

@Version Annotation in Springboot ?

If multiple users update the same account, one update could override another. Optimistic locking prevents this by using a version field.

Example: Adding @Version for Optimistic Locking

import javax.persistence.*;

@Entity
public class Account {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private double balance;

    @Version // Ensures only one update at a time
    private int version;
}

If two users update the same record simultaneously, one update fails.

Implement ACID using @Transactional in Springboot ?

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BankingService {

    @Autowired
    private AccountRepository accountRepository;

    @Transactional
    public void transferMoney(Long fromAccountId, Long toAccountId, double amount) {
        // Fetch accounts
        Account fromAccount = accountRepository.findById(fromAccountId)
                .orElseThrow(() -> new RuntimeException("From account not found"));
        Account toAccount = accountRepository.findById(toAccountId)
                .orElseThrow(() -> new RuntimeException("To account not found"));

        // Check sufficient balance (Consistency)
        if (fromAccount.getBalance() < amount) {
            throw new RuntimeException("Insufficient balance");
        }

        // Perform the transfer (Atomicity)
        fromAccount.setBalance(fromAccount.getBalance() - amount);
        toAccount.setBalance(toAccount.getBalance() + amount);

        // Save changes
        accountRepository.save(fromAccount);
        accountRepository.save(toAccount);

        // Simulate an error to test rollback (Atomicity)
        if (true) { // Remove this condition to test normal flow
            throw new RuntimeException("Simulated error after transfer");
        }
    }
}

What is Write-Ahead Logging (WAL)?

Write-Ahead Logging is a standard technique used by database management systems (DBMS) to ensure that changes to data are reliably persisted and recoverable in the event of a system crash or failure. The core idea is simple: before making any permanent changes to the database (on-disk data), the intended changes are first recorded in a log file. This log is written to durable storage (e.g., disk) before the transaction is considered committed.

  • “Write-Ahead”: The log is written ahead of the actual data modification.
  • Purpose: Guarantees that even if a crash occurs mid-transaction, the database can recover to a consistent state by replaying or undoing the logged changes.

WAL is widely used in relational databases like PostgreSQL, MySQL (with InnoDB), Oracle, and even in-memory databases like H2 when configured for persistence.

Difference between Eventual Consistency and Strong Consistency?

Eventual Consistency and Strong Consistency, two fundamental concepts in distributed systems and databases, especially relevant in microservices architectures.


1. Strong Consistency

  • Definition: Strong Consistency (also called Immediate Consistency or Linearizability) ensures that every read operation returns the most recent write operation’s result, regardless of which node or replica in the system is queried. Once a write is acknowledged, all subsequent reads reflect that update immediately.
  • How It Works:
    • All nodes in a distributed system synchronize their state before acknowledging a write.
    • Reads are blocked or redirected until the latest data is fully propagated.
  • Key Characteristics:
    • Immediate Visibility: Updates are visible to all clients instantly after a commit.
    • Single Source of Truth: At any moment, all replicas agree on the current state.
    • Cost: Requires tight coordination (e.g., locking, consensus protocols like Paxos or Raft).
  • Example:
    • A bank account balance in a traditional RDBMS: If $200 is withdrawn from an account with $1000, the balance updates to $800, and every query immediately sees $800, no matter which server handles the request.
  • Implementation:
    • Achieved using synchronous replication or two-phase commit (2PC) in distributed databases like PostgreSQL or MySQL with strong ACID guarantees.

2. Eventual Consistency

  • Definition: Eventual Consistency guarantees that, given enough time and no new updates, all replicas in a distributed system will converge to the same state. However, reads may return stale or outdated data temporarily after a write until the system catches up.
  • How It Works:
    • Writes are applied to one node/replica and propagated asynchronously to others.
    • Reads might see older data until replication completes.
  • Key Characteristics:
    • Delayed Visibility: Updates propagate over time, leading to temporary inconsistency.
    • High Availability: Prioritizes availability and partition tolerance (per CAP theorem) over immediate consistency.
    • Cost: Less coordination overhead, making it more scalable.
  • Example:
    • A social media post: You post a status update, and it’s immediately visible on your device, but your friend on another continent might see it a few seconds later due to replication lag.
  • Implementation:
    • Common in NoSQL databases like Cassandra, DynamoDB, or MongoDB, using asynchronous replication or conflict resolution mechanisms (e.g., last-write-wins, vector clocks).

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *