0% found this document useful (0 votes)
5 views31 pages

OOP (Java)

Uploaded by

codingera01
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)
5 views31 pages

OOP (Java)

Uploaded by

codingera01
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/ 31

🟢 1.

Fundamentals of OOP

• What is OOP?
“OOP, or Object-Oriented Programming, is a programming approach that organizes code using
objects and classes.
A class is like a blueprint, and an object is a real-world instance of that blueprint.
OOP makes it easier to manage and scale programs by grouping related data and functions together.
It is based on 4 key principles:
1. Encapsulation – Hiding internal data and exposing only necessary parts using access modi ers (like private,
public).
2. Abstraction – Hiding complex logic and showing only essential features to the user.
3. Inheritance – Reusing properties and behaviors from one class in another.
4. Polymorphism – One function or object behaving differently in different contexts.
For example, if I have a class Car with a method drive(), I can reuse and modify it in a SportsCar class using
inheritance and overriding.
OOP is widely used in real-world software systems because it promotes reusability, modularity, and
maintainability.”**
• Need for OOP over Procedural Programming
Procedural programming is good for small programs, but when applications get large and complex, it
becomes hard to manage because everything is based on functions and global data.
OOP solves this by organizing code using classes and objects. It makes the code more reusable, maintainable, and
secure. Concepts like encapsulation, inheritance, abstraction, and polymorphism help developers build real-world,
modular, and scalable software.
That’s why OOP is preferred over procedural programming in most large-scale software systems.

• Advantages & Disadvantages of OOP


OOP has many advantages like code reusability, data hiding, modularity,Scalability and
it helps model real-world systems easily. Concepts like inheritance and polymorphism reduce code
duplication and improve exibility.
However, OOP can be complex for small programs,
More time for Execution ,
Requires more memory
and it may require more memory and effort to design. But for large and scalable applications, OOP is very
effective and widely used
• Features of OOP (also called principles or pillars):

◦ Class
A class is a blueprint or template used to create objects.
It de nes what data (variables) and functions (methods) the object will have.
◦ Object
An object is an instance of a class.
It represents a real-world entity created from the blueprint provided by the class.
◦ Encapsulation
Encapsulation is the process of binding data and the methods that operate on that data
into a single unit (a class), and restricting direct access to some parts of the object using access modi ers.
fi
fl
fi
fi
In short:
🔒 "Data hiding + data protection + one unit = Encapsulation"
🎯 Real-Life Example:
🔑 Think of a capsule medicine:
• It has ingredients inside (data)
• It has a protective shell (access control)
• You can take it, but you don’t see or touch what’s inside
That’s Encapsulation!

◦ Abstraction
Abstraction means showing only the important parts of an object and hiding the
unnecessary details.
🧠 Focus on "what it does", not "how it does it."
🎯 Real-Life Example:
When you:
• Use a mobile phone, you just tap to call — you don’t see the wiring, signal processing, etc.
• That's abstraction: You see only features, not the complex internal code.

◦ Inheritance
Inheritance is an OOP concept where one class (child or derived class) inherits the
properties and behaviors (data and methods) of another class (parent or base class).
🔑 In Short:
• It allows reusing code from one class into another.
• The child class can use, modify, or extend the functionality of the parent class.
• It helps achieve code reusability and a logical hierarchy.
🎯 Real-Life Example:
Think of a Parent and Child:
• Parent has some features (like surname, property).
• Child inherits them, and can also have own features.
Just like that — in code:
• Parent class = common logic
• Child class = inherits + adds more
◦ Polymorphism
Polymorphism means More than one form of an object
One person can behave differently based on the situation or role they are in.
• When he is in college → he behaves as a Student
• When he is at home → he behaves as a Son
• When he is at a part-time job → he behaves as an Employee
• When he’s playing cricket → he’s a Player

🟢 2. Class and Object Concepts

• De ning classes, Creating objects

✅ Class in Java
class Student {
String name;
fi
int rollNo;

void showDetails() {
System.out.println("Name: " + name);
System.out.println("Roll No: " + rollNo);
}
}

public class Main {


public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Amit";
s1.rollNo = 101;
s1.showDetails();
}
}
• Access modi ers (private, public, protected)
🎯 Real-Life Analogy:
Imagine a house:
• Public = Main door → Anyone can enter
• Protected = Bedrooms → Family members can enter
• Private = Locker → Only you can open

✅ Summary Table for Interviews:


Access Same Same Subclass (diff Other
Modi er Class Package pkg) Packages
public ✅ ✅ ✅ ✅

