Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
Chaturmind
← Java Interview Prep: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 2–5 YearsRevise the Fresher Tier
✓ FreeIntermediate· 43 min read

Revise: Core Java Fundamentals (Fresher Tier)

Every fresher-level Core Java question — JVM, OOP, strings, keywords, exceptions, serialization — as a one-line answer with a link to the full answer.

Published September 25, 2026


How to use this revision

This page condenses every question from the Fresher to 2 Years course in these areas into a single line: the question, linked to its full answer, and the one-sentence answer you should be able to give instantly. Read down the list and answer each question aloud before reading the line. Wherever you hesitate, follow the link and revise the full answer — interviewers at your level expect these basics to be fluent, and they often open with them before going deeper.

Java Basics, JVM & Memory

JDK, JRE, JVM & the main Method — Interview Questions — open the lesson

  • What is Java? — Java is a high-level, class-based, object-oriented programming language. Its source code compiles to platform-neutral bytecode, which runs on any machine that has a Java Virtual Machine.
  • What are the main features of Java? — Platform independence, object orientation, automatic memory management, strong type safety and security, built-in multithreading, and a rich standard library.
  • What is the JVM, and why is it important? — The Java Virtual Machine is the runtime engine that loads, verifies and executes Java bytecode. It's what makes Java platform independent: the bytecode is the same everywhere, and each operating system gets its own JVM implementation.
  • What is the difference between JDK, JRE and JVM? — The JVM runs bytecode. The JRE is the JVM plus the standard class libraries, which is everything needed to run Java programs.
  • What are the key components of the JVM architecture? — Three main parts: the class loader subsystem, the runtime data areas, and the execution engine.
  • Can a Java application run without a JRE installed? — It always needs a Java runtime, but that runtime doesn't have to be installed system-wide. You can bundle a runtime with the application.
  • Is it possible to have a JDK installed without a JRE? — No. Every JDK includes a full Java runtime, because the development tools themselves (javac, for example) are Java programs that need it.
  • Explain public static void main(String[] args). — It's the entry point the JVM looks for when you launch a class. Each keyword has a reason — public class Greeter { public static void main(String[] args) {
  • What happens if main is not declared static? — Up to Java 20, the class compiles, but launching it fails with the error "Main method is not static in class X, please define the main method as: public static void main(String[] args)".
  • Can we override the main method? — Not in the true sense, because static methods aren't overridden. A subclass can declare its own static main, but that hides the parent's method; it doesn't override it.
  • Can we overload the main method? — Yes. main is an ordinary static method, so you can declare other main methods with different parameter lists.
  • Will the JVM execute an overloaded main method? — No. The launcher calls only the entry-point signature, main(String[] args). The overloads run only if your code calls them.
  • Can we print something to the console without a main method? — Not in modern Java. Up to Java 6, you could print from a static initialiser block, which ran when the class loaded, before the launcher complained about the missing main.

JVM Memory & Garbage Collection — Interview Questions — open the lesson

  • What memory areas does the JVM have? — The heap (objects), the method area / Metaspace (class metadata), and, per thread, a Java stack, a program counter register and a native method stack.
  • Which is faster, stack or heap, and why? — The stack is cheaper. Allocation and deallocation are just moving the stack pointer, frames are freed automatically when a method returns, and the data is thread-private and usually hot in the CPU cache.
  • What is garbage collection in Java, and how does it work? — Garbage collection is the JVM's automatic memory management. It finds objects that are no longer reachable from any GC root and reclaims their memory, so you never free memory manually.
  • What is the role of finalize() in garbage collection? — finalize() was a hook the GC could call before reclaiming an object, meant for releasing resources. It is deprecated (since Java 9, and marked for removal in Java 18), and you should never rely on it.
  • Which algorithms and collectors does the JVM use? — The core algorithms are mark-sweep, mark-compact and copying (used for the young generation). The HotSpot collectors combine them: Serial, Parallel, G1 (the default since Java 9), and the low-pause ZGC and Shenandoah.
  • How can memory leaks happen in Java if there's automatic garbage collection? — The GC only frees unreachable objects. A leak happens when objects you no longer need stay reachable, so they're never collected and memory keeps growing.
  • What are weak references and soft references? — They're references that don't stop an object from being collected. - A weak reference is cleared at the next GC once no strong references remain. - A soft reference is kept until the JVM is running low on memory.
  • What is Java Flight Recorder (JFR)? — JFR is a profiling and event-recording framework built into the JVM. It captures GC pauses, allocations, lock contention, I/O, CPU samples and exceptions with very low overhead (typically around 1%), so it's safe to run in production.
  • What is the difference between the Young Generation and the Old Generation? — The Young Generation is where new objects are allocated. It's collected often, with fast minor GCs. The Old (tenured) Generation holds objects that have survived several young collections.

