0% found this document useful (0 votes)
30 views21 pages

Javassss

Uploaded by

equram6
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)
30 views21 pages

Javassss

Uploaded by

equram6
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
You are on page 1/ 21

1. What is Excep on Handling in Java?

Ans: - Excep on handling in Java is a mechanism that allows a program to handle run me errors
in a controlled way. It enables the program to con nue execu ng, rather than crashing when an
error occurs. The main components of Java's excep on handling are:

1. try block: Contains code that might throw an excep on.

2. catch block: Catches and handles the excep on if one occurs.

3. finally block: Executes code a er the try and catch blocks, regardless of whether an
excep on was thrown or not.

4. throw keyword: Used to explicitly throw an excep on.

5. throws keyword: Declares that a method can throw an excep on, signaling to the caller that
it must handle the poten al excep on.

Simple :

Excep on handling in Java is like having a safety net when things go wrong in your program. Imagine
you're ordering something online. You try to enter your payment details (try), but if there's an issue
like your card is declined (catch), the website shows you an error message instead of crashing. No
ma er what happens, the website might show a confirma on screen or suggest trying again later
(finally).

2. OOPS Concepts: Inheritance, Overloading and Overriding, Excep on Handling,


Polymorphism, Abstrac on, this, default, private, public, default class, class, object, method.

Ans: -

1. Inheritance

 Detailed Explana on: Inheritance allows a new class, known as the child or subclass, to
acquire the proper es and behaviors (methods) of an exis ng class, known as the parent or
superclass. This promotes code reusability and a hierarchical classifica on.

 Example:

o Superclass: Vehicle with proper es like speed, fuel, and methods like start(), stop().

o Subclass: Car inherits these proper es and methods, but it can also have addi onal
features like airCondi oning or playMusic().

 Real-life Example: Think of a company where there’s a base employee class with general
a ributes like name and ID. Different types of employees (e.g., Manager, Developer) can
inherit these a ributes and have addi onal ones unique to their role.

2. Overloading

 Detailed Explana on: Method overloading allows a class to have more than one method
with the same name, but different parameters (type, number, or both). The correct method
is chosen based on the arguments passed when the method is called.

 Example:
o void add(int a, int b) for adding two integers.

o void add(double a, double b) for adding two doubles.

o void add(String a, String b) for concatena ng two strings.

 Real-life Example: Think of a restaurant where the same order form can be used to order
different types of food. The form’s fields change depending on what you’re ordering (pizza
vs. pasta).

3. Overriding

 Detailed Explana on: Method overriding occurs when a subclass provides a specific
implementa on of a method that is already defined in its superclass. The subclass method
overrides the parent class method when invoked on an instance of the subclass.

 Example:

o Superclass: Animal has a method makeSound().

o Subclass: Dog overrides makeSound() to bark(), while Cat overrides it to meow().

 Real-life Example: Think of a general rule in a company, like office hours. Different
departments might override this rule based on their specific needs (e.g., the IT department
might have different working hours).

4. Excep on Handling

 Detailed Explana on: Excep on handling allows a program to deal with unexpected
situa ons (errors) gracefully. This ensures that the program doesn’t crash and can either
recover or inform the user about the problem.

 Components:

o try block: Contains code that might throw an excep on.

o catch block: Catches and handles the excep on.

o finally block: Runs code that should execute regardless of whether an excep on
occurred.

 Real-life Example: Imagine booking a flight online. If the payment fails (excep on), the
website shows you an error message and allows you to try again, instead of just crashing.

5. Polymorphism

 Detailed Explana on: Polymorphism allows objects to be treated as instances of their parent
class, even though they may actually belong to different subclasses. It enables one method
to perform different tasks depending on the object it’s ac ng upon.

 Types of Polymorphism:

o Compile- me (Method Overloading): Decided during compile- me.

o Run me (Method Overriding): Decided during run me.

 Example:
o You have a method makeSound(Animal a). Depending on whether a is a Dog or Cat,
it will either bark() or meow().

 Real-life Example: A smartphone charger (method) works with different devices (objects).
Although the charger is the same, it charges a phone, tablet, or smartwatch according to the
specific needs of the device.

6. Abstrac on

 Detailed Explana on: Abstrac on focuses on exposing only the essen al details while hiding
the complex implementa on. It’s like crea ng a simplified model of something.

 Example:

