Top 50 Java QnA
Top 50 Java QnA
- JDK (Java Development Kit): A full development kit that includes tools for developing,
debugging, and running Java applica%ons.
- JVM (Java Virtual Machine): The engine that executes Java bytecode, making Java
plaOorm-independent.
- Primi%ve types: `int`, `byte`, `short`, `long`, `float`, `double`, `char`, `boolean`
- `equals()`: Compares the content (values) of two objects and is usually overridden in
custom classes for value comparison.
- Inheritance: Mechanism for a class to inherit fields and methods from another class.
- Abstrac%on: Hiding complex details and showing only the essen%al features.
Inheritance allows one class to inherit the fields and methods of another class, promo%ng
code reuse. The main types are:
- Mul%level Inheritance: A class inherits from a superclass, which also inherits from
another superclass.
Encapsula%on is the bundling of data and methods within a class. For example, in a `Car`
class, encapsula%on could be used to keep ajributes like `speed` and `fuelLevel` private,
with public methods `accelerate()` and `refuel()` to modify these ajributes safely.
Abstrac%on is the concept of hiding unnecessary details from the user and exposing only
essen%al features. In Java, abstrac%on is achieved using:
- Abstract classes: Classes with abstract methods that are implemented by subclasses.
- Constructors have the same name as the class and no return type.
12. What is a singleton class, and how do you create one in Java?
A singleton class restricts instan%a%on to only one object. To create one, define a private
constructor, a sta%c instance variable, and a public sta%c method that returns the instance.
- `this`: Refers to the current instance of a class, omen used to access class members and
constructors.
- `super`: Refers to the superclass instance, used to call superclass methods and
constructors.
- Method Overloading: Defining mul%ple methods with the same name but different
parameters in the same class.
- Anonymous Inner Class: A class without a name, omen used for short implementa%ons.
16. What is an excep%on, and what are the types of excep%ons in Java?
An excep%on is an event that disrupts normal program flow. Java excep%ons are of two
main types:
- Checked excep%ons: Must be either handled with a `try-catch` block or declared with
`throws` in the method signature.
A `try-catch` block is used to handle excep%ons. Code that may throw an excep%on is
placed inside the `try` block. If an excep%on occurs, it is caught in the `catch` block, where it
can be managed without stopping the program.
The `finally` block contains code that is always executed, regardless of whether an
excep%on was thrown or caught. It is commonly used for cleanup, such as closing files or
releasing resources.
- `throws`: Declares excep%ons that a method can throw, used in the method signature to
indicate poten%al excep%ons.
- Synchronized methods: Lock the en%re method, allowing only one thread at a %me.
- Synchronized blocks: Lock a specific code block or object, giving finer control over
synchroniza%on.
Deadlock occurs when two or more threads are wai%ng on each other to release
resources. It can be prevented by using a consistent order for locking, %meout mechanisms,
or lock avoidance techniques.
The Java Collec%ons Framework is a set of classes and interfaces for storing and
manipula%ng groups of objects, including lists, sets, maps, and queues.
- `ArrayList`: Dynamic array with fast random access but slow inser%ons/dele%ons.
- `LinkedList`: Doubly linked list with efficient inser%ons/dele%ons but slower random
access.
- `TreeSet`: Sorted collec%on with O(log n) %me for opera%ons and maintains ascending
order.
- `HashMap`: Non-synchronized and allows one null key and mul%ple null values.
- `Comparable`: Defines a natural ordering for objects, used for single criteria.
Java 8 introduced Lambda expressions, Stream API, default and sta%c methods in
interfaces, `Op%onal` class, and improved date-%me API.
The Stream API is used to process collec%ons of data in a func%onal style, suppor%ng
opera%ons like filtering, mapping, and reducing, making data processing more efficient.
Memory in Java is allocated in two main areas: the heap and the stack. The heap stores
objects and arrays, while the stack is used for method calls and local variables. Java's
garbage collector automa%cally manages heap memory by reclaiming memory used by
unreachable objects.
The `finalize()` method is called by the garbage collector before an object is destroyed. Its
purpose is to perform cleanup, like closing resources. However, it has limita%ons:
- Stack: Stores method frames, local variables, and references to objects. It has a Last In
First Out (LIFO) structure, and memory is automa%cally reclaimed when a method finishes.
- Heap: Stores objects and arrays. Memory is managed by the garbage collector, and it is
larger and more flexible than stack memory.
40. What are memory leaks in Java, and how can they be prevented?
Memory leaks occur when objects are no longer needed but are s%ll referenced,
preven%ng the garbage collector from reclaiming their memory. They can be prevented by
ensuring that unused objects are dereferenced and using tools like profilers to detect
memory leaks.
The `sta%c` keyword is used to define class-level variables and methods. It means the
member belongs to the class rather than to instances of the class. Sta%c members are
shared across all instances of the class.
The `final` keyword is used to declare constants, prevent method overriding, and prevent
inheritance:
The `vola%le` keyword ensures that a variable's value is always fetched from memory
rather than being cached. It is used in mul%-threaded environments to avoid inconsistent
reads and writes to variables.
45. Explain the difference between `public`, `private`, `protected`, and default access
modifiers.
Serializa%on is the process of conver%ng an object into a byte stream to save it to a file or
transmit it over a network. It is implemented by making the class implement the
`Serializable` interface.
48. How do you read and write a file in Java using `BufferedReader` and `BufferedWriter`?
Example:
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
`RandomAccessFile` allows reading and wri%ng to a file at any posi%on, unlike other file
streams that are sequen%al. It supports both reading and wri%ng data and is omen used for
files that require direct access (e.g., database files).
- `Serializable`: A marker interface that allows an object to be serialized by the Java default
mechanism.
- `Externalizable`: Extends `Serializable` and gives the programmer control over the
serializa%on process by implemen%ng `writeExternal()` and `readExternal()` methods.