Data Types, Wrapper Classes & Equality — Interview Questions — open the lesson

  • Is Java a 100% object-oriented language? — No. Java has eight primitive types (byte, short, int, long, float, double, char, boolean) that are not objects.
  • What are the advantages of Java being only partially object-oriented? — Performance and simplicity. Primitives are stored directly (on the stack, or inline inside objects and arrays), with no object header and no garbage-collection cost.
  • Why is object-oriented programming used in enterprise projects? — Large systems need to be divided among many developers and to keep changing for years. OOP helps by modelling the domain as objects with clear responsibilities, hiding internal details behind interfaces, and allowing reuse and extension without rewriting existing code.
  • What is the difference between primitive and non-primitive data types? — Primitives hold the value itself. They have a fixed size, can't be null, and have no methods. Non-primitive (reference) types hold a reference to an object on the heap.
  • Can a primitive be null? — No. A primitive always holds a value. Fields get a default (0, false, …), and local variables must be assigned before use, or the code won't compile.
  • Does Java have pointers? — Not in the C/C++ sense. Java has references, which point to objects, but you can't do pointer arithmetic, take the address of a variable, or cast an integer to a reference.
  • What is the difference between == and .equals()? — - For primitives, == compares values. - For objects, == compares references (is it the same object?), while .equals() compares logical content, as defined by the class.
  • What are wrapper classes? — Classes that wrap a primitive in an object: Byte, Short, Integer, Long, Float, Double, Character and Boolean in java.lang.
  • Why do we need wrapper classes? Why must collections use them? — Many Java APIs work only with objects. Generics and collections (List<Integer>, Map<String, Long>) can't hold primitives, because type parameters must be reference types.
  • What are autoboxing and unboxing? — Autoboxing is the compiler automatically converting a primitive to its wrapper (int → Integer). Unboxing is the reverse.
  • Where can autoboxing produce unexpected results? — Comparing wrappers with ==. Integer.valueOf caches the values −128 to 127. Inside that range, equal values share one object, so == happens to return true.
  • When can autoboxing or unboxing cause a NullPointerException? — Whenever a null wrapper is unboxed, because the compiler calls .intValue() on null.

Object-Oriented Programming

Classes, Objects, Packages & Access Modifiers — Interview Questions — open the lesson

  • Explain object-oriented programming in Java. — OOP organises a program around objects, which bundle data (fields) with the behaviour that operates on it (methods).
  • What are classes and objects? — A class is a blueprint that defines state (fields) and behaviour (methods). An object is a concrete instance of that class, created at runtime with its own copy of the instance fields.
  • What are the different ways to create an object in Java? — 1. The new keyword. 2. Reflection, with Constructor.newInstance(). 3. clone(). 4. Deserialization. 5. Factory or builder methods, which use one of the above internally.
  • Can a class have no fields or methods? — Yes. An empty class is legal: class Marker {}. It still inherits everything from Object (toString, equals, hashCode, …), and you can create instances of it.
  • What methods does the Object class provide? — equals(), hashCode(), toString(), getClass(), clone(), wait(), notify(), notifyAll(), and the deprecated finalize().
  • What is a package in Java? — A package is a namespace that groups related classes and interfaces, such as java.util or com.shop.orders.
  • Why do we use packages? — To organise code, avoid naming conflicts, and control access.
  • What are the access modifiers in Java? — Four levels, from most to least open: public, protected, default (package-private, meaning no keyword), and private.
  • When would you use each access modifier? And why use getters and setters instead of public fields? — Start with the most restrictive level that works: - private for fields and internal helpers. - package-private for classes that only collaborate inside one module. - protected for extension points meant for subclasses. - public only for the API that other code is meant…
  • Can a top-level class be private or protected? — No. A top-level class can only be public or package-private. private and protected only make sense relative to an enclosing class, so they're allowed on nested classes.

