0% found this document useful (0 votes)
48 views

Cracking the Java Interview_ Top Q&A

This document serves as a resource for Java developers preparing for technical interviews, compiling frequently asked questions with concise answers generated using Gemini AI. It covers various Java topics, including fundamentals, data types, object-oriented programming, collections, exception handling, multithreading, and Java 8 features. The document emphasizes targeted preparation rather than exhaustive learning, and readers are encouraged to report any inaccuracies.

Uploaded by

suresh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Cracking the Java Interview_ Top Q&A

This document serves as a resource for Java developers preparing for technical interviews, compiling frequently asked questions with concise answers generated using Gemini AI. It covers various Java topics, including fundamentals, data types, object-oriented programming, collections, exception handling, multithreading, and Java 8 features. The document emphasizes targeted preparation rather than exhaustive learning, and readers are encouraged to report any inaccuracies.

Uploaded by

suresh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Cracking the Java Interview: Top Q&A on Frequently

Asked Java Questions


Ali Benhima
January 29, 2025

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

2 Data Types, Variables & Control Flow 6


2.1 What are Java data types, variables, and literals? . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2 What are the different types of variables in Java (Local, Instance, Static)? . . . . . . . . . . . 6
2.3 What is the final keyword, and how is it used with variables, methods, and classes? . . . . . 6
2.4 Explain autoboxing and unboxing in Java. (Wrapper classes) . . . . . . . . . . . . . . . . . . 6
2.5 What is the ternary operator in Java? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

3 Strings & String Manipulation 7


3.1 What is the Java String Pool? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 Why are Strings immutable in Java? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.3 What is the difference between String, StringBuilder, and StringBuffer? . . . . . . . . . 7
3.4 How does creating a String using new() differ from using a String literal? . . . . . . . . . . . 7
3.5 How are Strings compared in Java? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
4 Object Creation, Lifecycle & Serialization 8
4.1 What is a constructor in Java? What are its types (default, parameterized)? . . . . . . . . . 8
4.2 What is constructor overloading, chaining, and the copy constructor? . . . . . . . . . . . . . . 8
4.3 What is the life cycle of an object in Java? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
4.4 What is serialization and deserialization in Java? . . . . . . . . . . . . . . . . . . . . . . . . . 9

5 Object-Oriented Programming (OOP) in Java 9


5.1 What is an object-oriented paradigm? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
5.2 What is the difference between a class and an object? . . . . . . . . . . . . . . . . . . . . . . 9
5.3 Explain the four main principles of OOP: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
5.4 What is the difference between an abstract class and an interface? . . . . . . . . . . . . . . . 9
5.5 What are the different types of polymorphism in Java? . . . . . . . . . . . . . . . . . . . . . . 10
5.6 What is method overloading and method overriding? . . . . . . . . . . . . . . . . . . . . . . . 10
5.7 What are access modifiers in Java, and what are their scopes? . . . . . . . . . . . . . . . . . . 10
5.8 Can you override a private or static method in Java? . . . . . . . . . . . . . . . . . . . . . . . 10
5.9 Does Java support multiple inheritance? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
5.10 What are this and super keywords, and how are they used? . . . . . . . . . . . . . . . . . . 10
5.11 Does Java use pass-by-value or pass-by-reference? . . . . . . . . . . . . . . . . . . . . . . . . . 11
5.12 What is the difference between shallow copy and deep copy in Java? . . . . . . . . . . . . . . 11

6 Java Collections & Generics 11


6.1 What is the Java Collections Framework? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
6.2 Explain the difference between List, Set, and Map. . . . . . . . . . . . . . . . . . . . . . . . . 11
6.3 What is the difference between ArrayList, LinkedList, and Vector? . . . . . . . . . . . . . 11
6.4 How does HashMap work internally in Java? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
6.5 What is the difference between HashMap and HashTable? . . . . . . . . . . . . . . . . . . . . 12
6.6 What is the Comparable and Comparator interface? . . . . . . . . . . . . . . . . . . . . . . . 12
6.7 What is the difference between Iterator and ListIterator? . . . . . . . . . . . . . . . . . . 12
6.8 What is the significance of Generics in Java? . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

