0% found this document useful (0 votes)
1 views20 pages

Java Interview

Uploaded by

girishkumartp9
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views20 pages

Java Interview

Uploaded by

girishkumartp9
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA

1. What is Java? James Gosling in 1995 Owned by oracle since 2010

- Java is a high-level, object-oriented programming language developed by Sun


Microsystems (now owned by Oracle). It is platform-independent thanks to the Java
Virtual Machine (JVM), which allows Java programs to run on any device that has the
JVM installed.

-----------------------------------------------------------------------------------------------------------------

2. What is the difference between JDK, JRE, and JVM?


- **JDK (Java Development Kit)**: A software development kit required to develop Java
applications, which includes the JRE and development tools like the compiler (`javac`).

- **JRE (Java Runtime Environment)**: Provides the libraries, JVM, and other
components to run Java applications, but does not include development tools.

- **JVM (Java Virtual Machine)**: An abstract machine that provides a runtime


environment for executing Java bytecode. It is platform-dependent, meaning there are
different JVM implementations for different operating systems.

-----------------------------------------------------------------------------------------------------------------

3. What are the main principles of Object-Oriented


Programming (OOP)?
The four main principles of OOP are:

- **Encapsulation**: Bundling the data (variables) and methods (functions) that into a
single unit, or class. Ex: ATMs i.e we can see account balance by entering pin, but we not able to change
balance data. Because data was protected by private access. we can use getters and setters.
- **Inheritance**: Mechanism where one class inherits the attributes and methods of
another class. Ex: Car inheriting from vehicle i.e common properties like engine, wheels are same for any vehicle.

- **Polymorphism**: The ability of a single function, method, or operator to work in


different ways depending on the context or the ability of an entity to behave in more
than one form depending on the context. Ex: Payment modes: UPI, Credit Card, or cash by using methods.

- **Abstraction**: Hiding the complex implementation details and showing only the
necessary features of an object. Ex: Car Ignition- if we switch on the key, the car gets started is shown,
but what happens internally is hidden because it is not necessary.
-----------------------------------------------------------------------------------------------------------------

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


- **`==`**: Compares primitive types or checks if two object references point to the
same memory location.

- **`.equals()`**: A method used to compare the content of two objects for equality. By
default, it checks for reference equality, but it can be overridden to check for content
equality.

-----------------------------------------------------------------------------------------------------------------

5. What is a constructor in Java?


A constructor in Java is a specialised method that has the same name as the class and
does not have a return type and it is called at the time of object creation. Generally it is
used to initialise the object.

2 Types: Default constructor and parameterised constructor.


No-argument or user-defined constructor and copy constructor.
-----------------------------------------------------------------------------------------------------------------

6. What is the difference between `abstract class` and


`interface` in Java?
- **Answer**:

- **Abstract Class**: A class that cannot be instantiated and can have abstract
(methods without a body) and concrete methods (methods with a body). It is used
when classes share some common behavior.

- **Interface**: A contract that defines a set of methods that a class must implement.
All methods in an interface are abstract (except those with default or static keywords in
Java 8+).

-----------------------------------------------------------------------------------------------------------------

7. What is exception handling in Java? Explain the keywords


`try`, `catch`, `finally`, and `throw`.
- **Exception Handling**: A mechanism to handle runtime errors to maintain the
normal flow of a program.

- **`try`**: Block that contains code that might throw an exception.

- **`catch`**: Block that handles the exception thrown by the `try` block.

- **`finally`**: Block that executes after the `try` and `catch` blocks, regardless of
whether an exception was thrown or not.

- **`throw`**: Keyword used to explicitly throw an exception.


public class ExceptionHandling {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
int res=10/0; //Cause runtime error
[Link]("Result: "+res);
}
catch(Exception e){
[Link]("Error: Divide by zero not allowed...");
}
finally {
[Link]("Finally block gets Executed...");
}
[Link]("Normal flow of program was achieved...");
}
}
-----------------------------------------------------------------------------------------------------------------

8. What is the difference between `ArrayList` and `LinkedList`


in Java?
- **`ArrayList`**: Uses a dynamic array to store elements. It provides fast random
access (O(1)) but slow insertion and deletion (O(n)) operations.

- **`LinkedList`**: Uses a doubly linked list to store elements. It provides faster


insertion and deletion (O(1) when adding/removing at the start or end) but slower
random access (O(n)).