Inheritance, Composition, this & super — Interview Questions — open the lesson

  • What is inheritance in Java? — Inheritance lets a class (the subclass) acquire the fields and methods of another class (the superclass) using extends.
  • What is the purpose of inheritance? — Code reuse, and above all substitutability: a Car can be used anywhere a Vehicle is expected. That's what makes polymorphism possible.
  • Can a class extend itself? — No. class A extends A {} is a compile error ("cyclic inheritance involving A"). The same applies to longer cycles, such as A extends B with B extends A.
  • Why doesn't Java support multiple inheritance of classes? — To avoid the diamond problem. If C extended both A and B, and both defined greet(), it would be ambiguous which one C inherits.
  • What's the difference between inheritance and composition? What does "composition over inheritance" mean? — Inheritance is an IS-A relationship: the subclass is a specialised parent. Composition is a HAS-A relationship: a class contains other objects and delegates work to them. "Composition over inheritance" means preferring to combine objects, because it's more flexible and…
  • What's the difference between association, aggregation and composition? — All three describe how objects are related, from loosest to tightest: - Association: a general "uses" or "knows" relationship.
  • Explain the IS-A and HAS-A relationships. — IS-A is inheritance or interface implementation: Car extends Vehicle, so a Car IS-A Vehicle. HAS-A is composition: Car has an Engine field, so a Car HAS-A Engine.
  • What are the this and super keywords? — this refers to the current object. super refers to the parent-class part of the current object. It's used to call the parent's constructor, or its version of an overridden method.
  • Can this be reassigned? What happens if you use super in a class with no explicit parent? — this is effectively final. this = other; is a compile error. And every class except Object has a superclass (Object by default), so super.toString() or super() compiles fine in a class that doesn't write extends.
  • Can this or super be used in a static method? — No. Static methods belong to the class, not to any object, so there's no current instance for this or super to refer to.
  • How does super relate to polymorphism? — Polymorphism lets an overriding method replace the parent's behaviour. super.method() lets the override extend that behaviour instead of replacing it: run the parent logic, then add to it.

Polymorphism, Overloading & Overriding — Interview Questions — open the lesson

  • What is polymorphism in Java? — Polymorphism ("many forms") means one interface or method name can behave differently depending on the actual object or the arguments.
  • What is method overloading? — Declaring several methods with the same name but different parameter lists in the same class (or inherited into it).
  • How does overloading relate to polymorphism? — It's the static form of polymorphism. One method name has many forms, and the right one is chosen at compile time from the declared types of the arguments.
  • How does the compiler decide which overloaded method to call? — It finds every method whose name matches and whose parameters can accept the arguments, then picks the most specific one.
  • Can methods be overloaded by return type alone? — No. int total() and long total() in the same class is a compile error. The compiler chooses an overload from the call's arguments, and a call like total(); gives it nothing to decide with.
  • What are the rules for method overloading? — The method name must be the same, and the parameter lists must differ in the number, types or order of the parameters.
  • What is method overriding? — A subclass provides its own implementation of an instance method inherited from a parent class or an interface, with the same name and parameter list.
  • What are the rules for method overriding? — - The name and parameter list must be the same. - The return type must be the same or a subtype (a covariant return). - Access can't be more restrictive (public can't become protected). - It can't throw new or broader checked exceptions. - static, final and private…
  • What does the @Override annotation do? — It tells the compiler that you intend to override a method. If no matching method exists in a supertype, for example because of a typo or a wrong parameter type, compilation fails instead of silently creating a new overload.
  • What is dynamic method dispatch? — The JVM's mechanism for choosing which overridden method to run at runtime, based on the real class of the object rather than the reference type.
  • What happens when several subclasses override the same method? — Each subclass has its own version, and a call through a parent reference runs the version belonging to the object's actual class.
  • Can constructors be polymorphic or overridden? — No. Constructors aren't inherited, so they can't be overridden, and they don't take part in dynamic dispatch. They can be overloaded, since a class can have several constructors with different parameters.