7 Exception Handling & Errors 12


7.1 What is exception handling in Java? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
7.2 What is the difference between checked (compile-time) and unchecked (runtime) exceptions?
Examples of each. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
7.3 Explain the try-catch-finally block. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
7.4 What happens if an exception is not caught? . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
7.5 What is the difference between Error and Exception? . . . . . . . . . . . . . . . . . . . . . . 13
7.6 What is the difference between throw and throws? . . . . . . . . . . . . . . . . . . . . . . . . 13
7.7 What are custom exceptions, and how do you create them? . . . . . . . . . . . . . . . . . . . 13
7.8 What is the difference between final, finally, and finalize()? . . . . . . . . . . . . . . . 14

8 Multithreading & Concurrency 14


8.1 What is multithreading in Java? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
8.2 What is the difference between Runnable, Callable, and Thread in Java? . . . . . . . . . . . 14
8.3 What are the different thread states in Java? . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
8.4 What is the synchronized keyword, and how does it work? . . . . . . . . . . . . . . . . . . . 14
8.5 What is the volatile keyword, and how does it work? . . . . . . . . . . . . . . . . . . . . . . 15
8.6 What is the difference between notify(), notifyAll(), and wait()? . . . . . . . . . . . . . 15

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

10 Spring Framework & Spring Boot 17


10.1 What is the Spring Framework, and what are its key features? . . . . . . . . . . . . . . . . . 17
10.2 What is IOC, dependency injection, and how is it implemented in Spring? . . . . . . . . . . . 17
10.3 What is the difference between @Component, @Repository, @Service, and @Controller an-
notations? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
10.4 What is a Spring Bean and its lifecycle? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
10.5 What is the use of @Autowired? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
10.6 What is AOP (Aspect-Oriented Programming) in Spring? . . . . . . . . . . . . . . . . . . . . 18
10.7 What is the difference between @Controller and @RestController? . . . . . . . . . . . . . . 18
10.8 What is Spring Boot, and how is it different from Spring? . . . . . . . . . . . . . . . . . . . . 18
10.9 What is the difference between JPA, Spring Data JPA, Spring JDBC and Hibernate? . . . . 18

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.

• Secure: Built-in security features to protect against malicious code.


• High-Performance: Just-In-Time (JIT) compilation improves performance.
• Multithreaded: Supports concurrent execution of multiple threads.

• Dynamic: Adapts to changing environments and supports dynamic class loading.

1.2 Why is Java platform-independent?


Java achieves platform independence through the use of bytecode. When you compile a Java program, it’s
not compiled into machine code for a specific operating system. Instead, it’s compiled into an intermediate
representation called bytecode. This bytecode can be executed on any device that has a Java Virtual Machine
(JVM). The JVM acts as an intermediary, translating the bytecode into the native machine code for the
specific platform at runtime.

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.

In short: JDK contains JRE, and JRE contains JVM.

1.4 Explain the JVM architecture and the role of Just-In-Time (JIT) compila-
tion.
The JVM architecture includes:

• Class Loader: Loads class files.


• Bytecode Verifier: Ensures the integrity of bytecode.
• Runtime Data Area: Stores data during program execution (Heap, Stack, Method Area, etc.).

• Execution Engine: Executes the bytecode.


The JIT compiler is part of the Execution Engine. It compiles frequently used bytecode into native machine
code at runtime, significantly improving performance.

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.

1.7 Describe the execution flow of a Java program.


• 1: The Java source code (.java file) is compiled into bytecode (.class file) by the javac compiler.
• 2: The class loader loads the .class file into the JVM.
• 3: The bytecode verifier checks the bytecode for integrity and security.

• 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.

1.9 What is the difference between == and .equals() in Java?