public class ArrayList {


public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> array1 = new ArrayList<>();
//Creation of array list without size
[Link](10);
[Link](1, 20);
[Link](2, 30);
[Link](3, 40);
[Link](2);
[Link]([Link]());
[Link](array1);
[Link]([Link](1)); //To access specific index

LinkedList<String> linkedList = new LinkedList<>();


//Same for linkedlist
}
}
-----------------------------------------------------------------------------------------------------------------
9. What is multithreading in Java?
**Multithreading** is a Java feature that allows concurrent execution of two or more
threads (smaller units of a process) for maximum CPU utilization. It is mainly used to
perform multiple tasks simultaneously within a single program. Threads can be created
by extending the `Thread` class or implementing the `Runnable` interface.

-----------------------------------------------------------------------------------------------------------------

10. What is the `StringBuilder` class in Java? How does it


differ from `String`?
- **`StringBuilder`**: A mutable sequence of characters. Unlike `String`, which is
immutable (cannot be changed once created), `StringBuilder` objects can be modified
without creating new objects. It is faster and more efficient for scenarios where multiple
modifications are needed (e.g., concatenation in a loop).

It is not threadsafe because of no synchronization(faster), where stringBuffer is


threadsafe due to synchronization(Slower).

-----------------------------------------------------------------------------------------------------------------

11. What is the difference between `static` and non-static


methods in Java?
- **Static Methods**: Belong to the class rather than any specific instance. They can be
called without creating an instance of the class and can only access static data (variables
or other static methods). The `static` keyword is used to define them.

Overloading static methods: Allowed.


Overriding static methods: Not allowed; static methods can only be hidden, not
overridden.

- **Non-Static Methods**: Belong to an instance of the class and can access both static
and non-static data. They require an instance of the class to be called.

-----------------------------------------------------------------------------------------------------------------

12. What is the `final` keyword in Java?


The `final` keyword is used to declare constants or to restrict inheritance and method
overriding:

- **`final` Variable**: Value cannot be changed once initialized.

- **`final` Method**: Cannot be overridden by subclasses.


- **`final` Class**: Cannot be sub classed or extended by any other class (e.g., `public
final class MyClass`).

13. What is garbage collection in Java? How does it work?


**Garbage Collection (GC)** is the process by which Java automatically identifies and
discards unused objects to free up memory. The Java Virtual Machine (JVM) has a
garbage collector that runs periodically to clear memory occupied by objects that are no
longer referenced or accessible in the program, helping to prevent memory leaks and
optimize memory usage.

14. What is the difference between `Overloading` and


`Overriding`?
- **Method Overloading**: Defining multiple methods with the same name but
different parameters (different type, number, order) within the same class. It is a
compile-time polymorphism.

- **Method Overriding**: Redefining a method in a subclass that already exists in its


superclass with the same method signature. It is used for runtime polymorphism,
allowing dynamic method dispatch.

15. What is the use of the `transient` keyword in Java?


The **`transient`** keyword is used in Java to indicate that a particular variable should
not be serialized when the object state is serialized. During serialization, the fields
marked as `transient` are skipped, which is useful for fields that are sensitive or
irrelevant for the serialization process.

In Java, the `transient` keyword is used to indicate that a field should not be serialized
when an object is converted into a byte stream. Serialization is the process of converting
an object's state into a format that can be stored or transmitted (e.g., saved to a file or
sent over a network). When a field is marked as `transient`, its value will be ignored
during this process.

### Example of `transient` keyword in Java


Consider the following example:

```java

import [Link].*;

class User implements Serializable {

private static final long serialVersionUID = 1L;

String username;

transient String password;

public User(String username, String password) {

[Link] = username;

[Link] = password;

@Override

public String toString() {

return "Username: " + username + ", Password: " + password;

public class Main {

public static void main(String[] args) {

User user = new User("john_doe", "supersecret");


// Serializing the object

try (ObjectOutputStream oos = new ObjectOutputStream(new


FileOutputStream("[Link]"))) {

[Link](user);

[Link]("Before serialization: " + user);

} catch (IOException e) {

[Link]();

// Deserializing the object

try (ObjectInputStream ois = new ObjectInputStream(new


FileInputStream("[Link]"))) {

User deserializedUser = (User) [Link]();

[Link]("After deserialization: " + deserializedUser);

} catch (IOException | ClassNotFoundException e) {

[Link]();

```