Abstraction, Interfaces & Encapsulation — Interview Questions — open the lesson

  • What is abstraction in Java? — Abstraction means exposing what an object does while hiding how it does it. In Java you express it with interfaces and abstract classes: callers depend on the contract, not on the implementation.
  • Where is abstraction used in the Java libraries? — Everywhere. The Collections Framework is the classic example: you code against List, Map and Set, and you can swap ArrayList for LinkedList without changing the calling code.
  • What happens if a class contains an abstract method? — The class must itself be declared abstract, or it won't compile. An abstract class can't be instantiated with new.
  • How does abstraction help achieve loose coupling? — When a class depends on an interface rather than a concrete class, you can change, replace or mock the implementation without touching the class.
  • What is an interface in Java? — An interface is a reference type that defines a contract: a set of methods that implementing classes must provide.
  • What's the difference between an interface and an abstract class? — An abstract class is a partially built parent. It can hold state, constructors and shared code, and a class can extend only one.
  • When would you use an interface, and when an abstract class? — - Use an interface to define a role or capability that unrelated classes can share (Comparable, PaymentGateway, Runnable), and whenever you want multiple implementations or easy mocking.
  • How do you get multiple inheritance using interfaces? — A class can implement several interfaces, so it inherits several types. It can be passed wherever any of them is expected.
  • Can interfaces have static methods? How do they differ from default methods? — Yes, since Java 8. - A static interface method belongs to the interface itself. It's called as InterfaceName.method(), and it's not inherited by implementing classes, so it can't be overridden. - A default method is an instance method with a body.
  • What is the diamond problem, and how does Java handle it? — The diamond problem arises when a class inherits the same method from two parents that share an ancestor, which makes it ambiguous which version to use.
  • What's the difference between Comparable and Comparator? — Comparable defines a class's natural ordering. The class itself implements compareTo, and there's exactly one such ordering.
  • What is encapsulation? Give an example. — Encapsulation means bundling data with the methods that operate on it, and restricting direct access to that data.
  • How does encapsulation improve security and integrity? — Only the class's own methods can change its state, so every change goes through validation. Invalid states become impossible, misuse is limited, and the internal representation can change without breaking callers.

Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions — open the lesson

  • What is a constructor in Java? — A constructor is a special block that initialises a new object. It has the same name as the class, no return type (not even void), and runs automatically when you use new.
  • Can a constructor be overloaded? — Yes. A class can have several constructors with different parameter lists, and they can call each other with this(...).
  • Can a constructor be private? Why would you do that? — Yes. A private constructor stops other classes from calling new. The typical uses are: - Singletons. - Utility classes with only static methods (such as Collections and Math). - Static factory methods, which control how instances are created (List.of, Optional.of).…
  • What are anonymous classes, and what are their advantages? — An anonymous class is a class without a name that is declared and instantiated in a single expression. It's typically used to implement an interface or extend a class for one-off use.
  • What is a Singleton class? — A class that allows exactly one instance in the application (strictly, per class loader), and provides a global access point to it.
  • How do you create a Singleton class? — 1. Make the constructor private. 2. Hold the single instance in a private static field. 3. Expose it through a public static accessor.
  • Is a singleton thread-safe? — It depends on how it's created. A lazy singleton written like this is not thread-safe, because two threads can both see null and each create an instance — public static Cache getInstance() { if (instance == null) instance = new Cache();
  • What does immutability mean in Java? — An immutable object's state can't change after construction. Any "modification" returns a new object instead. Examples: String, Integer, LocalDate, BigDecimal, and records with immutable fields.
  • Why are immutable objects useful in concurrent programming? — Their state never changes, so any number of threads can read them at the same time with no locking and no risk of seeing a half-updated object.
  • What are immutable classes? — Classes whose instances can't be modified after creation. All state is set once, usually in the constructor. There are no setters, and no method leaks a way to change the internals.
  • How do you create an immutable class? — 1. Declare the class final, so no subclass can add mutability. 2. Make all fields private final. 3. Don't provide setters. 4.