protected ✅ ✅ ✅ ❌

default ✅ ✅ ❌ ❌

private ✅ ❌ ❌ ❌

✅ Access Modi ers in Java


Java also uses public, protected, private keywords:
✅ Example:
class Student {
public String name = "Amit"; // Public
protected int age = 20; // Protected
private int marks = 90; // Private

public void show() {


System.out.println("Marks: " + marks); // ✅ Private inside class
}
}

public class Main {


public static void main(String[] args) {
Student s = new Student();
System.out.println(s.name); // ✅ Public
System.out.println(s.age); // ✅ Protected (same package)
// System.out.println(s.marks); // ❌ Private - Error
s.show(); // ✅ Works via method
}
}

• Constructors
fi
fi
fi
A constructor is a special method that is automatically called when an object is created.
It is used to initialize the object’s data members (like name, age, etc.).

✅ Java
🔹 Default Constructor
If you don’t de ne any constructor, Java gives you a default one automatically.
class Student {
String name;
int age;
Student() {
name = "Default";
age = 0;
}
}
🔹 Parameterized Constructor
Student(String n, int a) {
name = n;
age = a;
}
🔹 Copy Constructor (manual in Java)
Student(Student s) {
this.name = s.name;
this.age = s.age;
}

• Destructor (C++)
A Destructor is a special method that is called automatically when an object is destroyed.
It is used to clean up memory or release resources (like les, network, database)
🧠 Why is it needed?
Imagine you're opening a le in your program. Once the work is done, you must close it to avoid memory leaks.
👉 Destructor handles that automatically when the object is deleted.

• Static members (variables and functions)


Static members are variables or methods that belong to the class itself, not to individual objects.
Static variable → Same for all objects of the class.
Static method → Can be used without creating an object

🔹 There are 2 types of static members:

Type Meaning

Static Variable One copy shared across all objects

Static Method Can be called using class name, no self/this

✅ . Static Members in Java


In Java, use the static keyword for both variables and methods.
🔹 Example:
class Student {
static String schoolName = "ABC School"; // Static variable

static void showSchool() { // Static method


System.out.println("School: " + schoolName);
}
}

public class Main {


public static void main(String[] args) {
fi
fi
fi
System.out.println(Student.schoolName); // ✅ Access static variable
Student.showSchool(); // ✅ Call static method
}
}
🧠 Output:
ABC School
School: ABC School

• this pointer
✅ Java: this keyword
🔹 Example:
class Student {
String name;

Student(String name) {
this.name = name; // 'this' refers to current object
}

void show() {
System.out.println("Name: " + this.name);
}
}

public class Main {


public static void main(String[] args) {
Student s = new Student("Amit");
s.show();
}
}

🤝 Summary Table:

Language Keyword Use Example

Python self self.name = name


C++ this this->name = name
Java this this.name = name

• Final keyword (Java)


The final keyword in Java is used to make something unchangeable.
It can be applied to:
1. Variables
2. Methods
3. Classes
💡 Think of final like a lock:
Once something is marked final, you can’t change it or override it.

🔹 1. final Variable
👉 You cannot change the value after assignment.
final int age = 18;
age = 20; // ❌ Error: Cannot assign a value to final variable
Real life example:
If your birth year is nal → it never changes.

🔹 2. final Method
👉 You cannot override it in a subclass (child class).
class Parent {
final void show() {
System.out.println("Hello from Parent");
fi
}
}

class Child extends Parent {


// void show() { } ❌ Error: Cannot override final method
}

🔹 3. final Class
👉 You cannot inherit (extend) it.
final class Car {
void run() {
System.out.println("Car is running");
}
}

// class BMW extends Car { } ❌ Error: Cannot inherit from final class

• Object lifecycle

Stage What happens


1. Creation Object is created using a class
2. Initialization Constructor sets values and runs logic
3. Usage Object does its work using methods/attributes
4. Destruction Object is deleted/cleaned from memory

🟢 3. Encapsulation

• What is encapsulation?
Encapsulation means binding data and methods together into one unit (a class), and hiding
internal details from the outside.

🎯 Key Points:
• Keeps data safe from outside access.

• Only allows access using getters and setters.

• It's like putting data in a box and giving limited access.

🧠 Real-Life Example:
Think of a bank ATM:

• You enter a PIN to withdraw money → ✅ Valid way

• You can't directly open the ATM machine → ❌ Not allowed


Here:

• Money = Data

• ATM = Class