• ==: Compares memory addresses (references). For primitive types, it compares values.
• .equals(): Compares the content of objects. The default implementation in the Object class com-
pares references, but it’s often overridden in classes (like String) to compare content.

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.

• Methods: Prevents the method from being overridden in subclasses.


• Classes: Prevents the class from being subclassed (inherited from).

2.4 Explain autoboxing and unboxing in Java. (Wrapper classes)


• Wrapper Classes: Object representations of primitive data types (e.g., Integer for int, Double for
double).
• Autoboxing: Automatic conversion of a primitive value to its corresponding wrapper object (e.g.,
int to Integer).

• 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

2.5 What is the ternary operator in Java?


The ternary operator (condition ? value if true : value if false) is a shorthand way to write an
if-else statement. It evaluates a boolean condition. If the condition is true, it returns the first value;
otherwise, it returns the second value.
Example:

int x = (y > 10) ? 20 : 30; // If y > 10, x = 20; otherwise, x = 30.

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.

3.2 Why are Strings immutable in Java?


Strings are immutable in Java, meaning their values cannot be changed after they are created. This is
primarily for these reasons:
• Security: Immutable strings prevent malicious code from modifying string values, which is crucial for
security-sensitive operations (e.g., passwords, file paths).
• Caching: String literals can be safely shared and reused because they cannot be changed.
• Concurrency: Immutable objects are inherently thread-safe, as they cannot be modified by multiple
threads simultaneously, avoiding race conditions.

If you need to modify a string, you create a new string object with the desired changes.

3.3 What is the difference between String, StringBuilder, and StringBuffer?


• String: Represents immutable strings. Operations on strings create new string objects.

• 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.

3.5 How are Strings compared in Java?


Strings in Java are compared using the equals() method, not the == operator.

• ==: 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");

System.out.println(str1 == str2); // false (different memory addresses)


System.out.println(str1.equals(str2)); // true (same content)
It’s crucial to use .equals() for comparing string content.

4 Object Creation, Lifecycle & Serialization


4.1 What is a constructor in Java? What are its types (default, parameterized)?
A constructor is a special method in a class that is automatically called when an object of that class is
created. Its purpose is to initialize the object’s instance variables. It has the same name as the class and no
return type (not even void).
Types of constructors:

• 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.

4.2 What is constructor overloading, chaining, and the copy constructor?


• Constructor Overloading: Defining multiple constructors in a class with different parameter lists
(different number or types of parameters). This allows you to create objects in different ways.
• Constructor Chaining: Calling one constructor from another constructor within the same class
using the this() keyword. It’s used to reuse code and avoid redundancy.
• Copy Constructor: A special constructor that creates a new object as a copy of an existing object.
It takes an object of the same class as an argument.

4.3 What is the life cycle of an object in Java?


The life cycle of an object in Java typically involves these stages:

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.

5 Object-Oriented Programming (OOP) in Java


5.1 What is an object-oriented paradigm?
The object-oriented paradigm (OOP) is a programming model that organizes software design around data,
or objects, rather than functions and logic. It emphasizes the concepts of encapsulation, inheritance, poly-
morphism, and abstraction to create modular, reusable, and maintainable code.

5.2 What is the difference between a class and an object?


• Class: A blueprint or template for creating objects. It defines the structure (data members/instance
variables) and behavior (methods) that objects of that class will have.
• Object: An instance of a class. It’s a concrete entity that has its own data and can perform the
actions defined by its class.
Think of a class as a cookie cutter and objects as the cookies created using that cutter.

5.3 Explain the four main principles of OOP:


• Encapsulation: Bundling data (instance variables) and methods that operate on that data within a
class. It also involves controlling access to the data (using access modifiers like private) to protect it
from unauthorized modification.
• Inheritance: A mechanism that allows a class (subclass/child class) to inherit properties (data and
methods) from another class (superclass/parent class). It promotes code reuse and establishes ”is-a”
relationships.
• Polymorphism: The ability of an object to take on many forms. It allows you to treat objects of
different classes in a uniform way through a common interface or superclass.
• Abstraction: Hiding complex implementation details and showing only essential information to the
user. It simplifies the interaction with objects by providing an abstract view. Interfaces and abstract
classes are used to achieve abstraction.

