0% found this document useful (0 votes)
2 views8 pages

Basic Advanced Spring JAVA Interview Questions

Basic Advanced Java Interview Questions. Basic Advanced Java Interview Questions

Uploaded by

urabhishek95
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)
2 views8 pages

Basic Advanced Spring JAVA Interview Questions

Basic Advanced Java Interview Questions. Basic Advanced Java Interview Questions

Uploaded by

urabhishek95
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

Basic java

What are JDK, JRE, and JVM?


- JDK (Java Development Kit): A development environment that includes tools like the compiler
(`javac`), libraries, and the JRE. It is used for developing and running Java programs.
- JRE (Java Runtime Environment): Provides the libraries, Java Virtual Machine (JVM), and
other components necessary to run Java applications. It does not include development tools like
the compiler.
- JVM (Java Virtual Machine): The JVM is the runtime engine that executes Java bytecode. It is
platform-dependent but allows Java to be platform-independent by providing a consistent
execution environment.

Explain Abstraction and Encapsulation?


- Abstraction: Abstraction is the concept of hiding the complex implementation details and
showing only the essential features of an object. In Java, abstraction is typically achieved
through abstract classes and interfaces.
- Encapsulation: Encapsulation is the practice of wrapping the data (variables) and the code
(methods) that manipulate the data into a single unit or class, and restricting access to the
internals of that class. It is typically implemented using access modifiers like `private`,
`protected`, and `public`.

What is Inheritance, Aggregation, and Association?


- Inheritance: Inheritance is an object-oriented principle where one class (child/subclass) inherits
properties and behaviors (fields and methods) from another class (parent/superclass). It allows
for code reuse and establishes an "is-a" relationship.
- Aggregation: Aggregation represents a "has-a" relationship where one class contains
references to another class. It implies a whole-part relationship where the part can exist
independently of the whole.
- Association: Association describes a relationship between two classes where they interact with
each other, but neither owns the other. It can be one-to-one, one-to-many, many-to-one, or
many-to-many.

What is a try-with-resource in Java?


- Try-with-Resource: Introduced in Java 7, the try-with-resource statement is a try block that
automatically closes resources (like files or database connections) after the try block is exited.
Any object that implements `AutoCloseable` can be used as a resource.

Example:
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}

Explain different Java 8 features?


- Lambda Expressions: Allow you to treat functionality as a method argument or to treat code as
data.
- Streams API: Provides a way to process sequences of elements (e.g., collections) in a
functional style.
- Optional: A container class that may or may not contain a non-null value, used to avoid
`NullPointerException`.
- Default and Static Methods in Interfaces: Allows adding new methods to interfaces without
breaking existing implementations.
- New Date and Time API ([Link]): A modern, immutable API for handling dates and times.

Why is String immutable in Java?


- Security: Immutable strings prevent unauthorized access and modifications.
- Performance: Allows for string pooling, which saves memory.
- Thread Safety: Immutable strings can be shared across multiple threads without
synchronization.
- HashCode Caching: The hash code is cached at the time of creation and doesn't need to be
recalculated.

Explain the JVM memory model?


- Heap: Stores objects and class instances. The garbage collector manages memory in the
heap.
- Stack: Stores local variables and partial results. Each thread has its own stack.
- Method Area: Stores class-level data like runtime constant pool, field, and method data,
including static variables.
- Program Counter Register: Holds the address of the current instruction being executed.
- Native Method Stack: Manages native (non-Java) methods used in the application.

Explain Garbage Collection?


- Garbage Collection (GC): An automatic memory management feature in Java that removes
objects no longer referenced to free up memory. The JVM periodically runs the GC process to
reclaim memory from objects that are no longer reachable.
What are exceptions and what is exception handling?
- Exceptions: Events that disrupt the normal flow of a program. They are objects that represent
an error or unexpected condition.
- Exception Handling: The process of responding to exceptions using `try`, `catch`, `finally`, and
`throw` constructs to handle runtime errors gracefully without crashing the program.