### Explanation:

1. **User class:**

- This class implements `Serializable`, which means its objects can be serialized.

- It has two fields: `username` (a regular field) and `password`, which is marked as
`transient`.

2. **Serialization:**
- The `password` field is marked `transient`, so it will not be saved during serialization.

3. **Output:**

- Before serialization: Both `username` and `password` values are printed.

- After deserialization: The `username` field retains its value, but the `password` field
is `null` because it was not serialized.

### Output of the program:

```

Before serialization: Username: john_doe, Password: supersecret

After deserialization: Username: john_doe, Password: null

```

### Key Points:

- **`transient` fields are not part of the serialized object.**

- When deserializing, transient fields are set to their default values (`null` for objects, `0`
for numeric types, `false` for booleans, etc.).

- This is useful for sensitive data (like passwords) or fields that may not need to be
stored (such as temporary state variables).
JAVA OOPS
1. What are the main principles of Object-Oriented
Programming (OOP) in Java?
The four main principles of OOP are:

- **Encapsulation**: Wrapping the data (attributes) and code (methods) together as a


single unit or class, hiding the implementation details.

- **Inheritance**: Mechanism where one class (child or subclass) inherits properties


and behaviours from another class (parent or superclass).

- **Polymorphism**: The ability of an entity to behave in more than one form, this can
be achieved via method overloading and method overriding.

- **Abstraction**: Hiding the complex implementation details and exposing only the
necessary features or interfaces of an object.

2. **What is the difference between an `interface` and an


`abstract class` in Java?**
- **Answer**:

- **Interface**: A contract that specifies methods that a class must implement.


Interfaces can only have abstract methods (Java 7 and below), default and static
methods (Java 8+), and private methods (Java 9+). A class can implement multiple
interfaces.

- **Abstract Class**: A class that cannot be instantiated and can have both abstract
methods (methods without implementation) and concrete methods (methods with
implementation). A class can extend only one abstract class.

3. **What is method overloading and method overriding?**


- **Answer**:

- **Method Overloading**: A feature that allows a class to have more than one
method with the same name but different parameter lists (different type, number, or
order). It is an example of **compile-time polymorphism**.
- **Method Overriding**: A feature that allows a subclass to provide a specific
implementation of a method that is already defined in its superclass. The method must
have the same name, return type, and parameters. It is an example of **runtime
polymorphism**.

4. **What is encapsulation in Java?**


- **Answer**: **Encapsulation** is the concept of bundling the data (variables) and
methods that operate on the data into a single unit, or class. It restricts direct access to
some of an object's components, which helps to protect the integrity of the data and
ensures it is used only in the intended way. It is achieved using access modifiers like
`private`, `protected`, and `public`.

5. **What is inheritance in Java? Explain with an example.**


- **Answer**: **Inheritance** is a mechanism where a new class (child class) acquires
the properties and behaviors of an existing class (parent class). It allows for code
reusability and the creation of hierarchical relationships.

- **Example**:

```java

class Vehicle { // Parent class

void run() {

[Link]("Vehicle is running");

class Car extends Vehicle { // Child class

void run() {

[Link]("Car is running");

```
Here, `Car` is a subclass that inherits from `Vehicle`.

6. **What is polymorphism in Java? How is it implemented?**


- **Answer**: **Polymorphism** means "many forms" and it allows one interface to be
used for different data types. In Java, polymorphism is implemented in two ways:

- **Compile-time Polymorphism**: Achieved through method overloading.

- **Runtime Polymorphism**: Achieved through method overriding and dynamic


method dispatch.

7. **What is abstraction in Java? How do you achieve it?**


- **Answer**: **Abstraction** is the concept of hiding the complex implementation
details and showing only the essential features of an object. It is achieved in Java using:

- **Abstract Classes**: Classes that contain abstract methods (methods without a


body) and cannot be instantiated.

- **Interfaces**: Define a contract of methods that must be implemented by a class.

8. **What is the `super` keyword in Java?**


- **Answer**: The **`super`** keyword in Java refers to the superclass (parent class) of
the object. It is used to:

- Access methods and variables of the parent class.

- Call the parent class's constructor.

- Example:

```java

class Parent {

void display() {

[Link]("Parent class method");

}
class Child extends Parent {

void display() {

[Link](); // Calls Parent class's method

super( ); //It will call constructor of the super class

[Link]("Child class method");

```