• PIN method = Getter/Setter

• How to implement it (getters/setters)

🔸 Java: Encapsulation
class Student {
private String name; // private variable
public void setName(String n) { // setter
name = n;
}
public String getName() { // getter
return name;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.setName("Siddhesh");
System.out.println(s.getName());
}
}

• Data hiding
Data Hiding means protecting internal data of a class from direct access by the outside world.

✅ Real-Life Example:

Think of a voting machine:

• You press a button (method)

• But you can’t see or directly change the internal vote count (data)

• Bene ts of encapsulation

1. 🔒 Data Hiding – Protects internal data from direct access


2. 🎮 Control over Data – Use setters/getters to manage how data is used
3. 🔐 Improved Security – Prevents accidental or unauthorized changes
4. 🛠 Easy Maintenance – Internal changes don’t affect other parts of code
5. 🔁 Code Reusability – Well-encapsulated classes can be reused
6. 🧹 Better Code Organization – Keeps code clean and modular
7. 🐞 Easier Debugging – You know exactly where the data changes happen
fi
• Use cases in software design
In real-world software design, encapsulation is used to protect sensitive data like user credentials, nancial records, or
game state by allowing access only through controlled interfaces like getters and setters. This helps maintain security,
structure, and maintainability.
1⃣ Banking Systems
• 🏦 Hide account balance and transaction logic from direct access.
• ✅ Access only via deposit(), withdraw(), getBalance() methods.
• 🎯 Prevents misuse like setting balance directly.
2⃣ Login & Authentication
• 🔐 Hide user passwords (never store or show raw passwords).
• ✅ Access only through authenticateUser() or isPasswordCorrect().
• 🎯 Increases security and protects user data.
3⃣ Medical/Patient Record Systems
• 🩺 Patient health records are private.
• ✅ Only doctors can read/write via de ned methods.
• 🎯 Prevents unauthorized access to sensitive info.
4⃣ E-commerce Applications
• 🛒 Product quantity, pricing, and discounts are managed via methods.
• ✅ Prevents users from directly changing values.
• 🎯 Ensures pricing rules and limits are followed.
5⃣ Game Development
• 🎮 Player health, score, and inventory are private.
• ✅ Controlled access ensures no cheating or direct edits.
• 🎯 Game logic stays consistent and fair.
6⃣ Library Management System
• 📚 Book availability and user history are encapsulated.
• ✅ Only librarians can update book stock via methods.
• 🎯 Keeps the system clean and controlled.
7⃣ API Design (Backend)
• 🛠 Expose only required elds in API response.
• ✅ Keep internal logic hidden inside the backend.
• 🎯 Improves security and clean structure.

🟢 4. Abstraction

• What is abstraction?
“Abstraction is the process of hiding internal details and showing only what is necessary.”
✅ Why is Abstraction Useful?
• To reduce complexity
• To focus on what’s important
• To use things without knowing internal code
🎯 Real-life Examples:
1. Mobile Phone
◦ You press the call button — don't need to know how the signal travels.
3. ATM
◦ You enter the amount — you don’t see the banking logic.
fi
fi
fi
• Abstract classes
An abstract class is a class that cannot be instantiated (you can't create objects of it) and is meant to be inherited by
other classes.
It may contain:
• Abstract methods (no body)
• Normal methods (with body)
An abstract class is like a blueprint. It de nes what should be done, but not how to do it — the child class will de ne the
actual implementation
🎯 Real-Life Example:
Imagine a base class called Animal:
• All animals can make sound, but each one does it differently.
• So Animal class has a method makeSound() but doesn’t de ne how.
• Subclasses like Dog, Cat, Cow will de ne it.
🔹 Java:
abstract class Animal {
abstract void makeSound(); // Abstract method
}
class Dog extends Animal {
void makeSound() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.makeSound();
}
}

• Interface
An Interface is a completely abstract class — it only has method declarations (no body), and no variables (except
constants).
It de nes what a class must do, but not how.
🔹 Java Interface Example:
interface RemoteControl {
void turnOn();
void turnOff();
}

class TV implements RemoteControl {


public void turnOn() {
System.out.println("TV is ON");
}

public void turnOff() {


System.out.println("TV is OFF");
}
}

• Differences: Abstract class vs Interface


fi
fi
fi
fi
fi
Feature Abstract Class Interface

✅ Purpose Partial abstraction (some code + some rules) Full abstraction (only rules, no code)

🏷 Keyword abstract (Java), pure virtual in C++ interface (Java), ABC in Python
🧩 Variables Can have instance variables Only constants ( nal + static) in Java