Explain Autoboxing and Unboxing?


- Autoboxing: The automatic conversion of primitive types into their corresponding wrapper
classes (e.g., `int` to `Integer`).
- Unboxing: The reverse process where the wrapper class is converted back into its
corresponding primitive type (e.g., `Integer` to `int`).

Example:
```java
Integer obj = 5; // Autoboxing
int num = obj; // Unboxing
```

What is Typecasting? Explain with a Parent-Child inheritance


example.
- Typecasting: Converting one type into another. In inheritance, typecasting can be used to treat
a child class as its parent class (upcasting) or vice versa (downcasting).

Example:
```java
class Parent {}
class Child extends Parent {}

Parent p = new Child(); // Upcasting


Child c = (Child) p; // Downcasting
```

Why is the Java platform independent?


- Bytecode: Java code is compiled into platform-independent bytecode, which is executed by
the JVM. The JVM is platform-dependent, but bytecode can run on any JVM, making Java
platform-independent.
How many ways can we create objects in Java?
- Using the `new` keyword: `ClassName obj = new ClassName();`
- Using reflection: `[Link]("ClassName").newInstance();`
- Using `clone()` method: `ClassName obj2 = (ClassName) [Link]();`
- Using `deserialization`: Reading an object from a byte stream.
- Using `ClassLoader`: `[Link]("ClassName").newInstance();`

What is the Collections framework?


- Collections Framework: A unified architecture for storing and manipulating groups of objects in
Java. It includes interfaces like `List`, `Set`, `Map`, and classes like `ArrayList`, `HashSet`,
`HashMap`.

Explain static, this, and super keyword?


- static: Used to define class-level variables and methods that are shared across all instances.
- this: Refers to the current object instance. Used to differentiate between instance variables and
parameters.
- super: Refers to the parent class's objects. Used to call parent class methods and
constructors.

Explain finally, finalize and final keyword?


- finally: A block used with try-catch to execute code after the try block, regardless of whether an
exception was thrown.
- finalize(): A method called by the garbage collector before an object is destroyed. It is used to
perform cleanup.
- final: A keyword used to declare constants (final variables), prevent method overriding (final
methods), and prevent inheritance (final classes).

Advanced Java

What is Serialization?
- Serialization: The process of converting an object into a byte stream, which can then be saved
to a file, sent over a network, or stored in a database. It allows objects to be persisted and later
reconstructed using deserialization.
Explain the Internal working of a HashMap?
- Internal Working of HashMap:
- Hashing: HashMap uses hashing to store key-value pairs. It calculates the hash code of the
key using the `hashCode()` method and maps it to a bucket index.
- Bucket: A bucket is essentially a linked list where the key-value pairs are stored. If multiple
keys have the same hash code (hash collision), they are stored in the same bucket using a
linked list or a balanced tree (in Java 8+).
- Retrieval: To retrieve a value, the hash code of the key is computed, and the corresponding
bucket is searched. The key is then compared using the `equals()` method to find the correct
value.

What is ConcurrentHashmap?
- ConcurrentHashMap: A thread-safe variant of HashMap introduced in Java 5. It allows
concurrent access to the map, meaning multiple threads can read and write without locking the
entire map. It achieves thread safety by dividing the map into segments and synchronizing only
on those segments.

Difference between ArrayList and LinkedList?


- ArrayList:
- Backed by a dynamic array.
- Better for random access (index-based operations).
- Slower for insertions and deletions in the middle or at the beginning, as elements need to be
shifted.
- LinkedList:
- Backed by a doubly-linked list.
- Better for insertions and deletions, especially in the middle.
- Slower for random access as it requires traversal of nodes.

Difference between Comparator and Comparable?


- Comparable:
- Defined in `[Link]`.
- Used to define the natural ordering of objects.
- The class that needs to be compared implements the `Comparable` interface and overrides
the `compareTo()` method.
- Example: `public int compareTo(Object obj)`
- Comparator:
- Defined in `[Link]`.
- Used to define custom ordering of objects.
- A separate class or an anonymous class can implement the `Comparator` interface and
override the `compare()` method.
- Example: `public int compare(Object obj1, Object obj2)`
What is the default size of ArrayList and HashMap?
- ArrayList: The default initial capacity of an `ArrayList` is 10.
- HashMap: The default initial capacity of a `HashMap` is 16, with a load factor of 0.75.

What are Marker Interfaces and Functional Interfaces?


- Marker Interfaces:
- An interface with no methods or fields. It is used to signal to the JVM or compiler that the
implementing class has some special property.
- Examples: `Serializable`, `Cloneable`.
- Functional Interfaces:
- An interface with exactly one abstract method, used primarily for lambda expressions in Java
8 and later.
- Examples: `Runnable`, `Callable`, `Comparator`.

Explain Classloading in Java and types of classloaders?


- Classloading:
- The process by which the JVM loads classes into memory when they are required for
execution.
- Types of Classloaders:
- Bootstrap ClassLoader: Loads core Java classes from the `[Link]` or bootstrap classpath.
- Extension ClassLoader: Loads classes from the Java Extensions directory (`ext`).
- System/Application ClassLoader: Loads classes from the application classpath defined by
the `CLASSPATH` environment variable.

What are Generics in Java?


- Generics: Introduced in Java 5, generics allow classes, interfaces, and methods to operate on
types of objects specified at runtime, providing type safety. They allow code to be more reusable
and reduce the need for typecasting.

Example:
```java
List<String> list = new ArrayList<>();
[Link]("Hello");
// String str = [Link](0); // No type casting needed
```

How can we create a custom Exception?


- Creating a Custom Exception:
- To create a custom exception, extend the `Exception` class (for checked exceptions) or
`RuntimeException` class (for unchecked exceptions).

Example:
```java
public class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
```

What is the Covariant return type?


- Covariant Return Type: A feature introduced in Java 5, allowing an overridden method to
return a subtype of the return type of the overridden method in the superclass. This provides
more flexibility in returning objects.

Example:
```java
class Parent {
Parent get() {
return this;
}
}

class Child extends Parent {


@Override
Child get() {
return this;
}
}
```

What is Threading?
- Threading: A process that allows concurrent execution of two or more parts of a program
(threads). Threads share the same memory space and can run in parallel, improving the
efficiency and performance of a program.

What are Daemon threads?


- Daemon Threads: Background threads that provide services to user threads. The JVM
terminates daemon threads when all user threads have finished executing. They are typically
used for tasks like garbage collection.

Example:
```java
Thread daemonThread = new Thread(() -> {
// task
});
[Link](true);
[Link]();
```

Difference between start() and run()?


- start():
- Creates a new thread and invokes the `run()` method on the new thread.
- run():
- If called directly, it does not create a new thread but runs in the current thread like a normal
method.

What is the Volatile keyword?


- Volatile Keyword: Used to indicate that a variable's value may be modified by different threads.
Declaring a variable `volatile` ensures that its value is always read from and written to the main
memory, providing visibility and consistency across threads.

Difference between Synchronized method and block?


- Synchronized Method:
- Locks the entire method for the calling object, ensuring that only one thread can execute it at
a time.
- Synchronized Block:
- Locks a specific block of code within a method, allowing more fine-grained control over
synchronization.

Difference between sleep(), wait(), yield()?


- sleep():
- Causes the current thread to pause execution for a specified period, without releasing the
monitor lock.
- wait():
- Causes the current thread to wait until another thread invokes `notify()` or `notifyAll()`,
releasing the monitor lock.
- yield():
- Suggests that the current thread is willing to yield its current use of the CPU but does not
release any locks. The thread scheduler decides whether to yield or not.

You might also like