9. **What is a constructor in Java? Can a constructor be


inherited?**
- **Answer**: A **constructor** is a special method that has the same name as the class
and does not have a return type, it is called when an object is instantiated. Constructors
initialize the object’s state.

- **Inheritance of Constructors**: Constructors are not inherited by subclasses.


However, a subclass can call the constructor of its superclass using the `super()`
keyword.

10. **What is the difference between `this` and `super`


keywords in Java?**
- **Answer**: Based on inheritance

- **`this`**: Refers to the current instance of the class. It is used to distinguish


between instance variables and parameters, invoke current class methods, and
constructors.

- **`super`**: Refers to the superclass (parent class) instance. It is used to call the
parent class's methods, access parent class variables, and invoke parent class
constructors.
11. **What is an association in Java? How is it different from
aggregation and composition?**
- **Answer**:

- **Association**: A relationship between two objects, where one object can use or
interact with another. It represents a "uses-a" or "works-with" relationship. Example: A
`Person` works in an `Organization`.

- **Aggregation**: A specialized form of association where one object ("whole") can


contain or reference another ("part") without a strict dependency, meaning the "part"
can exist independently of the "whole." It represents a "has-a" relationship. Example: A
`Mobile` has `Charger`. If the `Mobile` is lost, `Charger` can still exist. Also called as
loosely bounded.

- **Composition**: A stronger form of aggregation where the "part" cannot exist


independently of the "whole." It represents a "part-of" relationship. Example: An `OS` is
the part of `Laptop`. If the `Laptop` is destroyed, the `OS` do not exist.

12. **What is the difference between `public`, `private`,


`protected`, and default access modifiers in Java?**
- **Answer**:

- **`public`**: The member is accessible from any other class.

- **`protected`**: The member is accessible within the same package and by subclasses
in different packages.

- **Default (Package-Private)**: If no access modifier is specified, the member is


accessible only within the same package (not outside the package or in subclasses
outside the package).

- **`private`**: The member is accessible only within the class it is declared in.

13. **What is the use of the `finalize()` method in Java?**


- **Answer**: The **`finalize()`** method is called by the garbage collector just before
an object is removed from memory. It is used to perform cleanup activities, like
releasing resources (e.g., closing files or network connections). However, its use is
discouraged in modern Java development due to unpredictability and performance
issues, and developers are encouraged to use try-with-resources or explicit resource
management instead.

14. **What is a static block in Java? When is it executed?**


- **Answer**: A **static block** is a block of code inside a class that is marked with the
`static` keyword. It is used for static initialization of a class. The static block is executed
when the class is first loaded into memory, before the execution of the main method or
any instance creation. Static blocks are typically used to initialize static variables or
perform setup tasks.

- **Example**:

```java

class Example {

static int value;

static {

value = 10; // Static block to initialize the static variable

[Link]("Static block executed.");

```

15. **What is an inner class in Java? What are its types?**


- **Answer**: An **inner class** is a class defined within another class. It can access all
the members (including private) of its outer class. Inner classes are used to logically
group classes that are only used in one place or to define callback methods, listeners,
etc.

- **Types of Inner Classes**:

- **Member Inner Class**: A non-static class defined inside another class.

- **Static inner Class**: A static class defined inside another class. It cannot access
non-static members of the outer class directly.

- **Local Inner Class**: Defined inside a method or a block of code.


- **Anonymous Inner Class**: A class without a name that is declared and
instantiated in a single statement. Often used for implementing interfaces or abstract
classes in a concise manner.

JAVA ADVANCED CONCEPTS

Here are deeper and more detailed definitions of each topic in Java, along with real-world
usage and examples:

✅1. Packages

Definition:
A package in Java is a container that groups related types (classes, interfaces, enumerations,
and annotations). It provides access protection and namespace management.

Why use it?

 Avoids naming conflicts.


 Organizes code logically.
 Controls access with access modifiers (e.g., public, protected, package-private).

Example:

// File: com/example/util/[Link]
package [Link];

public class Helper {


public static void sayHello() {
[Link]("Hello from Helper class!");
}
}

Use case: In large-scale enterprise applications like an e-commerce site, different modules
(order, payment, user) will be in separate packages.

✅2. Time and Space Complexity

