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

Java Oop Complete Notes

The document provides comprehensive notes on Java Object-Oriented Programming (OOP), covering key concepts such as objects, memory storage (Heap and Stack), and differences between JRE, JVM, and JDK. It explains the significance of the main() method, the execution order of a Java program, and various OOP principles including encapsulation, polymorphism, and method overloading/overriding. Additionally, it discusses abstract classes, interfaces, constructors, exception handling, and file handling in Java.

Uploaded by

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

Java Oop Complete Notes

The document provides comprehensive notes on Java Object-Oriented Programming (OOP), covering key concepts such as objects, memory storage (Heap and Stack), and differences between JRE, JVM, and JDK. It explains the significance of the main() method, the execution order of a Java program, and various OOP principles including encapsulation, polymorphism, and method overloading/overriding. Additionally, it discusses abstract classes, interfaces, constructors, exception handling, and file handling in Java.

Uploaded by

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

JAVA OOP COMPLETE NOTES

What is an object?

An object in Java is a real-world entity that represents an instance of a class.


A class is a blueprint, and an object is the actual thing created from that blueprint.
An object has state (attributes/fields) and behavior (methods/functions).

For example:
class Car {
String color;
int speed;

void drive() {
[Link]("Car is driving");
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car(); // object created
[Link] = "Red";
[Link] = 120;

[Link]([Link]); // prints Red


[Link](); // prints Car is driving
}
}
Car → Class (blueprint)
myCar → Object (instance of Car)
color and speed → State
drive() → Behavior
So, an object is the runtime entity in Java that occupies memory and interacts with other objects.

------------------------------------------------------------------------------------------------------------
Explain how objects are stored in memory (Heap & Stack in JVM)?
In Java, when we create an object, memory is divided mainly into Stack and Heap areas:
1. Stack Memory (Method Stack)
Stores method calls, local variables, and references (pointers) to objects in heap.
Stack is thread-specific (each thread has its own stack).
Memory is automatically managed → when a method ends, its stack frame is removed.
Example:
Car myCar = new Car();
Here, the reference variable myCar is stored in the Stack.

2. Heap Memory
Stores actual objects and instance variables.
Heap is shared among all threads.
Garbage Collector (GC) runs on Heap memory to clear unused objects.
In the example, new Car() creates the actual object in the Heap.

3. Visualization
Stack (method memory) Heap (shared memory)
-------------------- ---------------------
myCar -----> -----------------> [Car object]
(reference) color = null
speed = 0
drive() method code

The reference variable (myCar) lives in Stack.


The object itself lives in Heap.
✅ Key point to remember in interviews:
Stack = stores references + local variables
Heap = stores objects
Garbage Collector cleans Heap, not Stack.
------------------------------------------------------------------------------------------------------------
difference between JRE and JVM and JDK
Nice one 👍 — let’s clear this up step by step.
---

## 🔹 *JRE vs JVM*

### *1. JVM (Java Virtual Machine)*

* *Engine* that executes Java bytecode (.class files).


* Converts bytecode → *machine code* specific to your OS.
* Handles:
* Execution (interpreter + JIT compiler)
* Memory management (Heap, Stack, Garbage Collection)
* Security (bytecode verification).
* *It does not provide libraries or tools by itself.*

👉 JVM = The *runner* of Java programs.

--
### *2. JRE (Java Runtime Environment)*
* Provides everything needed to *run* Java programs.
* Contains:
* *JVM* (to run bytecode)
* *Core class libraries* (e.g., [Link], [Link], [Link], etc.)
* Supporting files (like property files, resources).
* Does *NOT* include development tools like javac.

👉 JRE = JVM + Libraries → *Environment to run programs*.


---
DK (Java Development Kit)
JDK = JRE + Development tools (compiler javac, debugger, etc.).
Needed by developers to write, compile, and run Java programs.

Contains:
JRE
javac (compiler)
Debugger, Documentation tools, etc.
👉 Developers install JDK to build Java apps.
## 🔹 Key Differences

| Feature | JRE (Java Runtime Environment) | JVM (Java Virtual Machine) |


| ---------------------- | ------------------------------------- | ------------------------------------- |
| *Definition* | Provides environment to run Java apps | Engine that executes Java bytecode
|
| *Contains* | JVM + class libraries | Only the execution engine |
| *Purpose* | To provide runtime environment | To convert bytecode into machine
code |
| *Can run alone?* | ✅ Yes, can run Java programs | ❌ No, needs JRE and libraries |
| *Development tools?* | ❌ No (only for running) | ❌ No |