5.4 What is the difference between an abstract class and an interface?


• Abstract Class: Can contain both abstract methods (methods without implementation) and concrete
methods (methods with implementation). It cannot be instantiated directly; you must subclass it and
provide implementations for the abstract methods. Can have instance variables.
• Interface: Can only contain abstract methods (or default methods since Java 8). It defines a contract
that classes can implement. A class can implement multiple interfaces. Cannot have instance variables
(only constants).
An abstract class represents an ”is-a” relationship (e.g., ”Dog is-a Animal”), while an interface often repre-
sents a ”can-do” relationship (e.g., ”Flyable can-do fly”).

9
5.5 What are the different types of polymorphism in Java?
There are two main types of polymorphism in Java:

• Compile-time Polymorphism (Method Overloading): Achieved by defining multiple methods


in the same class with different parameter lists. The compiler determines which method to call based
on the arguments passed.
• Runtime Polymorphism (Method Overriding): Achieved by defining a method in a subclass that
has the same signature (name and parameters) as a method in its superclass. The JVM determines
which method to call at runtime based on the actual object type.

5.6 What is method overloading and method overriding?


• Method Overloading: Defining multiple methods in the same class with the same name but different
parameter lists.
• Method Overriding: Defining a method in a subclass that has the same signature as a method in
its superclass.

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:

• private: Accessible only within the same class.


• default (no modifier): Accessible within the same package.
• protected: Accessible within the same package and by subclasses (even if they are in a different
package).
• public: Accessible from any other class.

5.8 Can you override a private or static method in Java?


No, you cannot override a private or static method in Java. private methods are not accessible in
subclasses, so they cannot be overridden. static methods belong to the class, not to instances of the class,
so they cannot be overridden either. Attempting to define a method with the same signature as a private
or static method in a subclass will result in a compile-time error or will simply define a new method, not
an overridden one.

5.9 Does Java support multiple inheritance?


Java does not support multiple inheritance of classes (inheriting from multiple classes). However, Java does
support multiple inheritance of interfaces (a class can implement multiple interfaces).

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.

6 Java Collections & Generics


6.1 What is the Java Collections Framework?
The Java Collections Framework is a set of interfaces and classes that provide a standard way to represent
and manipulate collections of objects. It includes interfaces like List, Set, Map, and classes like ArrayList,
LinkedList, HashSet, HashMap, etc. It simplifies working with collections of data and provides efficient
implementations for common data structures.

6.2 Explain the difference between List, Set, and Map.


• List: An ordered collection that allows duplicate elements. Elements can be accessed by their index.
(e.g., ArrayList, LinkedList)
• Set: An unordered collection that does not allow duplicate elements. (e.g., HashSet, TreeSet)

• Map: A collection of key-value pairs. Each key is unique, but values can be duplicated. (e.g., HashMap,
TreeMap)

6.3 What is the difference between ArrayList, LinkedList, and Vector?


• ArrayList: A dynamic array that can grow or shrink as needed. It provides fast access to elements
using their index (O(1) for get). Adding or removing elements in the middle of the list can be slow
(O(n)).
• LinkedList: A doubly linked list. It provides fast insertion and deletion of elements (O(1) if you have
the pointer). Accessing elements by index is slow (O(n)).
• Vector: Similar to ArrayList, but it is synchronized (thread-safe). It is older and less commonly
used than ArrayList.

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.

6.5 What is the difference between HashMap and HashTable?


• HashMap: Not synchronized (not thread-safe). Allows null keys and null values. Generally more
performant than HashTable.
• HashTable: Synchronized (thread-safe). Does not allow null keys or null values. Older class.

ConcurrentHashMap is often preferred over HashTable for thread-safe operations.

6.6 What is the Comparable and Comparator interface?