Definition:
These measure algorithm efficiency:

 Time Complexity: How time grows as input increases.


 Space Complexity: How much memory is required.

Common Time Complexities:


 Constant – O(1)
 Linear – O(n)
 Logarithmic – O(log n)
 Quadratic – O(n²)

Example:

// O(n) time, O(1) space


int findMax(int[] arr) {
int max = arr[0];
for (int i : arr)
if (i > max) max = i;
return max;
}

Use case: Optimizing sorting algorithms in financial apps or real-time games.

✅3. Multithreading

Definition:
Multithreading enables concurrent execution of two or more threads, enabling better CPU
utilization and responsive applications.

Java Features:

 Thread class and Runnable interface


 synchronized keyword for thread safety
 ExecutorService for managing thread pools

Example:

class MyTask extends Thread {


public void run() {
[Link]("Running in thread: " +
[Link]().getName());
}
}

Use case:

 Web servers handling multiple clients


 Background operations like file downloads

✅4. Collections and Generics

Collections
Definition:
Part of Java Collections Framework (JCF), it includes interfaces like List, Set, Map and
classes like ArrayList, HashSet, HashMap.

Example:

List<String> fruits = new ArrayList<>();


[Link]("Apple");
[Link]("Banana");

Generics

Definition:
Generics allow writing code with type parameters, improving type safety and code reuse.

Example:

class Box<T> {
T value;
void set(T val) { value = val; }
T get() { return value; }
}

Use case: Ensures type-safe data structures without casting.

✅5. JDBC (Java Database Connectivity)

Definition:
JDBC is an API for connecting Java applications to relational databases, executing SQL
queries, and processing results.

Steps:

1. Load driver
2. Establish connection
3. Create statement
4. Execute query
5. Process results
6. Close connection

 Loaded Driver class into memory, registered with Driver Manager


 Driver Manager establishes connection to the database.
 Create a statement or prepared statement (object) to send SQL queries to database.
 Execute query using ps object
 Process results after retrieval
 Close connection and other resources.
Example:

Connection con = [Link](


"jdbc:mysql://localhost:3306/mydb", "root", "password");
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM users");

Use case: Banking systems, user authentication, inventory management.

✅6. Design Patterns

Definition:
Reusable solutions to common software problems in object-oriented design.

Popular Patterns:

 Singleton: Ensures one instance (e.g., database connection)


 Factory: Creates objects based on input
 Observer: Event-based communication (e.g., GUI listeners)

Singleton Example:

class DBConnection {
private static DBConnection instance;
private DBConnection() {}
public static DBConnection getInstance() {
if (instance == null) instance = new DBConnection();
return instance;
}
}

Use case: Clean code, maintainability, scalability.

✅7. Hibernate

Definition:
Hibernate is an ORM (Object-Relational Mapping) tool that maps Java objects to database
tables using annotations or XML.

Advantages:

 Eliminates boilerplate JDBC code


 Transaction(Either complted or rollback) and lazy loading (Data fetched only when
accessed not immediately)support.
 HQL (Hibernate Query Language)

Example:
@Entity
@Table(name="users")
public class User {
@Id
private int id;
private String name;
}

Use case: CRUD applications, like hospital management systems.

✅8. Spring Framework

Definition:
Spring is a lightweight, modular framework for building Java enterprise applications. It
promotes loose coupling through Dependency Injection (DI).

Loose Coupling: Components are independent of each other.


Dependency Injection: It is a design pattern where the dependencies (objects) are injected
by the framework(like Spring).

Core Modules:

 Spring Core (DI)


 Spring AOP (Aspect-Oriented-Programming)
 Spring MVC (Model-View-Controller)
 Spring JDBC
 Spring Security

DI Example:

@Component
class Engine {}

@Component
class Car {
@Autowired
Engine engine;
}

Use case: Scalable enterprise-level apps like banking, e-commerce.

✅9. Spring Boot

Definition:
Spring Boot is a tool built on top of Spring that auto-configures components, eliminates
boilerplate code, and let us quickly develop microservices.

Features:
 Embedded servers (Tomcat, Jetty)
 Starter dependencies
 Production-ready features (actuator, metrics)

Example:

@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
[Link]([Link], args);
}
}

Use case: Rapid REST API development, cloud-ready microservices.

Would you like a real-world mini project idea using all these technologies like Spring Boot,
Hibernate, JDBC, and multithreading?

You might also like