o An ATM class might have methods like withdraw(), deposit(), and checkBalance().
Users don’t need to know how these methods are implemented, just that they exist.

 Real-life Example: When you drive a car, you don’t need to know how the engine works
internally. You just use the steering wheel, pedals, and gears (interface) to drive.

7. this Keyword

 Detailed Explana on: The this keyword in Java refers to the current object in a method or
constructor. It’s commonly used to differen ate between instance variables and parameters
that have the same name.

 Example:

o If a class has an instance variable name, and a method or constructor has a


parameter also named name, you use this.name to refer to the instance variable.

 Real-life Example: Imagine you’re a teacher in a classroom. If you want to refer to yourself,
you say “I” or “this teacher” to make it clear you’re talking about yourself and not someone
else.

8. Access Modifiers: private, public, default

 Detailed Explana on:

o private: The variable or method can only be accessed within its own class.

o public: The variable or method can be accessed from any other class.

o default: (No modifier) Accessible only within the same package.

 Real-life Example:

o Private: Your personal bank account details are private and only accessible to you.

o Public: A public park is accessible to everyone.

o Default: An apartment building might have a shared garden that’s accessible only to
residents.

9. Class
 Detailed Explana on: A class is a template or blueprint that defines what an object’s
proper es and behaviors will be. It’s a way to group related variables (a ributes) and
func ons (methods) together.

 Example:

o A Car class might have proper es like color, model, speed and methods like
accelerate(), brake().

 Real-life Example: Think of a class as a house blueprint. It defines what the house will look
like, but you need to build (instan ate) the house (object) based on that blueprint.

10. Object

 Detailed Explana on: An object is an instance of a class. It’s the actual en ty that’s created
from the class blueprint and has the characteris cs defined by the class.

 Example:

o If Car is the class, myCar = new Car() creates an object myCar of type Car. myCar can
have specific values for color, model, and speed.

 Real-life Example: Con nuing the house analogy, if the class is the blueprint, an object is the
actual house built from that blueprint. Each house (object) might look similar but can have
different features like paint color or size.

11. Method

 Detailed Explana on: A method is a func on defined inside a class that describes an ac on
or behavior that an object can perform. Methods can take inputs (parameters), perform
ac ons, and return outputs (or not).

 Example:

o In a Car class, drive() might be a method that increases the car’s speed, and stop()
might be a method that brings the car to a halt.

 Real-life Example: In a washing machine (object), methods would be the different cycles
(wash, rinse, spin) that it can perform.

12. Default Class

 Detailed Explana on: A class without any access modifier is considered a "default" class. It is
accessible only within its own package, meaning that other classes within the same package
can access it, but classes outside the package cannot.

 Example:

o If you create a class Employee without specifying an access modifier, it can be used
by other classes in the same package but not by classes in other packages.

 Real-life Example: Consider a book in a library that is accessible only to members of a


specific club (package). Other members from different clubs (packages) cannot access it.
3. What is Abstrac on? How can we implement it?

Ans:-

What is Abstrac on?

Abstrac on is one of the core principles of Object-Oriented Programming (OOP). It involves


hiding the complex implementa on details of a system and showing only the essen al features
or func onali es to the user. The main idea is to focus on what an object does rather than how it
does it.

Real-Life Example:

Think of a TV remote. When you press a bu on to increase the volume, you don't need to know
how the TV processes that signal internally. You only care about the outcome— the volume
increases. The remote control abstracts away the complex details and provides a simple interface
for you to interact with.

How to Implement Abstrac on in Java?

In Java, abstrac on is implemented using abstract classes and interfaces.

1. Abstract Class:

An abstract class is a class that cannot be instan ated on its own and may contain abstract
methods (methods without a body) as well as regular methods with implementa ons.

 Why use an abstract class? To provide a common base with some default behavior that
other classes can inherit and extend.

 How to Implement:

abstract class Vehicle {

abstract void start(); // Abstract method (no implementa on)

void stop() { // Concrete method

System.out.println("Vehicle stopped.");

class Car extends Vehicle {

@Override

void start() {

System.out.println("Car started.");

}
4. What is a Constructor? Purpose of using a Constructor?

Ans:-

What is a Constructor?

A constructor is like a special setup func on that runs automa cally when you create a new
object from a class. Imagine you're building a toy car (the object), and the constructor is like the
assembly instruc ons that tell you how to put the car together when you open the box.

Purpose of a Constructor

1. Se ng Things Up:

o The main job of a constructor is to get everything ready for the object. It sets the
ini al values for the object’s proper es (like the color or size of the toy car).

o Example:

2. class Car {
3. String model;
4. int year;
5.
6. // Constructor
7. Car(String model, int year) {
8. this.model = model; // Setting the model of the car
9. this.year = year; // Setting the year of the car
10. }
11. }
12.
13. public class Main {
14. public static void main(String[] args) {
15. Car myCar = new Car("Toyota", 2020); // This calls the
constructor
16. System.out.println(myCar.model); // Output: Toyota
17. }
18. }
19.

 

Here, when you create a new Car, the constructor automa cally sets up the car’s model and year.

 Giving Default Values:

 Some mes, you might not have specific details when you create an object. A constructor can
set some default values so that the object is s ll usable.

 Example:

 class Car {
 String model;
 int year;

 // Default Constructor
 Car() {
 this.model = "Unknown"; // Default model name
 this.year = 0; // Default year
 }
 }

 public class Main {
 public static void main(String[] args) {
 Car myCar = new Car(); // Uses the default constructor
 System.out.println(myCar.model); // Output: Unknown
 }
 }

A constructor is a special method in a class that is automa cally used when you create a new
object. Think of it like the setup process when you get a new phone—before you can use it, you
have to set it up (like adding your contacts, Wi-Fi, etc.). The constructor sets up the object so it’s
ready to use.

5. Why is the main method sta c?

Ans:- In Java, the main method is defined as sta c because it needs to be called by the Java
run me without crea ng an instance of the class.

Here’s why:

1. No Object Crea on Needed:

o When you start a Java program, there's no object of the class available yet. The main
method needs to be accessible right away so that the Java Virtual Machine (JVM) can
run the program. If the main method were not sta c, you would need to create an
instance of the class before calling main, which would be a problem since main is the
entry point and there's no code running yet to create that instance.

2. Direct Access:

o sta c methods belong to the class itself, not to any par cular object. This means the
JVM can directly call main without needing to know anything about the objects of
the class. This direct access simplifies the program startup process.

3. Consistency:

o Since the main method is the star ng point for any Java applica on, making it sta c
ensures that it is consistently available and behaves the same way in every class.

Simplified Example:

Imagine you have a factory (the class), and the factory needs to produce the first worker (an
object) to start working. However, to create the first worker, you need someone to turn on the
factory’s power (which would be the main method). If the power switch were inside the factory
and you needed a worker to turn it on, you'd have a chicken-and-egg problem. By making the
power switch accessible without needing a worker (making main sta c), you can start the factory
without needing anyone inside it yet.

Summary:

The main method is sta c so that the JVM can run your program without needing to create an
object of the class first. It allows the program to start directly from the main method, providing a
consistent entry point for all Java applica ons.

6. What is inheritance? How can we achieve mul ple inheritance in Java?

Ans: -

What is Inheritance?

Inheritance is an Object-Oriented Programming (OOP) concept where a new class (called a


subclass or child class) inherits proper es and behaviors (fields and methods) from an exis ng
class (called a superclass or parent class). This allows the child class to reuse the code in the
parent class, reducing redundancy and promo ng code reuse.

Example of Inheritance:

Imagine you have a general blueprint for a vehicle (the parent class). A car and a bike (the child
classes) can inherit the basic characteris cs of the vehicle, like having wheels and the ability to
move, but they can also have their own unique features.

How to Implement Inheritance in Java:

In Java, you use the extends keyword to make one class inherit from another.

// Parent class

class Vehicle {

String brand;

void start() {

System.out.println("Vehicle is star ng");

// Child class

class Car extends Vehicle {

int doors;
void honk() {

System.out.println("Car is honking");

public class Main {

public sta c void main(String[] args) {

Car myCar = new Car();

myCar.brand = "Toyota";

myCar.doors = 4;

myCar.start(); // Inherited method from Vehicle

myCar.honk(); // Method in Car class

System.out.println(myCar.brand); // Output: Toyota

In this example:

 The Car class inherits the start() method and brand field from the Vehicle class.

 The Car class also has its own honk() method and doors field.

Achieving Mul ple Inheritance in Java

Java does not support mul ple inheritance directly with classes. This means you cannot have a
class directly inherit from more than one class. This restric on is in place to avoid complexity and
ambiguity (like the diamond problem) that can arise from mul ple inheritance.

How to Achieve Mul ple Inheritance in Java:

Although Java doesn’t allow a class to inherit from mul ple classes, you can achieve similar
func onality using interfaces. A class can implement mul ple interfaces, allowing you to
"inherit" from mul ple sources.

Example Using Interfaces:


interface Drivable {

void drive();

}
interface Flyable {

void fly();

class FlyingCar implements Drivable, Flyable {

@Override

public void drive() {

System.out.println("Driving on the road");

@Override

public void fly() {

System.out.println("Flying in the sky");

public class Main {

public sta c void main(String[] args) {

FlyingCar myFlyingCar = new FlyingCar();

myFlyingCar.drive(); // Output: Driving on the road

myFlyingCar.fly(); // Output: Flying in the sky

In this example:

 The FlyingCar class implements two interfaces: Drivable and Flyable.

 This allows FlyingCar to have both driving and flying capabili es, simula ng mul ple
inheritance.

Summary:

 Inheritance in Java allows a class to inherit proper es and methods from another class,
promo ng code reuse.

 Mul ple inheritance (inheri ng from more than one class) is not directly supported with
classes in Java to avoid complexity.

 You can achieve mul ple inheritance using interfaces, allowing a class to implement mul ple
interfaces and "inherit" behaviors from all of them.
7. Abstract Class vs Interface.

Ans:-

Abstract Class vs. Interface

Abstract Class:

 What It Is: A special class that can't be used to create objects on its own. It can provide some
methods with code and some without (abstract methods).

 Use When: You have a base class with common features that you want to share among
several other classes.

 Key Points:

o Can have methods with code (concrete methods) and methods without code
(abstract methods).

o Can have fields (variables) and constructors.

o A class can only inherit from one abstract class.

Example:

java

Copy code

abstract class Animal {

abstract void makeSound(); // Method without code

void eat() { // Method with code

System.out.println("Ea ng");

Interface:

 What It Is: A collec on of methods that classes must implement. Interfaces are used to
define a set of rules or capabili es.

 Use When: You need to define methods that mul ple classes can use, regardless of their
hierarchy.

 Key Points:

o Can only define methods (before Java 8) and constants. Since Java 8, interfaces can
also have methods with code (default methods).

o Can’t have fields or constructors (except constants).

o A class can implement mul ple interfaces.

Example:
java

Copy code

interface Swimmable {

void swim(); // Method without code

default void floatOnWater() { // Method with code

System.out.println("Floa ng");

Summary:

 Abstract Class: Use it when you have a base class with some common func onality and fields
that other classes will extend. You can’t create objects from it directly.

 Interface: Use it to define a set of methods that different classes can implement, allowing
mul ple classes to follow the same rules or capabili es.

Interview Answer: "An abstract class is a base class that can provide some common behavior but
cannot be instan ated on its own. It can have both methods with and without implementa ons.
An interface, on the other hand, is like a contract that specifies methods a class must implement,
and since Java 8, it can also include methods with default implementa ons. While a class can
extend only one abstract class, it can implement mul ple interfaces."

8. Excep on hierarchy.?
Ans: -
The excep on hierarchy in Java is structured under the Throwable class, which has two
main branches: Error and Excep on. Error represents severe issues like system failures,
while Excep on includes all excep ons that a program might handle. Under Excep on,
there are Run meExcep on (unchecked excep ons) and checked excep ons like
IOExcep on, which must be handled or declared in the method signature."

9. explain the terms final, finally, finalize().?

Summary:

 final: Keyword to make variables immutable, prevent method overriding, or stop class inheritance.

 finally: Block of code that always executes a er a try block and op onal catch block, used for cleanup.

 finalize(): Method called by the garbage collector to clean up before an object’s memory is reclaimed,
though it’s generally advised to use other resource management techniques.

Interview Answer:
 "final is a keyword used to define constants, prevent method overriding, and prevent inheritance of
classes. finally is a block that ensures certain code runs a er a try block, regardless of whether an
excep on occurs. finalize() is a method used for cleanup before an object is garbage-collected, but it's
less commonly used now due to be er resource management prac ces."

10. Differen ate between Sta c and Constant. ?

Ans:-

Summary:

 Sta c:

o Refers to class-level members (variables and methods) that belong to the class itself and are
shared among all instances.

o Syntax: sta c

 Constant:

o Refers to variables whose values are fixed once assigned and cannot be modified.

o Syntax: final (o en combined with sta c)

Interview Answer:

 "Sta c is used to declare class-level variables and methods that belong to the class itself rather than to
instances. Constant refers to variables that are immutable once assigned and are o en declared as
sta c final to ensure their values remain unchanged and accessible globally."

11. Method, Constructor, this keyword, unchecked excep on, overloading, HashMap,
excep on, catch block, checked and unchecked excep ons.?
Ans:-

1. Method

 Defini on: A block of code that performs a specific task and can be called on objects or classes.

 Usage: Defined within a class, methods can return values, accept parameters, and are used to define
the behavior of objects.

java

Copy code

class Example {

void greet() {

System.out.println("Hello");

2. Constructor

 Defini on: A special method used to ini alize objects when they are created. It has the same name as
the class and no return type.
 Usage: Sets up ini al values for an object's fields.

java

Copy code

class Example {

int value;

Example(int ini alValue) { // Constructor

value = ini alValue;

3. this Keyword

 Defini on: Refers to the current instance of the class. Used to access instance variables, methods, or
constructors from within the class.

 Usage: Helps dis nguish between instance variables and parameters with the same name.

java

Copy code

class Example {

int value;

Example(int value) {

this.value = value; // Refers to the instance variable

4. Unchecked Excep on

 Defini on: Excep ons that do not need to be declared in the method signature. They are usually
run me excep ons.

 Examples: NullPointerExcep on, ArrayIndexOutOfBoundsExcep on.

 Usage: Can be caught at run me but are not required to be caught or declared.

5. Overloading

 Defini on: The ability to define mul ple methods in a class with the same name but different
parameters.

 Usage: Allows methods to perform similar but dis nct tasks based on their parameter lists.

java

Copy code
class Example {

void print(int num) {

System.out.println(num);

void print(String text) {

System.out.println(text);

6. HashMap

 Defini on: A data structure that stores key-value pairs and provides fast lookups.

 Usage: Allows efficient retrieval, inser on, and dele on of elements based on keys.

java

Copy code

HashMap<String, Integer> map = new HashMap<>();

map.put("key", 1);

int value = map.get("key"); // Retrieves value associated with "key"

7. Excep on

 Defini on: An event that disrupts the normal flow of a program’s execu on. Excep ons are objects
that describe an error or unexpected condi on.

 Usage: Handled using try-catch blocks to prevent program crashes.

8. Catch Block

 Defini on: A block of code that handles excep ons thrown by a try block.

 Usage: Catches and processes excep ons to prevent program termina on.

java

Copy code

try {

// Code that might throw an excep on

} catch (Excep on e) {

// Handle the excep on

9. Checked Excep ons

 Defini on: Excep ons that must be either caught or declared in the method signature using the
throws keyword.
 Examples: IOExcep on, SQLExcep on.

 Usage: Used for recoverable condi ons that the program should handle.

10. Checked and Unchecked Excep ons

 Checked Excep ons:

o Must be handled or declared in the method signature.

o Example: IOExcep on.

 Unchecked Excep ons:

o Do not need to be explicitly handled or declared.

o Example: NullPointerExcep on.

Interview Answer:

 "A method is a block of code that performs a task and can be called on objects. A constructor
ini alizes objects and has the same name as the class. The this keyword refers to the current instance
of the class. Unchecked excep ons are run me errors not required to be caught or declared, like
NullPointerExcep on. Overloading allows mul ple methods with the same name but different
parameters. A HashMap stores key-value pairs for efficient lookups. An excep on disrupts normal
program flow and is handled by catch blocks. Checked excep ons must be handled or declared, while
unchecked excep ons do not."

12. Ques ons on Java keywords like final, finally, extend, default, sta c, throw, and throws. ?

Ans:-

final

 Variable: Once you set a final variable, you can’t change its value. It’s like wri ng something in stone.

 Method: A final method can’t be changed by subclasses. Imagine it as a rule that can’t be broken.

 Class: A final class can’t be extended or inherited. It’s like a complete book that can’t be added to.

finally

 Block: The finally block is used a er a try block to run some code no ma er what happens, whether
an error occurred or not. It’s like cleaning up a er a meal, no ma er if you enjoyed it or not.

extend

 Keyword: extend is used when one class wants to use features from another class. It’s like a child
inheri ng traits from a parent.

default

 Method (Java 8 and later): default methods in interfaces provide a basic implementa on. It’s like
having a default se ng that you can use unless you choose to change it.

 Access Modifier: If you don’t specify an access level, default means the member is accessible only
within its own package, kind of like a private club that only certain people can enter.

sta c
 Keyword: sta c means something belongs to the class itself rather than to individual objects of that
class. For example, a sta c method or variable can be used without crea ng an object of the class. It’s
like having a universal se ng or tool that everyone in the class can use.

throw

 Keyword: throw is used to manually create and send an error in your program. Think of it as throwing
a flag to signal that something went wrong.

throws

 Keyword: throws is used in a method’s declara on to indicate that the method might throw certain
types of errors. It’s like pu ng up a warning sign that tells others: “This method might cause
problems, so be ready to handle them.”

These keywords help manage different aspects of Java programming, from handling errors to controlling
how classes and methods are used.

4o mini

Java Basics

1. What are the main features of Java?

o Java is object-oriented, pla orm-independent, simple, secure, and robust. It supports


automa c memory management and has a strong standard library.

2. Explain the difference between JDK, JRE, and JVM.

o JVM (Java Virtual Machine): Runs Java programs. It translates Java bytecode into machine
code.

o JRE (Java Run me Environment): Includes JVM and libraries needed to run Java programs.

o JDK (Java Development Kit): Includes JRE and tools for developing Java programs, like the
compiler (javac).

3. What is the significance of the main method in Java?

o The main method is the entry point of a Java program. It’s where the program starts running.

4. How does Java achieve pla orm independence?

o Java programs are compiled into bytecode, which is run by the JVM. This means the same
bytecode can run on any pla orm with a JVM.

5. What are data types in Java? Explain the difference between primi ve and reference data types.

o Primi ve data types: Basic types like int, char, float, etc.

o Reference data types: These refer to objects, like String, arrays, and custom classes.

Object-Oriented Programming (OOP)

6. What is encapsula on? How is it implemented in Java?


o Encapsula on means hiding the internal state of an object and requiring all interac ons to be
performed through methods. This is done using private variables and public ge er and se er
methods.

7. What is inheritance? How do you implement it in Java?

o Inheritance allows one class to use fields and methods of another class. It’s implemented
using the extends keyword. For example: class Dog extends Animal.

8. Explain polymorphism with examples.

o Polymorphism allows objects to be treated as instances of their parent class. Example: A


method can behave differently based on the object that calls it, like shape.draw() where
shape could be a Circle or Rectangle.

9. What is abstrac on? How do you achieve it in Java?

o Abstrac on hides complex implementa on details and shows only the necessary features. It’s
achieved using abstract classes and interfaces.

10. What is the difference between an abstract class and an interface?

o Abstract class: Can have methods with or without implementa on and can have fields.

o Interface: Can only have method signatures (Java 8+ allows default methods) and no fields.

Classes and Objects

11. How do you create an object in Java?

o Use the new keyword to create an object. For example: Person p = new Person();.

12. What is a constructor? Explain the different types of constructors.

o A constructor ini alizes objects. There are:

 Default constructor: No parameters, provided by Java automa cally.

 Parameterized constructor: Takes parameters to ini alize object fields.

13. What is the difference between this and super keywords?

o this: Refers to the current object.

o super: Refers to the parent class of the current object.

14. What is method overloading and method overriding? Provide examples.

o Overloading: Same method name with different parameters. Example: void add(int a, int b)
and void add(double a, double b).

o Overriding: Redefining a method in a subclass. Example: @Override void display() in a


subclass.

15. How does garbage collec on work in Java?

o Java automa cally deletes objects that are no longer used to free up memory. This is
managed by the garbage collector.

Excep on Handling

16. What is excep on handling? Why is it important?


o Excep on handling deals with errors that occur during program execu on. It helps to manage
and recover from errors gracefully.

17. What are the different types of excep ons in Java?

o Checked excep ons: Must be handled (e.g., IOExcep on).

o Unchecked excep ons: Do not have to be handled (e.g., NullPointerExcep on).

18. How do you handle excep ons using try, catch, finally, and throw?

o try: Block where code that may throw an excep on is placed.

o catch: Block where the excep on is handled.

o finally: Block that executes code regardless of whether an excep on occurs or not.

o throw: Used to manually throw an excep on.

19. What is the difference between throw and throws?

o throw: Used to throw an excep on from a method.

o throws: Used in method signatures to declare that a method may throw excep ons.

20. How can you create a custom excep on in Java?

o Create a new class that extends Excep on or Run meExcep on and add any necessary
constructors or methods.

Java Collec ons Framework

21. What is the Java Collec ons Framework? Name some important interfaces and classes.

o It’s a set of classes and interfaces for working with groups of objects. Key interfaces: List, Set,
Map. Key classes: ArrayList, HashSet, HashMap.

22. Explain the difference between ArrayList and LinkedList.

o ArrayList: Backed by an array, allows fast random access but slow inser ons/removals.

o LinkedList: Uses a doubly-linked list, allows fast inser ons/removals but slow random access.

23. What is the difference between HashMap and TreeMap?

o HashMap: Stores key-value pairs in a hash table. It does not maintain order.

o TreeMap: Stores key-value pairs in a red-black tree. It maintains a sorted order.

24. How does HashSet work? What is the difference between HashSet and LinkedHashSet?

o HashSet: Implements a set using a hash table, does not maintain order.

o LinkedHashSet: Maintains inser on order by using a linked list internally.

25. What is the difference between List, Set, and Map?

o List: An ordered collec on that allows duplicates (e.g., ArrayList).

o Set: A collec on that does not allow duplicates (e.g., HashSet).

o Map: A collec on of key-value pairs (e.g., HashMap).

Mul threading and Concurrency


26. What is mul threading? How is it implemented in Java?

o Mul threading allows mul ple threads to run concurrently. It’s implemented using Thread
class or Runnable interface.

27. What is the difference between a thread and a process?

o Process: An independent program with its own memory space.

o Thread: A lightweight process that shares memory space with other threads in the same
process.

28. Explain the synchronized keyword and its use.

o The synchronized keyword is used to ensure that only one thread can access a resource at a
me, preven ng thread interference.

29. What are Runnable and Callable interfaces?

o Runnable: Used to define a task that can be executed by a thread.

o Callable: Similar to Runnable but can return a result and throw checked excep ons.

30. How do you handle thread synchroniza on and avoid deadlocks?

o Use synchroniza on to control access to shared resources. Avoid deadlocks by acquiring locks
in a consistent order.

Java 8 and Beyond

31. What are lambda expressions? Provide an example.

o Lambda expressions provide a concise way to represent an anonymous func on. Example: (a,
b) -> a + b is a lambda expression for adding two numbers.

32. What is the Stream API? How do you use it?

o The Stream API provides a way to process collec ons of data in a func onal style. Example:
list.stream().filter(x -> x > 10).forEach(System.out::println);.

33. Explain the concept of func onal interfaces.

o A func onal interface is an interface with exactly one abstract method. Example:
@Func onalInterface interface MyFunc on { void apply(); }.

34. What is the Op onal class and how is it used?

o Op onal is a container for values that may or may not be present. It helps avoid
NullPointerExcep on. Example: Op onal<String> opt = Op onal.of("Hello");.

35. What are default methods in interfaces?

o Default methods in interfaces provide a default implementa on. This allows interfaces to be
extended with new methods without breaking exis ng implementa ons.

Miscellaneous

36. What is the final keyword in Java? How is it used with variables, methods, and classes?

o Variable: Cannot be reassigned.

o Method: Cannot be overridden.


o Class: Cannot be subclassed.

37. What is the sta c keyword? How does it differ from instance members?

o Sta c members belong to the class rather than instances. They are shared among all objects.
Instance members belong to a specific object.

38. Explain the concept of this and super keywords with examples.

o this: Refers to the current object. Example: this.name = name;.

o super: Refers to the parent class. Example: super.display();.

39. What are Java annota ons? How are they used?

o Annota ons provide metadata about the code. They can be used for code analysis, compile-
me checking, and run me processing. Example: @Override indicates a method overrides a
superclass method.

40. How do you handle file I/O opera ons in Java?

o Use classes from java.io package like FileReader, FileWriter, BufferedReader, and
BufferedWriter to read from and write to files.

These answers aim to provide clear and straigh orward explana ons of core Java concepts.

You might also like