Design Patterns & SOLID Basics — Interview Questions — open the lesson

  • What is a design pattern, and why do we use them? — A design pattern is a proven, reusable solution to a recurring design problem. It's a template for structuring classes and objects, not a piece of code to copy.
  • Name and explain a few common design patterns. — Pick patterns you can illustrate — interface ShippingStrategy { BigDecimal cost(Order o); } class StandardShipping implements…
  • How do design patterns affect performance? — Usually only slightly. Patterns add some indirection (extra objects, interface calls), and the JIT compiler largely optimises that away.
  • Which pattern would you use to manage database connections efficiently? — An Object Pool, meaning a connection pool such as HikariCP (the Spring Boot default). The pool keeps a set of open connections, lends one out for each unit of work, and takes it back afterwards.
  • How do you choose the right design pattern for a problem? — Start from the problem, not the pattern: 1. Identify what varies, or what hurts: object creation, a growing if/else over types, the need to add behaviour, a notification fan-out. 2.
  • What are the SOLID principles? — Five object-oriented design principles that keep code easy to change — interface GpsDevice { Position currentPosition(); } class VehicleTracker {

Strings, Keywords, Exceptions & Serialization

Strings, String Pool, StringBuilder & StringBuffer — Interview Questions — open the lesson

  • What is the string pool? — The string pool (the "intern pool") is a JVM-managed table of unique String instances. String literals, and strings you explicitly intern(), are stored there once and reused.
  • When is the string pool (interning) not beneficial? — When strings are mostly unique, or short-lived. Interning costs a hash lookup and keeps an entry in the pool table, so doing it on unique values (request IDs, UUIDs, user input) wastes CPU and memory, and saves nothing.
  • What's the difference between String and StringBuffer? — String is immutable. Every "modification" creates a new object. StringBuffer is a mutable sequence of characters that you change in place.
  • How is StringBuilder different from StringBuffer, and when should you use each? — They have the same API. StringBuilder (Java 5) is not synchronized, so it's faster, and it's the right choice almost always, because string building usually happens inside one method on one thread.
  • Give a scenario where StringBuffer is better than String. — When one character buffer must be modified by several threads. For example, several worker threads appending fragments to a shared diagnostic report, where each append must be atomic.
  • What's the difference between a string literal and a string object? — A literal ("java") is pooled: equal literals share one instance. new String("java") always creates a new, separate object, even though an equal string already exists in the pool.
  • Why is String immutable in Java? — For security, safe sharing (pooling), thread safety and hash caching.

static & final Keywords — Interview Questions — open the lesson

  • What does the static keyword mean? — static marks a member as belonging to the class rather than to any object. There's one copy, shared by all instances, and it's accessible without creating an object: Math.max(a, b), Integer.MAX_VALUE.
  • What is a static block? — A static { … } block runs once, when the class is initialised (on first use), before any object is created or any static method runs.
  • Can a static block throw an exception? — It can't throw a checked exception. There's nowhere to declare a throws clause, so checked exceptions must be caught inside the block.
  • Can we override static methods? — No. Overriding relies on runtime dispatch on the object's type, and static methods are bound at compile time to the class.
  • Can a static method access non-static members? — Not directly. A static method has no this, because no particular object is involved, so it can't refer to instance fields or methods.
  • What does the final keyword do? — It means "can't be changed", in three places: - A final variable can be assigned only once. - A final method can't be overridden. - A final class can't be extended (String, Integer, LocalDate).
  • What are common uses of final variables? — - Constants: static final int MAX_SIZE = 100;. - Immutable fields in value objects and injected dependencies. - Local variables captured by lambdas or anonymous classes, which must be final or effectively final. - Parameters, as documentation that they're never reassigned.
  • How does final contribute to immutability and thread safety? — final fields can't be reassigned, and the Java Memory Model gives them a special guarantee. Once a constructor finishes, any thread that sees the object also sees the final fields' fully initialised values, without synchronisation (provided this didn't escape during…
  • Are there performance considerations when using final? — Very few. The JIT compiler is already good at inlining non-final methods (it tracks which classes are actually loaded and deoptimises if that changes), so marking methods final rarely makes code faster.
  • Does final improve performance by reducing method-call overhead? — In early JVMs, somewhat. On modern HotSpot, not meaningfully. The JIT uses class hierarchy analysis to inline methods that have only one loaded implementation, whether or not they're final, and it inlines polymorphic call sites that are hot.

Exceptions, Generics, Enums & Reflection — Interview Questions — open the lesson

  • What are exceptions in Java? — An exception is an object representing an abnormal event that interrupts normal flow: a missing file, invalid input, a null reference.
  • What's the difference between checked and unchecked exceptions? — Checked exceptions (subclasses of Exception, but not of RuntimeException) are verified at compile time. You must either catch them or declare them with throws.
  • What are the roles of try, catch and finally? — - try wraps the code that might throw. - catch handles a specific exception type. - finally always runs afterwards, whether or not an exception occurred, and is used for cleanup.
  • If try or catch executes a return, does finally still run? — Yes. finally runs after the return value is computed but before control goes back to the caller.
  • Can you use try without catch? — Yes. try–finally (no catch) runs cleanup while letting the exception propagate to the caller. try-with-resources can also stand alone, with no catch and no finally.
  • Does exception handling affect performance? — A try block itself costs essentially nothing. Throwing an exception is what's expensive, mainly because the stack trace is captured, and unwinding the stack takes time.
  • When does a finally block not execute? — - When the JVM stops before reaching it: System.exit() in try or catch, Runtime.halt(), a JVM crash, or the process being killed (kill -9, power loss). - When the try block never finishes, because of an infinite loop or a deadlock. - When the thread is a daemon…
  • Can a try have multiple finally blocks? How do you handle several exceptions in one catch? — No. Each try can have at most one finally (but many catch blocks). To handle several exception types the same way, use multi-catch (Java 7+) — try { importFile(path);
  • What's the difference between Throwable, Exception and Error? — Throwable is the root of everything that can be thrown. Exception represents conditions an application might reasonably handle.
  • What's the difference between finally and finalize()? — finally is a language block that runs deterministically after try/catch. finalize() was a method the garbage collector might call before reclaiming an object.
  • What are generics? — Generics let classes, interfaces and methods take type parameters (List<String>, Map<K, V>, <T> T first(List<T>)).
  • What is an enum in Java? — An enum is a type with a fixed set of named constants, such as OrderStatus { PLACED, PAID, SHIPPED, DELIVERED }.
  • What is reflection? — Reflection (java.lang.reflect) lets code inspect and use classes at runtime: list fields, methods, constructors and annotations, create instances, call methods, and read or write fields, even private ones, when access is allowed.

Serialization & transient — Interview Questions — open the lesson

  • What is serialization in Java? — Serialization converts an object (and the objects it references) into a byte stream, so it can be stored or sent over a network.
  • What is the purpose of serialVersionUID? — It's a version number for a serializable class. During deserialization, the JVM compares the UID stored in the byte stream with the UID of the class currently loaded.
  • What happens if serialVersionUID changes between serialization and deserialization? — Deserialization fails with a java.io.InvalidClassException ("local class incompatible: stream classdesc serialVersionUID = X, local class serialVersionUID = Y").
  • How do you stop certain fields from being serialized? What does transient mean? — Mark them transient. A transient field is skipped during serialization, and gets its default value (null, 0, false) after deserialization.
  • Can a class be serialized if one of its fields isn't serializable? — Only if that field is transient (or null at the time), or if you handle it with custom serialization logic.
  • What are writeObject() and readObject() used for? — They're private hook methods that a serializable class can declare to customise its own serialization. You call defaultWriteObject()/defaultReadObject() for the normal fields, then write or read extra data.
  • Are static fields serialized? — No. Serialization captures an object's state, and static fields belong to the class. After deserialization, a static field has whatever value the class currently holds in that JVM.
  • How are circular references handled? — Automatically. ObjectOutputStream keeps a table of the objects already written in the stream. When it meets the same object again, it writes a back-reference (a handle) instead of serializing the object a second time.

Follow-up questions this topic invites — and their answers

Q: How should I use this list in the last week before an interview? A: Do one pass per day. Cover the answer text, say your answer out loud, then check it. Mark every question you could not answer crisply, and spend your study time only on the marked ones by opening the linked full answer. By the third pass the marked list should be short.

Q: The interviewer asks one of these basics — should I give only the one-liner? A: Lead with the one-liner, then add one concrete detail or example from your own work. At this level the follow-up usually probes the mechanism behind the basic answer, so be ready to go one layer deeper using the key points in the full lesson.

Q: Some answers here were corrected compared with common prep sheets — why? A: Several widely shared answers are outdated or wrong (for example, Java version details, removed Spring APIs, or SQL queries that miss edge cases). The full lessons call these out under "Common trap" — reading those is the fastest way to stand out from candidates who memorised the same sheets.

Next

Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)

AI Tutor

Lesson: Revise: Core Java Fundamentals (Fresher Tier)

Quick actions

AI responses can be inaccurate. Verify critical information.