---

### 🔹 Example
1. You write [Link] and compile with *JDK* → produces [Link].
2. To run [Link]:
* *JRE* provides JVM + libraries.
* *JVM* actually executes the bytecode.

---
✅ *In short:*

* *JVM* = Virtual machine that executes bytecode.


* *JRE* = JVM + libraries → provides the runtime environment to run Java apps.

4,Why main() cannot be private:


JVM needs access to main()
When we run a program, the JVM looks for the method:
public static void main(String[] args)
If main() is private, JVM (which is outside your class) cannot access it, since private methods are
accessible only within the same class.
Program won’t start
The compiler won’t complain if you write private static void main, but at runtime JVM throws:
Error: Main method not found in class ...
That means the JVM is unable to call the method.
Why public is needed
Declaring main() as public ensures that JVM, which is an external program, can access and
invoke it.
🔹 Example:
class Test {
private static void main(String[] args) {
[Link]("Hello World");
}
}
Compilation: ✅ (no error)
Execution: ❌
Error: Main method not found in class Test, please define the main method as:
public static void main(String[] args)
✅ In short:
main() must be public so JVM can access it.
If it’s private, the program compiles but won’t run.
--------------------------------------------------------------------------------------------------------

[Link] are OS dependent and Independent?


JVM (Java Virtual Machine)
OS-dependent ✅
Because every operating system has its own implementation of JVM (Windows JVM, Linux
JVM, Mac JVM).
Reason: JVM interacts directly with the OS and underlying machine hardware.
JRE (Java Runtime Environment)
OS-dependent ✅
Since JRE contains the JVM + set of class libraries, it also depends on the OS (because the JVM
inside it is OS-specific).
JDK (Java Development Kit)
OS-dependent ✅
JDK includes JRE and additional tools (compiler javac, debugger, etc.). Since JRE is OS-
specific, JDK also becomes OS-specific.
Java Bytecode (.class files)
OS-independent ✅
Once Java source code is compiled into bytecode (.class file), that bytecode can run on any
machine that has a JVM installed.
This is why Java is called "Write Once, Run Anywhere" (WORA).
✅ Summary:

OS-dependent → JDK, JRE, JVM


OS-independent → Java Bytecode
what happens if we remove static from main function
------------------------------------------------------------------------------------------------------------
🔹 What happens if we remove static from main()?
class Test {
public void main(String[] args) { // ❌ no static
[Link]("Hello World");
}
}
1. Compilation
The code compiles successfully ✅.
Because there’s no rule that main() must be static at compile time.

2. Execution
At runtime, JVM searches specifically for:
public static void main(String[] args)
Since it’s not static here, JVM cannot call it directly (because non-static methods need an
object).
Result: Runtime Error ❌
Error: Main method not found in class Test, please define the main method as:
public static void main(String[] args)
🔹 Why is main() static?
Called by JVM without creating an object
JVM needs to start the program without creating an object of your class.
static methods belong to the class, not to objects, so JVM can directly call it.
Saves memory and time
No object creation overhead just to start execution.
Entry point consistency
Every Java program has the same predictable entry point: public static void main.
✅ In short:
Without static, JVM won’t find the entry point → runtime error.

With static, JVM can directly execute the method without creating an object.
------------------------------------------------------------------------------------------
[Link] happens if we remove string args[]?
ChatGPT said:
Ah, this is another classic Java interview twist! Let’s analyze carefully.
1. Original main method
public static void main(String[] args) {
[Link]("Hello World");
}
JVM looks specifically for a method with this exact signature to start the program.
String[] args allows command-line arguments to be passed.

2. If we remove String[] args


public static void main() {
[Link]("Hello World");
}

Compilation ✅
The code compiles successfully.
Execution ❌
JVM cannot find the expected main(String[] args) method.
Result:
Error: Main method not found in class Test, please define the main method as:
public static void main(String[] args)

3. Why JVM needs String[] args


String[] args is part of the method signature that JVM searches for.
Even if your program doesn’t use command-line arguments, JVM requires this exact parameter
to identify the entry point.

