Cracking the Java Interview_ Top Q&A
Cracking the Java Interview_ Top Q&A
This document, is intended to be a helpful resource for Java developers preparing for technical interviews.
Given the high demand for Java skills, I’ve compiled a collection of frequently asked questions, leveraging
Gemini AI to formulate concise and informative answers. While I’ve strived for accuracy, I acknowledge
that errors may occur. I encourage readers to point out any inaccuracies so that I can make corrections.
This document is not meant to be an exhaustive treatise on Java or a substitute for in-depth learning.
Rather, it aims to provide a targeted overview of key concepts and questions, helping candidates identify
areas where they should focus their preparation. The emphasis is on concise answers to guide your study,
not on providing comprehensive explanations.
Disclaimer: This document is intended for informational purposes only and should not be considered a substitute for
professional training or advice.
Contents
1 Java Fundamentals 4
1.1 What is Java, and what are its key features? . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 Why is Java platform-independent? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 What are JDK, JRE, and JVM? How do they differ? . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Explain the JVM architecture and the role of Just-In-Time (JIT) compilation. . . . . . . . . 4
1.5 Explain Java memory management (Heap, Stack, and Garbage Collection). . . . . . . . . . . 5
1.6 What is public static void main(String args[]), and why is it needed? . . . . . . . . . 5
1.7 Describe the execution flow of a Java program. . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.8 What is a package in Java, and how is it used? What are the main types? . . . . . . . . . . . 5
1.9 What is the difference between == and .equals() in Java? . . . . . . . . . . . . . . . . . . . . 5
9 Java 8 Features 15
9.1 What are the new features introduced in Java 8? . . . . . . . . . . . . . . . . . . . . . . . . . 15
9.2 What is a lambda expression in Java? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
9.3 What is a functional interface in Java? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
9.4 What is the Stream API, and how does it work? . . . . . . . . . . . . . . . . . . . . . . . . . 16
9.5 Explain the map(), filter(), and reduce() operations in Java 8. . . . . . . . . . . . . . . . 16
2
9.6 What is the purpose of the Optional class in Java? . . . . . . . . . . . . . . . . . . . . . . . . 16
9.7 What are functional interfaces, and what is the difference between Predicate and Function? 16
9.8 What is a default method in interfaces? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
9.9 What is the significance of the forEach() method in Java 8? . . . . . . . . . . . . . . . . . . 16
9.10 What are method references in Java 8? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3
1 Java Fundamentals
1.1 What is Java, and what are its key features?
Java is a high-level, object-oriented programming language developed by Sun Microsystems (now owned by
Oracle). Key features include:
• Object-Oriented: Organizes code around objects and their interactions.
• Platform-Independent: ”Write Once, Run Anywhere” (WORA) capability due to bytecode.
• Robust: Strong memory management and exception handling.
1.3 What are JDK, JRE, and JVM? How do they differ?
• JDK (Java Development Kit): A software development kit that includes tools for developing,
compiling, and debugging Java programs. It contains the JRE plus the compiler (javac) and other
development tools.
• JRE (Java Runtime Environment): Provides the runtime environment needed to execute Java
programs. It includes the JVM and the necessary libraries.
• JVM (Java Virtual Machine): An abstract machine that executes Java bytecode. It’s responsible
for loading, verifying, and executing the bytecode. It’s the key to Java’s platform independence.
1.4 Explain the JVM architecture and the role of Just-In-Time (JIT) compila-
tion.
The JVM architecture includes:
4
1.5 Explain Java memory management (Heap, Stack, and Garbage Collection).
• Heap: Stores objects and their instance variables. Shared by all threads.
• Stack: Stores method frames (local variables, method parameters, return addresses). Each thread has
its own stack.
• Garbage Collection: Automatic memory management process that reclaims memory occupied by
objects that are no longer referenced by the program. This prevents memory leaks.
1.6 What is public static void main(String args[]), and why is it needed?
public static void main(String args[]) is the entry point of any Java program.
• public: Access modifier, making it accessible from anywhere.
• static: Allows the main method to be called without creating an object of the class.
• void: Specifies that the main method doesn’t return any value.
• String args[]: Accepts command-line arguments as an array of strings.
It’s needed because the JVM looks for this specific method signature to start the execution of a Java program.
• 4: The JVM executes the bytecode, potentially using the JIT compiler to translate parts of it into
native machine code for better performance.
1.8 What is a package in Java, and how is it used? What are the main types?
A package is a way to organize related classes and interfaces into namespaces. It helps prevent naming
conflicts and improves code maintainability. Packages are used with the import statement to bring classes
into the current scope.
Main types of packages:
• Built-in Packages: Part of the Java Development Kit (e.g., java.lang, java.util, java.io).
• User-defined Packages: Created by developers to organize their code.
For example, for String comparison, you should almost always use ‘.equals()‘ and not ‘==‘.
5
2 Data Types, Variables & Control Flow
2.1 What are Java data types, variables, and literals?
• Data Types: Specify the kind of data a variable can hold (e.g., integer, floating-point, character,
boolean). Java has primitive types (e.g., int, double, char, boolean) and reference types (objects).
• Variables: Named storage locations that hold data. A variable must have a specific data type.
• Literals: Constant values that appear directly in the code (e.g., 10, 3.14, ’A’, "hello").
2.2 What are the different types of variables in Java (Local, Instance, Static)?
• Local Variables: Declared inside a method. Their scope is limited to that method.
• Instance Variables: Declared within a class but outside any method. Each object of the class has
its own copy of instance variables.
• Static Variables (Class Variables): Declared within a class and marked with the static keyword.
They belong to the class itself, not to any specific object. There is only one copy of a static variable
shared among all the objects of the class.
2.3 What is the final keyword, and how is it used with variables, methods,
and classes?
The final keyword has different meanings depending on where it’s used:
• Variables: Makes the variable a constant. Its value cannot be changed after initialization.
• Unboxing: Automatic conversion of a wrapper object to its corresponding primitive value (e.g.,
Integer to int).
Example:
Integer intObj = 10; // Autoboxing
int intVal = intObj; // Unboxing
6
3 Strings & String Manipulation
3.1 What is the Java String Pool?
The Java String Pool (also called the String Constant Pool) is a special area in the heap memory that stores
string literals. When you create a string literal (e.g., String str = "hello";), the JVM first checks if a
string with the same value (”hello”) already exists in the String Pool. If it does, the new string variable
will refer to the existing string in the pool. If it doesn’t, a new string object is created in the pool, and the
variable refers to it. This mechanism helps save memory by reusing string literals.
If you need to modify a string, you create a new string object with the desired changes.
• StringBuilder: Represents mutable strings. It allows you to modify the string in place without
creating new objects, making it more efficient for string manipulation. Not thread-safe.
• StringBuffer: Also represents mutable strings. Similar to StringBuilder, but it is thread-safe
(synchronized), making it suitable for multithreaded environments.
Use String when you don’t need to modify the string. Use StringBuilder for frequent string manipulations
in a single-threaded environment. Use StringBuffer when you need thread-safe string manipulation.
3.4 How does creating a String using new() differ from using a String literal?
• String Literal (e.g., String str = "hello";): The string is created in the String Pool (if it doesn’t
already exist), and the variable refers to it.
• Using new() (e.g., String str = new String("hello");): A new string object is created in the
heap, even if a string with the same value exists in the String Pool. The variable refers to this new
object in the heap.
Using string literals is generally preferred for efficiency, as it can reuse strings from the pool.
• ==: Compares memory addresses (references). It checks if two variables refer to the same object in
memory.
• .equals(): Compares the content of the strings. It checks if two strings have the same sequence of
characters.
7
Example:
String str1 = "hello";
String str2 = new String("hello");
• Default Constructor: A constructor that takes no arguments. If you don’t define any constructors
in a class, the compiler automatically provides a default constructor. It initializes instance variables
to their default values (e.g., 0 for numeric types, null for object references, false for booleans).
• Parameterized Constructor: A constructor that takes one or more arguments. It allows you to
initialize instance variables with specific values during object creation.
1. Creation: The object is created using the new keyword. Memory is allocated for the object, and the
constructor is called to initialize its instance variables.
2. Usage: The object is used by the program. Its methods are called, and its instance variables are
accessed.
3. Garbage Collection: When the object is no longer referenced by any part of the program, it becomes
eligible for garbage collection. The garbage collector reclaims the memory occupied by the object.
4. Finalization (Optional): Before an object is garbage collected, the finalize() method (if defined
in the class) is called. This provides an opportunity to perform cleanup operations. However, relying
on finalization is generally discouraged.
8
4.4 What is serialization and deserialization in Java?
• Serialization: The process of converting an object’s state into a stream of bytes. This stream can be
stored in a file or transmitted over a network. It allows you to save the state of an object and recreate
it later.
• Deserialization: The reverse process of converting a stream of bytes back into an object. It recon-
structs the object’s state from the serialized data.
Serialization is often used for saving objects to disk (persistence) or for sending objects over a network.
The java.io.Serializable interface is used to mark objects that can be serialized.
9
5.5 What are the different types of polymorphism in Java?
There are two main types of polymorphism in Java:
5.7 What are access modifiers in Java, and what are their scopes?
Access modifiers control the visibility and accessibility of classes, interfaces, variables, and methods. Java
has four access modifiers:
5.10 What are this and super keywords, and how are they used?
• this: Refers to the current object. It’s used to access instance variables or methods of the current
object, especially when there is a naming conflict between a local variable and an instance variable. It
can also be used to call one constructor from another constructor within the same class (constructor
chaining).
• super: Refers to the superclass of the current object. It’s used to access instance variables or methods
of the superclass, especially when a subclass has a method with the same name as a method in its
superclass (method overriding). It can also be used to call the superclass constructor from the subclass
constructor.
10
5.11 Does Java use pass-by-value or pass-by-reference?
Java uses pass-by-value. However, when you pass an object to a method, you are passing a copy of the
object’s reference (memory address), not the object itself. So, if you modify the object’s state within the
method, the changes will be reflected in the original object. It might seem like pass-by-reference, but it’s
still pass-by-value (of the reference).
5.12 What is the difference between shallow copy and deep copy in Java?
• Shallow Copy: Creates a new object, but the instance variables of the new object still refer to the
same objects as the original object. Changes made to the objects referenced by the copy will also affect
the original object.
• Deep Copy: Creates a new object, and also creates copies of all the objects referenced by the instance
variables of the original object. Changes made to the objects referenced by the copy will not affect the
original object.
Deep copy creates a completely independent copy of the object and all its related objects.
• Map: A collection of key-value pairs. Each key is unique, but values can be duplicated. (e.g., HashMap,
TreeMap)
Use ArrayList when you need fast access to elements. Use LinkedList when you need frequent inser-
tions and deletions. Avoid Vector unless you specifically require thread safety (consider other concurrent
collections instead).
11
6.4 How does HashMap work internally in Java?
HashMap uses a hash table data structure to store key-value pairs. It uses a hash function to calculate the
index (bucket) in the table where a key-value pair should be stored. Collisions (when multiple keys map to
the same bucket) are handled using linked lists (or, in newer Java versions, balanced trees if the list gets too
long). When retrieving a value, the hash function is used to find the bucket, and then the linked list (or
tree) in that bucket is searched for the key.
• ListIterator: Used to traverse elements in a list in both forward and backward directions. Provides
additional methods like previous(), hasPrevious(), add(), and set().
ListIterator can only be used with lists, while Iterator can be used with any collection.
12
7.2 What is the difference between checked (compile-time) and unchecked (run-
time) exceptions? Examples of each.
• Checked Exceptions: Exceptions that are checked by the compiler at compile time. The compiler
forces you to either handle them using a try-catch block or declare them using the throws keyword.
IOException (e.g., file not found) is a checked exception.
• Unchecked Exceptions: Exceptions that are not checked by the compiler. They typically occur due
to programming errors. You are not required to handle them explicitly. NullPointerException and
ArrayIndexOutOfBoundsException are unchecked exceptions.
7.7 What are custom exceptions, and how do you create them?
Custom exceptions are exceptions that you define yourself. They allow you to create specific exception
types for your application’s needs. To create a custom exception, you create a new class that extends the
Exception class (for checked exceptions) or the RuntimeException class (for unchecked exceptions).
Example:
class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
13
7.8 What is the difference between final, finally, and finalize()?
• final: A keyword that can be used with variables (making them constants), methods (preventing
overriding), and classes (preventing subclassing).
• finally: A block of code in a try-catch block that is always executed, regardless of whether an
exception is thrown or caught. Used for cleanup operations.
• finalize(): A method that is called by the garbage collector before an object is reclaimed. It provides
an opportunity to perform cleanup actions. However, relying on finalize() is generally discouraged.
8.2 What is the difference between Runnable, Callable, and Thread in Java?
• Runnable: An interface that defines a single method, run(). You implement this interface to define
the code that a thread will execute. You then create a Thread object, passing an instance of your
Runnable implementation to it. This is the preferred way to create threads.
• Callable: An interface similar to Runnable, but its call() method can return a value and can throw
checked exceptions. Used with ExecutorService for more advanced thread management.
• Thread: A class that represents a thread. You can create a thread by extending the Thread class and
overriding its run() method. However, implementing Runnable is generally preferred because it allows
you to inherit from other classes as well.
• New: The thread has been created but not yet started.
• Runnable: The thread is ready to run and is waiting for its turn to get CPU time.
• Blocked/Waiting: The thread is blocked waiting for a resource (e.g., a lock, I/O operation) or
waiting for another thread to complete a task.
• Timed Waiting: Similar to waiting, but the thread will only wait for a specified amount of time.
• Terminated: The thread has finished executing.
14
8.5 What is the volatile keyword, and how does it work?
The volatile keyword is used to indicate that a variable’s value might be changed by multiple threads. It
ensures that the value of the volatile variable is always read from main memory and not from the thread’s
local cache. This prevents visibility issues where one thread might see an outdated value of the variable. It
does not provide atomicity.
• wait(): Causes the current thread to wait until it is notified by another thread. The thread releases
the lock on the object it is waiting on.
These methods must be called from within a synchronized block or method. They are used in producer-
consumer scenarios or other situations where threads need to coordinate their actions.
9 Java 8 Features
9.1 What are the new features introduced in Java 8?
Java 8 introduced several significant features, including:
• Lambda expressions
• Functional interfaces
• Stream API
• Method references
• Default methods in interfaces
15
9.4 What is the Stream API, and how does it work?
The Stream API provides a way to process collections of data in a declarative and functional style. A stream
represents a sequence of elements that can be processed using various operations like filtering, mapping, and
reducing. Streams don’t modify the original data source; they produce new streams as a result of operations.
They also support parallel processing, which can significantly improve performance.
9.7 What are functional interfaces, and what is the difference between Predicate
and Function?
Functional interfaces are interfaces with a single abstract method.
• Predicate: A functional interface that represents a boolean-valued function. Its test() method takes
an argument and returns a boolean. Used for filtering.
• Function: A functional interface that represents a function that takes one argument and returns a
result. Its apply() method takes an argument and returns a value. Used for mapping/transforming.
16
10 Spring Framework & Spring Boot
10.1 What is the Spring Framework, and what are its key features?
The Spring Framework is a powerful and versatile open-source framework for building enterprise Java appli-
cations. Key features include:
• Inversion of Control (IoC) and Dependency Injection (DI): Core principles that promote loose
coupling and testability.
• Aspect-Oriented Programming (AOP): Enables modularization of cross-cutting concerns (e.g.,
logging, security).
• Data Access and Integration: Provides support for working with databases and other data sources.
• Web Development: Offers a robust framework for building web applications (Spring MVC).
• Transaction Management: Simplifies transaction management.
• Testing: Provides support for unit and integration testing.
Spring’s IoC container manages the creation and wiring of beans. DI is implemented through constructor
injection, setter injection, or field injection using annotations like @Autowired.
1. Bean Definition: The bean’s configuration is defined (e.g., in XML or using annotations).
2. Bean Instantiation: The Spring container creates an instance of the bean.
3. Dependency Injection: Dependencies are injected into the bean.
4. Initialization: The bean is initialized (e.g., using an @PostConstruct method or implementing the
InitializingBean interface).
17
5. Usage: The bean is used by the application.
6. Destruction: The bean is destroyed (e.g., using an @PreDestroy method or implementing the
DisposableBean interface).
Spring Boot makes it easier to get started with Spring and reduces boilerplate code.
10.9 What is the difference between JPA, Spring Data JPA, Spring JDBC and
Hibernate?
• JPA (Java Persistence API): A specification for accessing, persisting, and managing data between
Java objects and a relational database. It defines a standard set of interfaces and annotations.
• Hibernate: A popular ORM (Object-Relational Mapping) implementation of the JPA specification.
It provides a concrete implementation of the JPA interfaces and handles the mapping between Java
objects and database tables.
• Spring Data JPA: A Spring module that simplifies working with JPA. It reduces boilerplate code for
common database operations by providing interfaces for common queries and allowing you to define
custom queries using method naming conventions.
• Spring JDBC: A Spring module that provides support for working with JDBC (Java Database
Connectivity). It offers utilities for simplifying common JDBC operations, such as executing queries
and updating data. It is lower level than JPA, giving you more control but requiring more code to
manage the connection, queries, and mapping data.
18
JPA is the standard specification. Hibernate is a popular implementation of JPA. Spring Data JPA simplifies
working with JPA. Spring JDBC is for lower-level database access.
Thank you for your reading! I sincerely hope this document has been helpful to you. Whether you’re
preparing for an interview or pursuing other endeavors, I wish you all the best.
19