🧪 Multiple
❌ Not supported in Java (Yes in C++) ✅ Yes, multiple interfaces can be implemented
Inheritance

🏗 Constructors ✅ Yes ❌ No

• Real-life examples of abstraction

1⃣ ATM Machine
2⃣ Mobile Phone
• When to use abstraction
I use abstraction when I want to hide complexity, enforce rules through interfaces or abstract
classes, and create a clear separation between what something does and how it’s done. It helps build
scalable, modular, and maintainable code.

🟢 5. Inheritance

• What is inheritance?
Inheritance is an OOP concept where one class (child) gets the properties and behaviors (data and methods) of
another class (parent).
🎯 Real-Life Example:
👨 Parent Class → Vehicle
• Methods: start(), stop()
🧒 Child Class → Car
• Inherits start() and stop() from Vehicle
• Can also have its own method like openTrunk()

• Types of inheritance:
fi
◦ Single
When a class inherits from only one parent class, it is called Single Inheritance.
✅ Example:

Java:
class Animal {
void speak() {
System.out.println("Animal speaks");
}
}

class Dog extends Animal {}

class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.speak();
}
}
◦ Multilevel
Java:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dog barks");
}
}

class Puppy extends Dog {


void weep() {
System.out.println("Puppy weeps");
}
}

class Main {
public static void main(String[] args) {
Puppy p = new Puppy();
p.sound();
p.bark();
p.weep();
}
}

◦ Hierarchical
Java:
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat meows");
}
}
class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
d.bark();
Cat c = new Cat();
c.sound();
c.meow();
}
}

🔸 Java (using interface):


interface Father {
void farming();
}

interface Mother {
void cooking();
}

class Child implements Father, Mother {


public void farming() {
System.out.println("Farming skills from Father");
}
public void cooking() {
System.out.println("Cooking skills from Mother");
}
}

class Main {
public static void main(String[] args) {
Child c = new Child();
c.farming();
c.cooking();
}
}

• Constructor chaining in inheritance


Constructor chaining means:
When an object of a child class is created, the parent class constructor is called rst, then the child class
constructor.
fi
• Method overriding
When a child class has a method with the same name and parameters as in its parent class, and it rede nes it — that
is called method overriding.

🔁 Key Rule:
• Same method name
• Same number & type of parameters
• In inheritance only
class Animal {
void speak() {
System.out.println("Animal speaks");
}
}
class Dog extends Animal {
@Override
void speak() {
System.out.println("Dog barks");
}
}
class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.speak(); // Output: Dog barks
}
}
• Ambiguity in multiple inheritance
Ambiguity occurs in multiple inheritance when two parent classes have methods or variables
with the same name, and the child class inherits both — so the compiler gets confused about
which one to use.

🟢 6. Polymorphism

• What is polymorphism?
Polymorphism means one name, many forms. It allows the same function or method name to behave differently
depending on the object or input

✅ Polymorphism in Java
• Meaning: The ability of an object to take many forms.

• In simple words: One name, multiple behaviors.

• Helps reuse code and implement OOP concepts.


fi
Types of Polymorphism

1. Compile-Time Polymorphism (Static Polymorphism)


◦ Resolved at compile time.

◦ Achieved by method overloading or operator overloading (Java has limited


operator overloading).

◦ Example:

class MathOp {

◦ int add(int a, int b) { return a + b; }


◦ double add(double a, double b) { return a + b; }
// method overloading
◦ }

2. Runtime Polymorphism (Dynamic Polymorphism)


◦ Resolved at runtime.

◦ Achieved by method overriding (child class provides its own implementation).

Example:

class Animal {

void sound() { System.out.println("Animal makes


sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Dog
barks"); }
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog(); // runtime
polymorphism
a.sound(); // prints "Dog barks"
}
}
▪ Dynamic dispatch
Dynamic Dispatch means the decision of which function to call is made at runtime, not at compile time.
It’s how runtime polymorphism is implemented in object-oriented languages like C++, Java, and Python.

• Rules for overriding (Java)


To override a method, both method name and parameters must match. In Java, we follow strict
access rules and can't override static or nal methods.

🟢 7. Advanced Class Behavior

• Friend function and friend class ()

✅ Answer in Simple Words

• In C++, a friend function can access private and protected members of a class, even
though it is not part of the class.

• In Java, there is no concept of friend function because Java strictly follows


encapsulation and data hiding.

• If one class needs to use data from another class, Java provides alternatives like:

1. Getters and Setters (controlled access).

2. Inheritance (child class uses parent class members).

3. Package-private (default access modi er) – classes in the same package can access
each other’s members if not marked private.

• Abstract and Final classes (Java)

✅ Abstract Class in Java


🎯 De nition:
An abstract class is a class that cannot be instantiated (you can't create objects from it) and may contain abstract
methods (methods without a body).

🔹 When to use?
• When you want to provide a common base with partial implementation.
• To de ne shared behavior, but leave details to child classes.

✅ Syntax:
abstract class Animal {
abstract void sound(); // abstract method (no body)

void sleep() {
System.out.println("Sleeping...");
fi
fi
fi
fi
}
}

class Dog extends Animal {


void sound() {
System.out.println("Bark!");
}
}
🔸 Usage:
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound(); // Bark!
a.sleep(); // Sleeping...
}
}

✅ Final Class in Java


🎯 De nition:
A nal class is a class that cannot be inherited (no subclassing allowed).

🔹 When to use?
• To prevent other classes from modifying or extending your class.
• Common for security or utility/helper classes.

✅ Syntax:
final class MathUtils {
public static int square(int x) {
return x * x;
}
}

// This would cause an error:


// class MyMath extends MathUtils {} ❌

• Anonymous classes (Java)

✅ What is an Anonymous Class?


An anonymous class is a class without a name, used to create a one-time-use object of a class — usually to override
a method or implement an interface quickly.
🎯 When to use?
• When you need to create a class just once.
• To avoid writing a separate class le.
• Common in event handling, callbacks, or thread creation.
🔹 Example 1: Anonymous class implementing an interface
interface Animal {
void sound();
}
public class Main {
public static void main(String[] args) {
Animal dog = new Animal() {
public void sound() {
System.out.println("Bark!");
}
};
fi
fi
fi
dog.sound(); // Output: Bark!
}
}

✅ Generic Method in Java


• A Generic Method is a method that can work with any data type.

• We use type parameters like <T> before the return type.

• It helps in code reusability and type safety (no need to write the same method for int,
String, double, etc.).

🔹 Example

class Test {
// Generic Method
public <T> void printData(T data) {
System.out.println("Data: " + data);
}

public static void main(String[] args) {


Test t = new Test();

t.printData(10); // Integer
t.printData("Hello"); // String
t.printData(12.5); // Double
}
}

🟢 8. Object Relationships

• Is-a relationship (Inheritance)


The IS-A relationship represents inheritance in object-oriented programming.
It means “X is a type of Y”, or a subclass is a specialized form of its superclass.

🎯 Real-life Example:
• A Dog IS-A Animal
• A Car IS-A Vehicle
• A Student IS-A Person
These represent "is-a" relationships because the child class inherits properties of the parent class.

• Has-a relationship (Composition)


A HAS-A relationship means one class contains an object of another class as a member eld.
It represents Composition in OOP — a “whole-part” relationship.

🎯 Real-life Examples:
• A Car HAS-A Engine
• A Library HAS-A Book
• A Student HAS-A Address
🧠 Interview One-liner:
“HAS-A represents composition, where one class contains another class object. For example, a Car HAS-A Engine. It
promotes code reuse and exibility.”

• Uses-a relationship (Association)


A Uses-A relationship means one class uses the functionality of another class, usually by calling its method —
without owning or containing it.
🎯 Real-life Examples:
• A Teacher uses a Pen to write
• A Customer uses a BankAccount to withdraw money
• A Driver uses a Car to drive

• Aggregation vs Composition

🔷 1. Composition (Strong HAS-A)


A part cannot exist without the whole.
The lifetime of the part depends on the whole.
✅ Real-life Example:
• A House has-a Room
If the house is destroyed, the rooms are also gone.

🔶 2. Aggregation (Weak HAS-A)


A part can exist independently of the whole.
The object is passed from outside, and not tightly bound.
✅ Real-life Example:
• A Team has Players, but a Player can exist without a Team.

• Object Dependency
Object dependency means one object depends on another object to do its job.
In simple words:
If Class A uses Class B, then A is dependent on B.
🎯 Real-life Example:
• A Car depends on an Engine

🟢 9. Memory Management

• Stack vs Heap
fl
fi
Feature Stack Heap
Memory used for static memory Memory used for dynamic memory
📦 De nition allocation allocation
⚙ Usage Stores method calls, local variables Stores objects and dynamic variables
⏱ Access Very fast Slower than stack
speed
🔄 Memory Limited and small Larger than stack
size

• Memory allocation of objects


When you create an object, memory is allocated to store its data and methods.
This memory is usually allocated in the heap because objects have a dynamic lifetime.

📦 Where is object memory stored?

Memory
Part Description
Location
Object data Heap Actual data ( elds/attributes) of the object
Object A pointer or reference to the object (variable in
Stack
reference method)

• Dynamic object creation (new/delete in C++, new in Java)


Java:

ClassName obj = new ClassName(); // Object created dynamically

• Garbage Collection (Java)


Garbage Collection (GC) is the process of automatically identifying and deleting unused objects from memory
(Heap), so the memory can be reused.
In short:
🔁 Find + Free = Clean Heap

🎯 Why Garbage Collection?


Without GC:
• You would manually release memory (delete in C++)
• Forgetting it → Memory leaks 💣
With GC:
• The language runtime (JVM or Python interpreter) does it for you ✅
☕ Java Garbage Collection
• Java uses the JVM (Java Virtual Machine) to manage memory.
• JVM checks for objects that have no references and removes them.
🔹 Example:
public class Test {
public static void main(String[] args) {
Test t = new Test(); // Object created
fi
fi
t = null; // No reference → eligible for GC
System.gc(); // Request GC (not guaranteed)
}
protected void finalize() {
System.out.println("Object destroyed");
}
}
📌 Key Points:
• System.gc() is just a request.
• finalize() method is called before object is deleted.
• Actual GC timing is controlled by JVM.

🟢 10. Exception Handling


Exception Handling is a way to detect, handle, and recover from errors (called exceptions)
during program execution — without crashing the program.

🧠 Simple De nition:
“It is a technique to handle unexpected runtime errors in a safe and controlled way.”

🎯 Why use Exception Handling?

✅ Prevent program crash


✅ Show user-friendly error messages
✅ Handle errors like:

• Divide by zero

• File not found

• Network failure

• Invalid input

• try-catch- nally / except


When something goes wrong (e.g., divide by zero, le not found), instead of the program crashing, we handle it using
these blocks.

✅ Java: try-catch-finally
🧾 Syntax:
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle that exception
} finally {
// Code that always runs (even if error happens or not)
fi
fi
fi
}
💡 Example:
public class Main {
public static void main(String[] args) {
try {
int a = 5 / 0; // Error: divide by zero
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("This will always run.");
}
}
}

• throw/throws

🧨 What is throw?
throw is used to actually throw an exception (manually) during program execution.

✅ Syntax:
throw new ExceptionType("message");
🔹 Example:
public class Main {
public static void main(String[] args) {
int age = 15;
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
System.out.println("Eligible to vote");
}
}

📢 What is throws?
throws is used in method signature to declare that a method might throw an exception.
✅ Syntax:
returnType methodName() throws ExceptionType1, ExceptionType2 {
// code
}
🔹 Example:
public class Main {
static void checkFile() throws IOException {
throw new IOException("File not found");
}

public static void main(String[] args) {


try {
checkFile();
} catch (IOException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
• Custom Exception classes
A custom exception is a user-de ned error type — you create it when existing exceptions (like
ArithmeticException, FileNotFoundError) don't describe the speci c error your app needs.

☕ Java: Custom Exception


✅ How to create:
1. Extend the Exception (checked) or RuntimeException (unchecked) class.
2. Add a constructor.
🔹 Example:
class AgeException extends Exception {
AgeException(String message) {
super(message);
}
}

public class Main {


public static void main(String[] args) {
try {
int age = 15;
if (age < 18) {
throw new AgeException("You must be 18+");
}
} catch (AgeException e) {
System.out.println("Custom Exception: " + e.getMessage());
}
}
}

🟢 11. Language-Speci c OOP Concepts


• Static block
A static block in Java is a block of code that runs once, when the class is loaded, even before the main() method
or any object is created.
🧾 Syntax:
class Example {
static {
System.out.println("Static block executed!");
}

public static void main(String[] args) {


System.out.println("Main method executed!");
}
}
🖨 Output:
Static block executed!
Main method executed!

• Super & this

🔹 super Keyword
🔸 Refers to the parent (super) class — used in inheritance.
✅ Use cases:
1. To call parent class constructor.
2. To access parent class variables or methods.
fi
fi
fi
🧾 Simple Example:
class Person {
String name = "John";

void show() {
System.out.println("Person Name: " + name);
}
}

class Student extends Person {


String name = "Siddhesh";

void display() {
System.out.println("Student Name: " + name); // Siddhesh
System.out.println("Person Name: " + super.name); // John
super.show(); // Call parent class method
}
}

📌 super() Constructor Call


class Person {
Person() {
System.out.println("Person constructor");
}
}

class Student extends Person {


Student() {
super(); // Calls parent class constructor
System.out.println("Student constructor");
}
}
🖨 Output:
Person constructor
Student constructor
• Functional interfaces (Java 8+)
Functional Interface in Java is an interface that contains only one abstract method.
🧠 This allows the use of lambda expressions to represent the method implementation.
🔸 Real-World Analogy:
Think of a functional interface as a contract for a single action.
If a class is signing this contract, it must perform exactly one job.
📌 Syntax:
@FunctionalInterface
interface MyFunction {
void doSomething(); // Only one abstract method allowed
}

1. Core Java Basics


1. What is Java? Features?
Java is a high-level, object-oriented programming language. It is platform-independent
because programs run on the JVM (Java Virtual Machine), so the same code can run
anywhere. It is widely used for web apps, desktop apps, and mobile apps.

Main Features of Java:

• Simple – easy to learn and use.

• Object-Oriented – everything is treated as objects.

• Platform Independent – write once, run anywhere.

• Secure – no direct access to memory, has built-in security.

2. Difference between JDK, JRE, JVM.

JDK (Java Development Kit):


👉 It is a software package that we install to develop Java programs.
👉 It contains JRE + development tools like compiler (javac).

JRE (Java Runtime Environment):


👉 It is used to run Java programs.
👉 It contains JVM + libraries, but no compiler.

JVM (Java Virtual Machine):


👉 It is the engine that actually runs the Java bytecode.
👉 It makes Java platform-independent.

3. Explain “Write once, run anywhere”.

👉 We write the Java program only once, and it can run on any operating system without changing
the code.
👉 This is possible because Java code is compiled into bytecode, and the JVM (Java Virtual
Machine) on each OS understands and runs that bytecode.

4. Difference between == and .equals().

== (double equals)

👉 Compares references (memory addresses) for objects.


👉 For primitives, it compares actual values.

Example:

String s1 = new String("Hello");


String s2 = new String("Hello");
System.out.println(s1 == s2); // false (different
objects in memory)
System.out.println(s1.equals(s2)); // true (same content)

.equals() method

👉 De ned in Object class.


👉 By default, it behaves like == (checks reference).
👉 But classes like String, Integer override equals() to check content/value.

5. String vs StringBuilder vs StringBuffer.

String

• Immutable (once created, cannot change).

• Every change creates a new object.

• Example:

String s = "Hello";

• s = s + " World"; // creates a new object

StringBuilder

• Mutable (can change the value without creating a new object).

• Not synchronized → faster, but not thread-safe.

• Used when frequent changes are needed.

StringBuffer

• Mutable like StringBuilder.

• Synchronized → thread-safe, but slower than StringBuilder.

• Used in multithreaded environments.

Is Java fully object-oriented?


fi
• No, Java is not fully object-oriented.

Reason:

• Because primitive data types (int, char, boolean, etc.) are not objects.

• Everything else in Java (classes, methods, inheritance, polymorphism, encapsulation) is


object-oriented.

• If Java had no primitives and everything was an object, it would be fully OOP, but it uses
primitives for performance reasons.

Internal Process (How Java Program Runs)

1. Write code → MyProgram.java

2. Compile using JDK (javac MyProgram.java) → generates bytecode →


MyProgram.class

3. Run using JVM (java MyProgram) → JVM loads .class le

4. JVM veri es bytecode → interprets or JIT compiles → executes on OS

Java Collections Framework (JCF)

• De nition: A set of classes and interfaces that provide ready-made data structures and
algorithms to store, manage, and manipulate groups of objects.

• Helps avoid writing custom data structures.

• Includes List, Set, Queue, Map, and related utility classes like Collections and
Arrays.

1. List
• Ordered collection (maintains insertion order)

• Allows duplicates

• Access by index

• Examples: ArrayList, LinkedList, Vector

• Use case: Storing a sequence of elements where order matters.

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


list.add("Apple");
fi
fi
fi
list.add("Banana");
list.add("Apple"); // duplicate allowed

2. Set
• Unordered collection (no guarantee of order, except LinkedHashSet)

• No duplicates allowed

• Cannot access by index

• Examples: HashSet, TreeSet, LinkedHashSet

• Use case: Storing unique elements.

Set<String> set = new HashSet<>();


set.add("Apple");
set.add("Banana");
set.add("Apple"); // ignored, no duplicates

3. Map
• Stores key-value pairs

• Keys are unique, values can be duplicate

• No direct iteration over values, access via keys

• Examples: HashMap, TreeMap, LinkedHashMap

• Use case: Associating values with unique keys.

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


map.put(1, "Apple");
map.put(2, "Banana");
map.put(1, "Orange"); // key 1 is updated

1. ArrayList
• Implements: List interface

• Data structure: Dynamic array

• Access time: Fast for random access (O(1) by index)


• Insertion/Deletion: Slower, especially in middle (O(n)) because elements need to be
shifted

• Memory: Less memory overhead

ArrayList<String> list = new ArrayList<>();


list.add("Apple");
list.add("Banana");
System.out.println(list.get(0)); // Apple

2. LinkedList
• Implements: List and Deque interfaces

• Data structure: Doubly linked list

• Access time: Slower for random access (O(n))

• Insertion/Deletion: Fast, especially at start or middle (O(1) if node reference is known)

• Memory: More memory used (each node stores data + pointers to next/previous)

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


list.add("Apple");
list.add("Banana");
list.addFirst("Mango"); // fast insertion at start

1. HashMap
• Stores: Key-Value pairs

• Order: No order (unordered)

• Null keys/values: 1 null key, multiple null values allowed

• Performance: Fast, O(1) for get/put (on average)

• Implementation: Hash table

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


map.put(1, "Apple");
map.put(2, "Banana");

2. TreeMap
• Stores: Key-Value pairs

• Order: Sorted order of keys (ascending by default)

• Null keys: Not allowed

• Performance: Slower, O(log n) for get/put

• Implementation: Red-Black Tree

Map<Integer, String> map = new TreeMap<>();


map.put(2, "Banana");
map.put(1, "Apple"); // automatically sorted

3. LinkedHashMap
• Stores: Key-Value pairs

• Order: Insertion order preserved

• Null keys/values: 1 null key, multiple null values allowed

• Performance: Slightly slower than HashMap

• Implementation: Hash table + linked list

Map<Integer, String> map = new LinkedHashMap<>();


map.put(2, "Banana");
map.put(1, "Apple"); // order maintained

1. HashSet
• Stores: Unique elements (no duplicates)

• Order: No order (unordered)

• Null element: Allowed (1 null element)

• Performance: Fast, O(1) for add, remove, contains (on average)

• Implementation: Hash table

Set<String> set = new HashSet<>();


set.add("Apple");
set.add("Banana");
set.add("Apple"); // ignored, duplicates not allowed
2. TreeSet
• Stores: Unique elements (no duplicates)

• Order: Sorted order (ascending by default)

• Null element: Not allowed

• Performance: Slower, O(log n) for add, remove, contains

• Implementation: Red-Black Tree

Set<String> set = new TreeSet<>();


set.add("Banana");
set.add("Apple"); //
ConcurrentHashMap in Java
• De nition: A thread-safe version of HashMap that allows concurrent read and write
operations without throwing ConcurrentModificationException.

• Package: java.util.concurrent

• Key Feature:

◦ Multiple threads can read and write safely at the same time.

◦ Uses segment locking / bucket-level locking instead of locking the entire map, so
it’s faster than synchronized HashMap.

Example

import java.util.concurrent.ConcurrentHashMap;

public class Main {


public static void main(String[] args) {
ConcurrentHashMap<Integer, String> map = new
ConcurrentHashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");

System.out.println(map.get(1)); // Apple
}
}
1. What is a Servlet?
fi
• De nition: A Servlet is a Java class that runs on a web server and handles HTTP requests
and responses.

• It is part of Java EE (Jakarta EE) and is used to create dynamic web content.

• Extends HttpServlet class and overrides methods like doGet() and doPost(

Servlet Lifecycle in Java


A servlet goes through 3 main methods in its lifecycle: init(), service(), destroy()

1. init()

• Called once when the servlet is rst loaded by the server.

• Used to initialize resources like database connections or con guration.

• Signature:

public void init() throws ServletException

2. service()

• Called for every client request.

• Determines the type of request (GET, POST, etc.) and calls doGet() or doPost().

• Signature:

public void service(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException

3. destroy()

• Called once when the servlet is unloaded or server shuts down.

• Used to release resources like closing DB connections or le streams.

• Signature:

public void destroy()


fi
fi
fi
fi

You might also like