• Comparable: An interface that defines a natural ordering for objects of a class. The class must
implement the compareTo() method. Used when you want to sort objects of that class based on a
single criterion.
• Comparator: An interface that defines a custom ordering for objects. You create a separate class that
implements the Comparator interface and its compare() method. Used when you want to sort objects
based on different criteria or when you don’t have access to modify the class itself.

6.7 What is the difference between Iterator and ListIterator?


• Iterator: Used to traverse elements in a collection in a forward direction. Provides methods like
next(), hasNext(), and remove().

• 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.

6.8 What is the significance of Generics in Java?


Generics allow you to write type-safe code. They enable you to specify the type of objects that a collection
can hold at compile time. This prevents you from accidentally adding objects of the wrong type to a
collection, which can lead to runtime errors. Generics also improve code readability and reduce the need for
explicit type casting. They also help with compile time type checking.

7 Exception Handling & Errors


7.1 What is exception handling in Java?
Exception handling is a mechanism in Java to deal with runtime errors (exceptions) that can disrupt the
normal flow of a program’s execution. It allows you to gracefully handle these errors and prevent the program
from crashing. Java uses try-catch-finally blocks to handle exceptions.

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.3 Explain the try-catch-finally block.


The try-catch-finally block is used for exception handling:
• try: Contains the code that might throw an exception.
• catch: Handles a specific type of exception. You can have multiple catch blocks to handle different
exceptions.
• finally: Contains code that is always executed, regardless of whether an exception is thrown or
caught. It’s typically used for cleanup operations (e.g., closing files, releasing resources).

7.4 What happens if an exception is not caught?


If an exception is not caught by any catch block in the call stack, the program will terminate abnormally.
The JVM will print an error message (stack trace) indicating the type of exception and where it occurred.

7.5 What is the difference between Error and Exception?


• Error: Represents serious problems that a reasonable application should not try to recover from.
They usually indicate system-level issues (e.g., OutOfMemoryError, StackOverflowError).
• Exception: Represents conditions that a program might try to catch and handle. They are typically
caused by programming errors or external factors.
Generally, you should not try to catch Errors. Handle Exceptions to make your program more robust.

7.6 What is the difference between throw and throws?


• throw: Used to explicitly throw an exception. You create an exception object and then use throw to
throw it. (e.g., throw new IOException("File not found");)
• throws: Used in a method declaration to indicate that the method might throw a checked exception. It
tells the caller of the method that they need to handle the exception. (e.g., public void readFile()
throws IOException ... ;)

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 Multithreading & Concurrency


8.1 What is multithreading in Java?
Multithreading is a feature in Java that allows multiple threads (lightweight sub-processes) to execute concur-
rently within a single program. This enables parallel execution of different parts of the program, improving
performance and responsiveness, especially for tasks that can be divided into independent subtasks.

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.

8.3 What are the different thread states in Java?


A thread can be in one of several states during its lifecycle:

• 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.

8.4 What is the synchronized keyword, and how does it work?


The synchronized keyword is used to control access to shared resources in a multithreaded environment. It
ensures that only one thread can access a synchronized block or method at a time, preventing race conditions
and data corruption. synchronized works by using locks (intrinsic locks or monitor locks) associated with
objects or classes.

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.

8.6 What is the difference between notify(), notifyAll(), and wait()?


These methods are used for thread communication and synchronization:

• 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.

• notify(): Wakes up a single thread that is waiting on the object’s monitor.


• notifyAll(): Wakes up all threads that are waiting on the object’s monitor.

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

• Date and Time API improvements


• Nashorn JavaScript engine
• Parallel array sorting

9.2 What is a lambda expression in Java?


A lambda expression is an anonymous (unnamed) function. It’s a concise way to represent a method that
can be passed as an argument to another method or stored in a variable. Lambda expressions are often used
to implement functional interfaces. They have the syntax (parameters) -> expression or (parameters)
-> { statements; }.

9.3 What is a functional interface in Java?