✅ Key point:
public static void main() → won’t run
public static void main(String[] args) → runs successfully
-------------------------------------------------------------------------------------------------------
[Link] the execution order of Java program
ChatGPT said:
Sure! This is a very common question to check program flow understanding in Java. Here’s the
detailed execution order of a Java program:
1. Class Loading
When you run a Java program, the JVM loads the class containing the main() method.
The bytecode (.class file) is loaded into memory.

2. Static Initialization
Static variables and static blocks are executed in the order they appear in the class.
This happens once when the class is loaded.
class Test {
static int a = 10;
static {
[Link]("Static block executed");
}
public static void main(String[] args) { }
}

Output:
Static block executed
3. Main Method Execution
After class loading and static initialization, JVM calls the main() method.

Execution starts from first line inside main() and proceeds sequentially.
4. Object Creation (if any)
If new keyword is used, objects are created in Heap memory.
During object creation:
Instance variables are initialized (default → explicit → constructor).
Instance initialization blocks are executed.
Constructor code runs
class Test {
int x = 5;
Test() { [Link]("Constructor"); }
public static void main(String[] args) {
Test t = new Test();
}
}

Output:
Constructor

5. Execution of Non-Static Blocks & Methods


Non-static blocks execute during object creation (before constructor).
Methods execute only when called.
6. Program Termination
After main() finishes, JVM cleans up memory (stack frames removed).
Garbage Collector may free objects in Heap later.
7. Summary (Execution Order)
Class Loading → Bytecode loaded
Static variables and static blocks executed

main() method starts execution


Objects created → instance blocks → constructors
Methods executed when called
Program terminates → JVM cleanup

[Link] is a Class?
ChatGPT said:
Sure! Here’s a clear explanation suitable for an interview:
Definition:
A class in Java is a blueprint or template that defines the properties (fields/variables) and
behaviors (methods/functions) of objects.
It does not occupy memory by itself.
Objects are created from the class.
Key Points:
Class = Blueprint
Think of it like a plan for a house. The house itself is the object; the blueprint is the class.
Contains:
Fields/Attributes → store state of an object
Methods/Functions → define behavior
Constructors → initialize objects
Blocks (static/instance) → optional initialization

Syntax Example:
class Car { // class declaration
String color; // field
int speed; // field

void drive() { // method


[Link]("Car is driving");
}

Car(String c, int s) { // constructor


color = c;
speed = s;
}
}

Car → Class name


color, speed → State/Attributes
drive() → Behavior/Method
Car(String c, int s) → Constructor to initialize object
Creating Objects from Class:
Car myCar = new Car("Red", 120); // object created
[Link](); // calling method
Here, myCar is the object created from the class Car.

✅ In short:

Class = blueprint
Object = real-world instance of the class
Classes define structure and behavior, objects store actual data.
------------------------------------------------------------------------------------------------------------
1. Object
Definition
An object is a real-world entity that represents an instance of a class. It contains state (variables)
and behavior (methods).

Uses
 To store real-time data
 To model real-world entities
 To access class methods
 To implement OOP principles

Example
class Car {
String color;
int speed;

void drive() {
[Link]("Car is driving");
}
}

public class Main {


public static void main(String[] args) {
Car c = new Car();
[Link] = "Red";
[Link] = 120;
[Link]();
}
}

2. Abstract Class
Definition
An abstract class is a class that cannot be instantiated and may contain abstract methods
(methods without body) and concrete methods.

Uses
 To provide common base structure
 To achieve abstraction
 To enforce method implementation in subclasses
Example
abstract class Animal {
abstract void sound();

void sleep() {
[Link]("Sleeping");
}
}

class Dog extends Animal {


void sound() {
[Link]("Bark");
}
}

3. Polymorphism
Definition
Polymorphism means “many forms”. It allows one interface to be used for different data types.

Types
1. Compile-time (Method Overloading)
2. Runtime (Method Overriding)

4. Encapsulation
Definition
Encapsulation is wrapping data and methods into a single unit and restricting direct access using
access modifiers.

Uses
 Data hiding
 Security
 Controlled access

Example
class Student {
private int marks;

public void setMarks(int m) {


marks = m;
}

public int getMarks() {


return marks;
}
}

5. Method Overloading
Definition
Method overloading is defining multiple methods with the same name but different parameters.

Example
class Add {
int sum(int a, int b) {
return a + b;
}

double sum(double a, double b) {


return a + b;
}
}

6. Method Overriding
Definition
Method overriding is redefining a parent class method in a child class with same signature.

Example
class Parent {
void show() {
[Link]("Parent");
}
}

class Child extends Parent {


void show() {
[Link]("Child");
}
}
7. Interface
Definition
An interface is a blueprint of a class containing abstract methods (and default/static methods).

Example
interface Shape {
void draw();
}

class Circle implements Shape {


public void draw() {
[Link]("Drawing Circle");
}
}

8. Difference Between Interface and Abstract Class


Feature Interface Abstract Class
Methods Abstract by default Can have abstract & concrete
Variables public static final Any type
Constructor Not allowed Allowed
Multiple Inheritance Yes No

9. Constructor
Definition
A constructor is a special method used to initialize objects.

Example
class Car {
String color;

Car(String c) {
color = c;
}
}
10. Constructor Chaining
Definition
Calling one constructor from another constructor.

Implementation
class Test {
Test() {
this(10);
[Link]("Default Constructor");
}

Test(int x) {
[Link]("Parameterized Constructor");
}
}

11. Copy Constructor


C++ Implementation
class Sample {
int x;
public:
Sample(int a) { x = a; }
Sample(const Sample &obj) {
x = obj.x;
}
};

Java Implementation
Java does not have built-in copy constructor, but we can create manually.
class Sample {
int x;

Sample(int a) {
x = a;
}

Sample(Sample obj) {
x = obj.x;
}
}

Copy constructor is officially supported in C++. In Java, it is manually implemented.

12. Jagged Array


Definition
A jagged array is an array of arrays where each row has different column sizes.

Example
int[][] arr = new int[3][];
arr[0] = new int[2];
arr[1] = new int[4];
arr[2] = new int[3];

13. Exception Handling


Definition
Exception handling is a mechanism to handle runtime errors.

Types
1. Checked Exceptions
2. Unchecked Exceptions

Example
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}

Common Exceptions
 ArithmeticException
 NullPointerException
 ArrayIndexOutOfBoundsException
 FileNotFoundException
 IOException
 ClassNotFoundException
14. File Handling Classes
Important Classes
 File
 FileReader
 FileWriter
 BufferedReader
 BufferedWriter

Example
import [Link].*;

class FileExample {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("[Link]");
[Link]("Hello Java");
[Link]();
}
}

15. Uses of Methods


 Code reusability
 Improves readability
 Reduces complexity
 Enables modular programming
 Supports polymorphism

In Java, exceptions are divided into:


Throwable
├── Error
└── Exception
├── Checked Exceptions
└── Unchecked (Runtime) Exceptions
We’ll focus mainly on common exceptions with examples.
11 Unchecked Exceptions (Runtime Exceptions)
1️⃣
These happen during runtime.
They extend RuntimeException.

1. ArithmeticException
Occurs when dividing by zero.
int a = 10;int b = 0;
[Link](a / b); // ArithmeticException

2. NullPointerException (Very Common ⚠)


When calling method on null object.
String s = null;
[Link]([Link]()); // NullPointerException

3. ArrayIndexOutOfBoundsException
Invalid array index.
int[] arr = {1, 2, 3};
[Link](arr[5]); // ArrayIndexOutOfBoundsException

4. StringIndexOutOfBoundsException
Invalid string index.
String s = "Hello";
[Link]([Link](10)); // StringIndexOutOfBoundsException

5. NumberFormatException
Invalid string to number conversion.
int num = [Link]("abc"); // NumberFormatException

6. ClassCastException
Invalid type casting.
Object obj = "Hello";Integer num = (Integer) obj; // ClassCastException

7. IllegalArgumentException
Method receives wrong argument.
Thread t = new Thread();
[Link](20); // IllegalArgumentException

8. IllegalStateException
Method called at wrong time.
Scanner sc = new Scanner([Link]);
[Link]();
[Link](); // IllegalStateException

22 Checked Exceptions
2️⃣
Compiler forces you to handle them.

9. IOException
File related issues.
FileReader fr = new FileReader("[Link]"); // FileNotFoundException (subclass of IOException)

10. FileNotFoundException
File does not exist.
FileInputStream fis = new FileInputStream("[Link]");
11. SQLException
Database error.
Connection con = [Link]("wrong_url");

12. InterruptedException
Thread interruption.
[Link](1000); // InterruptedException

13. ClassNotFoundException
Class not found at runtime.
[Link]("[Link]");

3 3 Errors (Serious Problems)


⚠3️⃣
Not meant to be handled.

14. StackOverflowError
Infinite recursion.
void test() {
test(); // StackOverflowError
}

15. OutOfMemoryError
Memory exhausted.
int[] arr = new int[999999999];

🧠 Interview Important Ones


Most commonly asked
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
NumberFormatException
IOException
FileNotFoundException
ClassCastException

🎯 Quick Difference

Type Checked Unchecked

Checked Compile-time Must handle

Unchecked Runtime Not mandatory to handle

When people say “read file using buffer” in Java, they usually mean using:
BufferedReader
It reads data efficiently by using an internal buffer instead of reading character-by-character from
disk.

11 Using BufferedReader (Most Common Way)


1️⃣
✅ Example: Reading a Text File
import [Link].*;
public class Main {
public static void main(String[] args) {

try {
BufferedReader br = new BufferedReader(
new FileReader("[Link]"));

String line;

while ((line = [Link]()) != null) {


[Link](line);
}

[Link]();

} catch (IOException e) {
[Link]();
}
}
}

🔍 How It Works
FileReader → Reads file
BufferedReader → Wraps FileReader for fast reading
readLine() → Reads one full line
Returns null when file ends

22 Modern Way (Recommended) – Try With Resources


2️⃣
This automatically closes the file.
import [Link].*;
public class Main {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(
new FileReader("[Link]"))) {

String line;
while ((line = [Link]()) != null) {
[Link](line);
}

} catch (IOException e) {
[Link]();
}
}
}
No need for [Link]() ✔

⚡ Why Use BufferedReader?


Without buffer:
System reads from disk every time ❌ (slow)
With buffer:
Data is read in chunks into memory ✔
Faster
More efficient

📦 If You Want To Read Character By Character


int ch;while ((ch = [Link]()) != -1) {
[Link]((char) ch);
}

📌 For Binary Files (Important)


If reading images, PDFs, etc., use:
BufferedInputStream
Example:
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("[Link]"));

🎯 Interview Tip
If interviewer asks:
"What is difference between FileReader and BufferedReader?"
Answer:
FileReader reads characters directly from file.
BufferedReader uses internal buffer to improve performance.

If you want, I can also explain:

How buffer size works internally


How to write file using BufferedWriter
How to read large files efficiently
You’re building strong core Java fundamentals now 💪
write
Alright 👍 now let’s learn how to write into a file using buffer in Java.
When we talk about writing with buffer, we use:
BufferedWriter
It improves performance by writing data in chunks instead of character-by-character.

1️⃣Writing Text File Using BufferedWriter


✅ Example
import [Link].*;
public class Main {
public static void main(String[] args) {

try (BufferedWriter bw = new BufferedWriter(


new FileWriter("[Link]"))) {

[Link]("Hello World");
[Link]();
[Link]("This is file writing using BufferedWriter.");

} catch (IOException e) {
[Link]();
}
}
}

🔍 What Happens Here


FileWriter → connects to file
BufferedWriter → improves performance
write() → writes text
newLine() → moves to next line
try-with-resources → auto closes file
📌 Append Mode (Important)
If you don’t want to overwrite the file:
BufferedWriter bw = new BufferedWriter(
new FileWriter("[Link]", true));
true → enables append mode ✔

🚀 Writing Using Loop Example


try (BufferedWriter bw = new BufferedWriter(
new FileWriter("[Link]"))) {

for (int i = 1; i <= 5; i++) {


[Link]("Number: " + i);
[Link]();
}

} catch (IOException e) {
[Link]();
}

⚡ Why BufferedWriter?
Without buffer:
Writes to disk frequently ❌
With buffer:
Stores data temporarily in memory ✔
Writes in chunks ✔
Faster ✔

📦 For Binary Files (Images, PDFs)


Use:
BufferedOutputStream bos =
new BufferedOutputStream(
new FileOutputStream("[Link]"));

🎯 Interview Tip
Difference:
FileWriter → basic writing
BufferedWriter → faster writing with buffer
PrintWriter → formatted writing
----------------------------------
END OF DOCUMENT
----------------------------------

You might also like