A functional interface is an interface that has exactly one abstract method. Functional interfaces can be
used with lambda expressions and method references. The @FunctionalInterface annotation can be used
to mark an interface as functional, but it’s not strictly required.

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.5 Explain the map(), filter(), and reduce() operations in Java 8.


These are common stream operations:
• map(): Transforms each element of the stream into another element. (e.g., converting a stream of
strings to a stream of their lengths).
• filter(): Keeps only the elements of the stream that satisfy a given condition (predicate).
• reduce(): Combines the elements of the stream into a single value using a binary operation (e.g.,
summing all numbers in a stream).

9.6 What is the purpose of the Optional class in Java?


The Optional class is used to represent a value that may or may not be present (null). It helps avoid
NullPointerExceptions by explicitly handling the case where a value might be absent. It forces you to
check if a value is present before using it.

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.

9.8 What is a default method in interfaces?


A default method is a method defined in an interface that provides a default implementation. It allows you
to add new methods to an interface without breaking existing classes that implement the interface. Classes
that implement the interface can choose to override the default method or use the default implementation.

9.9 What is the significance of the forEach() method in Java 8?


The forEach() method is a terminal operation in the Stream API that allows you to iterate over the elements
of a stream and perform an action for each element. It provides a more concise and functional way to loop
through a collection.

9.10 What are method references in Java 8?


Method references are a shorthand way to refer to a method without explicitly writing a lambda expression.
They can be used to refer to static methods, instance methods, or constructors. They can make code more
readable when a lambda expression simply calls an existing method. Examples:
• ClassName::staticMethod (e.g., Integer::parseInt)
• object::instanceMethod (e.g., myList::size)
• ClassName::new (constructor reference)

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.

10.2 What is IOC, dependency injection, and how is it implemented in Spring?


• Inversion of Control (IoC): A design principle where the framework controls the creation and
management of objects (beans), rather than the application code.
• Dependency Injection (DI): A specific form of IoC where dependencies (other objects) are provided
to an object, rather than the object creating its own dependencies.

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.

10.3 What is the difference between @Component, @Repository, @Service, and


@Controller annotations?
These annotations are used to mark classes as Spring beans and also provide semantic meaning:

• @Component: A generic stereotype annotation for any Spring-managed component.


• @Repository: Indicates a data access repository (DAO). Provides exception translation for database
operations.
• @Service: Indicates a service component (business logic).
• @Controller: Indicates a controller component in Spring MVC, handling web requests.
• @RestController: A combination of @Controller and @ResponseBody. It’s used for building REST-
ful APIs.

10.4 What is a Spring Bean and its lifecycle?


A Spring bean is an object that is managed by the Spring IoC container. The bean lifecycle typically involves:

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).

10.5 What is the use of @Autowired?


The @Autowired annotation is used for dependency injection. It tells Spring to automatically wire (inject)
the required dependency into the field, constructor, or setter method.

10.6 What is AOP (Aspect-Oriented Programming) in Spring?


AOP is a programming paradigm that allows you to modularize cross-cutting concerns, such as logging,
security, and transaction management. These concerns are often scattered throughout the codebase, making
it difficult to maintain. AOP allows you to define these concerns as aspects, which are then woven into the
appropriate parts of the application.

10.7 What is the difference between @Controller and @RestController?


• @Controller: Used for traditional Spring MVC controllers that typically return views (HTML pages).
• @RestController: Used for building RESTful APIs. It automatically serializes the return value of the
controller methods into JSON or XML and sends it as the response body. It combines @Controller
and @ResponseBody.

10.8 What is Spring Boot, and how is it different from Spring?


Spring Boot is a framework built on top of the Spring Framework. It simplifies the development of Spring
applications by providing:

• Auto-configuration: Automatically configures Spring beans based on dependencies and settings.


• Embedded servers: Includes embedded servers (Tomcat, Jetty, Undertow) for easy deployment.
• Production-ready features: Provides features like metrics, health checks, and externalized config-
uration.

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy