OOPS Using Java Notes
OOPS Using Java Notes
Here are concise, exam-focused notes covering key programming paradigms, Object-Oriented
Programming (OOP), and Java fundamentals:
1. Imperative Programming
• Definition: Focuses on how to perform tasks using statements that change a program's
state.
• Examples: C, Java.
2. Procedural Programming
• Examples: C, Pascal.
• Definition: Organizes software design around data, or objects, rather than functions and
logic.
4. Functional Programming
• Definition: Emphasizes the evaluation of functions and avoids changing states and
mutable data.
5. Declarative Programming
• Definition: Expresses the logic of computation without describing its control flow.
Key Concepts:
• Abstraction: Hiding complex implementation details and showing only essential features.
• Inheritance: Mechanism where a new class derives properties from an existing class.
Features of OOP
Merits of OOP
Demerits of OOP
Applications of OOP
• Real-time systems.
• Game development.
• Platform-Independent: Runs on any device with the Java Virtual Machine (JVM).
Types of Java
• Definition: Provides libraries, Java Virtual Machine (JVM), and other components to run
applications written in Java.
• Definition: A set of pre-written packages, classes, and interfaces for building Java
applications.
Here are detailed, exam-oriented notes on Java Tokens, Program Structure, Data Types,
Type Casting, Variables, and Operators with definitions, features, examples, advantages, and
disadvantages for each topic:
Java Tokens
Definition:
Tokens are the smallest individual units in a Java program.
1. Keywords
• Features:
2. Character Set
• Includes:
o Digits: 0–9
o Unicode support
3. Identifiers
• Rules:
o Case-sensitive.
4. Literals
• Types:
o Integer: 10
o Float: 12.5f
o Character: 'A'
o String: "Hello"
5. Separators
• Examples:
o ; – Statement terminator
o { } – Block delimiters
6. Comments
• Types:
o Single-line: // comment
o Multi-line: /* comment */
System.out.println("Hello, World!");
Structure Includes:
1. Class Definition
2. Main Method
3. Statements
Command-Line Arguments
• Usage Example:
• java Hello 5 10
• Benefits:
• Limitations:
• Character: char
Type Promotion
Type Casting
Example:
double d = 5.5;
int i = (int) d; // i = 5
byte short
Type Promotion Rank
short int
int long
long float
float double
Types of Variables:
Scope:
Types of Operators
Arithmetic +, -, *, /, %
Logical &&, `
Assignment =, +=, -=
Bitwise &, `
Expressions
• Example: a + b * c
Here are detailed, exam-oriented notes on Classes, Objects, Access Modifiers, Methods,
Constructors, this, static, final, and Wrapper Classes with definitions, features, examples,
advantages, and disadvantages:
Concept of Class and Object
Class
• Definition: A blueprint for creating objects. It defines variables and methods common to
all objects of a certain type.
• Syntax:
• class Car {
• String color;
• void drive() {
• System.out.println("Driving...");
• }
• }
• Features:
o Supports reusability.
Object
• Syntax:
• Features:
Access Modifiers
private
(default)
protected
public
• Advantages:
o Encapsulation and control over data access.
• Disadvantages:
Java Methods
Method
• Syntax:
• return a + b;
• }
Method Overloading
• Definition: Defining multiple methods with the same name but different parameters.
• Example:
• Advantages:
• Disadvantages:
Constructor
• Types:
1. Default Constructor:
2. Car() { }
3. Parameterized Constructor:
4. Car(String color) {
5. this.color = color;
6. }
8. Car(Car c) {
9. this.color = c.color;
10. }
• Features:
o No return type.
• Advantages:
o Auto-initialization of objects.
• Disadvantages:
o Cannot be inherited.
this Keyword
• Usage:
• this.name = name;
• Advantages:
o Avoids ambiguity.
• Disadvantages:
static Keyword
Static Variable
Static Method
Static Block
static {
System.out.println("Static Block");
• Advantages:
o Saves memory (used once).
• Disadvantages:
final Keyword
• Used For:
• Advantages:
• Disadvantages:
o Limits flexibility.
Wrapper Classes
int a = 10;
• Advantages:
• Disadvantages:
• 1D & 2D Arrays
• Arrays Class
• Dynamic Arrays
• Syntax:
• Example:
• Syntax:
• Example:
• int[][] table = {
• {1, 2, 3},
• {4, 5, 6}
• };
Features:
Advantages:
Disadvantages:
• Definition: Part of the java.util package that provides utility methods for arrays.
Common Methods:
Method Description
Features:
Advantages:
• Improves readability.
Disadvantages:
• Definition: Arrays whose size can grow dynamically using ArrayList from java.util.
list.add(10);
list.add(20);
Features:
Advantages:
Disadvantages:
Declaration:
String s = "Hello";
Common Methods:
Method Description
Features:
Advantages:
• Thread-safe.
Disadvantages:
StringBuffer Class
• Syntax:
• sb.append(" World");
Features:
• Synchronized (thread-safe).
Advantages:
StringBuilder Class
• Syntax:
• sb.append(" Rocks");
Features:
• Not synchronized.
Advantages:
Disadvantages:
• Not thread-safe.
StringTokenizer Class
• Syntax:
• while (st.hasMoreTokens()) {
• System.out.println(st.nextToken());
• }
Features:
Advantages:
Disadvantages:
Comparison Table
Each topic includes definition, examples, features, advantages, and disadvantages (5 points
each):
Method Overloading
Definition:
Method overloading allows defining multiple methods with the same name but different parameter
lists in the same class.
Example:
class Calculator {
Features:
Advantages:
3. Promotes reusability.
5. Easy to maintain.
Disadvantages:
Method Overriding
Definition:
Example:
class Animal {
Features:
2. Happens at runtime.
5. Supports polymorphism.
Advantages:
4. Encourages extensibility.
Operator Overloading
Not supported in Java (like C++). Java avoids ambiguity and maintains simplicity by not
allowing user-defined operator overloading.
Constructor Overloading
Definition:
Example:
class Box {
Box() { }
Box(int length) { }
Features:
3. Compile-time polymorphism.
4. Enhances flexibility.
Advantages:
4. Cleaner code.
Disadvantages:
1. Increases memory usage if not optimized.
Concept of Inheritance
Definition:
Inheritance allows a class (subclass) to acquire properties and behavior from another class
(superclass).
Example:
class Parent {
void display() { }
void show() { }
Features:
4. Enhances extensibility.
Advantages:
1. Reduces redundancy.
2. Improves maintainability.
4. Facilitates modularity.
5. Increases scalability.
Disadvantages:
Subclass:
Superclass:
Types of Inheritance
1. Single-Level Inheritance
class A { }
class B extends A { }
2. Multi-Level Inheritance
class A { }
class B extends A { }
class C extends B { }
3. Hierarchical Inheritance
class A { }
class B extends A { }
class C extends A { }
interface A { }
interface B { }
class C implements A, B { }
5. Hybrid Inheritance
Used to:
super.display();
1. Final Variable
2. Final Method
• Cannot be overridden.
3. Final Class
• Cannot be inherited.
final class A { }
• Packages in Java
Definition:
• Encapsulation is the process of binding data (variables) and code (methods) into a single
unit (class).
• Data Hiding ensures that internal object details are hidden from the outside world by
declaring variables as private.
Example:
class Student {
private int marks;
if (m >= 0) marks = m;
return marks;
Features:
3. Increases modularity.
Advantages:
4. Supports abstraction.
Disadvantages:
Definition:
• Abstract Class: A class declared with the keyword abstract that cannot be instantiated.
Features:
3. Cannot be instantiated.
Advantages:
Disadvantages:
Interface in Java
Definition:
An interface is a reference type in Java that contains only abstract methods (until Java 7),
default, static (Java 8+), and private methods (Java 9+), with no implementation.
Example:
interface Drawable {
void draw();
}
class Circle implements Drawable {
Features:
Advantages:
5. Improves scalability.
Disadvantages:
Single Interface:
Multiple Interfaces:
Extending Interfaces:
Methods Can have concrete methods Only abstract (Java 7), default/static (Java 8+)
Use Case Base class with some logic Blueprint for complete abstraction
Packages in Java
Definition:
Syntax:
package mypackage;
import java.util.Scanner;
Features:
3. Logical groupings.
Types of Packages
1. Built-in Packages
2. User-defined Packages
• Created by developers.
• Example:
• package myapp;
Creating:
package myutils;
Importing:
import myutils.MathTool;
Advantages of Packages:
2. Improves modularity.
3. Easy to maintain.
4. Reusable code.
Disadvantages:
• Thread Class
• Runnable Interface
• Thread Lifecycle
Multithreading Fundamentals
Definition:
Multithreading is a programming technique that allows the execution of two or more threads
concurrently, enabling more efficient use of CPU resources.
Features:
2. Resource Sharing: Threads share resources such as memory, CPU time, etc.
5. Independent Execution: Threads can run independently but share the same memory
space.
Advantages:
4. Simpler code structure: Allows efficient handling of tasks like I/O operations without
blocking other processes.
5. Real-time processing: Useful in applications like games, real-time systems, and server-
side programming.
Disadvantages:
2. Concurrency issues: Issues like race conditions, deadlocks, and thread synchronization
can occur.
4. Memory consumption: Each thread has its own stack, leading to higher memory usage.
Thread Class
Definition:
The Thread class in Java provides methods to create and control threads. A thread is an instance
of the Thread class or a class that implements the Runnable interface.
Example:
System.out.println("Thread running...");
Features:
1. Thread creation: Extends the Thread class and overrides run() method.
3. Thread state management: Can be in states like new, runnable, blocked, etc.
4. Predefined methods: Methods like sleep(), join(), and isAlive() for thread management.
Advantages:
2. Control over execution: Methods like start(), sleep(), and join() offer better control.
5. Thread pooling: Easily integrates with thread pooling mechanisms for performance
enhancement.
Disadvantages:
1. Cannot inherit from another class: Since Java supports single inheritance, you can't
extend Thread and another class simultaneously.
2. Less flexible: Thread class is less flexible compared to the Runnable interface.
4. Complex error handling: Multithreaded code can be difficult to debug and maintain.
Definition:
The Runnable interface represents a task that can be executed concurrently by a thread. A class
that implements Runnable must override the run() method.
Example:
Features:
1. Implementable by any class: Unlike Thread, any class can implement Runnable.
4. Supports task sharing: Useful when multiple threads execute the same task.
Advantages:
1. Improved design: Allows a clean design where a class can implement multiple interfaces.
2. Resource sharing: Multiple threads can execute the same Runnable task.
4. Avoids multiple inheritance issues: Since a class can implement multiple interfaces.
Disadvantages:
1. More boilerplate: You must create a Thread object to run a Runnable, adding extra
steps.
2. No direct thread management: You don't have direct control over the thread (e.g.,
setting priorities).
3. Increased complexity: Slightly more complex to use than extending Thread.
4. Cannot directly manage thread state: Can't manage thread-specific states directly.
5. No thread state control: Unlike Thread, you cannot control the thread lifecycle or state
directly.
Definition:
A thread's lifecycle defines the various states it goes through during its execution, from creation to
termination.
States:
2. Runnable: The thread is ready to run but the OS is waiting for CPU time.
4. Waiting: The thread is waiting for another thread to perform a particular action.
Features:
2. State transitions occur based on thread actions (e.g., calling start(), sleep(), etc.).
Advantages:
3. Efficient resource allocation: Allows the system to allocate CPU time dynamically.
Disadvantages:
t.start();
}
}
Features:
Advantages:
5. Concurrency benefits such as reduced waiting times and quicker completion of tasks.
Disadvantages:
4. Potential deadlocks: Improper locking mechanisms can lead to threads waiting forever.
5. High memory usage: Each thread consumes system resources (stack memory, CPU
cycles).
Each topic includes definition, examples, features, advantages, and disadvantages, making
it exam-friendly.
Definition:
• InputStream: An abstract class for reading byte data.
Example (InputStream):
import java.io.*;
int byteRead;
System.out.print((char) byteRead);
is.close();
Example (OutputStream):
import java.io.*;
os.write(message.getBytes());
os.close();
Features:
2. Abstract: Both are abstract classes, so concrete implementations are used (e.g.,
FileInputStream, FileOutputStream).
Advantages:
1. Efficient for Binary Data: Perfect for file operations involving binary data (images,
audio).
3. Flexible for Large Files: Works well with large data streams since it reads/writes
sequentially.
5. Easy to Use: Simple classes like FileInputStream and FileOutputStream make it easy to
implement.
Disadvantages:
1. Not Suitable for Character Data: Not ideal for text files; use Reader/Writer classes for
better handling of characters.
3. Buffering Overhead: For large data, manual buffering may be required to improve
performance.
Definition:
Example (Reader):
import java.io.*;
int charRead;
System.out.print((char) charRead);
reader.close();
Example (Writer):
import java.io.*;
writer.write(message);
writer.close();
Features:
Advantages:
1. Handles Character Encoding: Works well with different character encodings (e.g., UTF-
8, ASCII).
3. Readable Code: Easier to use for text-based operations compared to byte streams.
Disadvantages:
3. Inefficient for Binary Files: Slower for binary files compared to byte streams.
4. Manual Error Handling: Similar to byte streams, requires explicit error handling.
5. Sequential Processing: Data is processed sequentially, not suitable for random access.
Definition:
File I/O in Java allows reading from and writing to files, either as byte or character streams,
providing input/output capabilities for persistent storage.
Example:
import java.io.*;
// Writing data
writer.write("Hello, Java!");
writer.close();
// Reading data
String line;
System.out.println(line);
reader.close();
Features:
1. File handling: Allows operations on files, such as reading, writing, and file manipulation.
4. Flexible: Handles both character and byte data through different streams.
5. Random Access: RandomAccessFile allows reading/writing from any part of the file.
Advantages:
1. Ease of Use: Classes like FileReader and FileWriter make file handling straightforward.
4. Supports large files: Buffered streams help process large files efficiently.
5. Simple Syntax: Java’s I/O stream API provides simple and intuitive syntax for file
handling.
Disadvantages:
1. Error-prone: I/O operations may lead to errors like IOException.
2. No direct support for advanced file systems: Lacks advanced file system management
(like symbolic links).
4. Memory intensive: Buffered classes use extra memory for efficient data handling.
Definition:
An exception is an event that disrupts the normal flow of a program. Java supports exception
handling using try, catch, throw, and throws.
Types of Exceptions:
Example (Try-Catch):
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
Example (Try-Finally):
try {
int result = 10 / 0;
} finally {
}
}
try {
test.checkAge(15);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
Features:
4. Custom Exceptions: Developers can define custom exceptions for specific errors.
5. Multiple Catch Blocks: Multiple exception types can be handled in different blocks.
Advantages:
5. Support for Multiple Exceptions: Handles multiple error types through various
exception classes.
Disadvantages:
2. Overused Exceptions: Can lead to cluttered code if exceptions are overused for control
flow.
3. Error Masking: Misuse can hide actual issues (e.g., catching Exception).
4. Complexity: Nested try-catch blocks can make the code more complex and harder to
read.
5. Requires Explicit Handling: Must explicitly handle checked exceptions, making the code
verbose.
• JDBC Drivers
Definition:
• JDBC is an API in Java that enables communication between Java applications and
relational databases (like MySQL, Oracle, etc.).
• It provides a standard interface for connecting to a database, sending SQL queries, and
retrieving results.
Example:
import java.sql.*;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// Create a statement
// Execute a query
while (rs.next()) {
// Close resources
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
Features:
3. SQL Query Execution: Supports executing SQL queries (e.g., SELECT, INSERT, UPDATE,
DELETE).
4. Result Set: Provides a structured way to retrieve data from the database.
Advantages:
Disadvantages:
2. Error Handling: JDBC requires careful exception handling, especially with SQL errors.
5. Verbose Code: SQL operations can result in long code with multiple lines for each query.
2. Setup Connection:
3. Close Connection: Always close the connection, statement, and result set when done.
Features:
1. JDBC API: Provides a set of Java classes and interfaces for database interaction.
3. Driver Types: JDBC drivers come in four types (1, 2, 3, and 4) with varying levels of
functionality.
4. Standard Database Access: Offers standard ways to connect and execute queries.
5. Support for Multiple Databases: Can connect to any relational database with a
compatible driver.
Advantages:
2. Flexibility: Can work with various databases by simply changing the JDBC driver.
Disadvantages:
1. Driver Dependency: Requires the correct driver for the specific database.
3. Not Dynamic: Switching databases requires manual changes in the driver code.
4. No Native Support for NoSQL: Does not support NoSQL databases natively.
5. Potential for Memory Leaks: Failing to close resources can lead to memory issues.
JDBC Drivers
Definition:
JDBC drivers are the interfaces that allow Java to interact with databases. There are four types of
JDBC drivers, each with varying capabilities and performance characteristics.
3. Type-3 Driver (Network Protocol Driver): Uses a middle layer to connect to the
database, making it platform-independent.
4. Type-4 Driver (Thin Driver): A pure Java driver that directly connects to the database
via TCP/IP, offering high performance.
Features:
1. Driver Types: Different drivers for different use cases and performance requirements.
4. Driver Configuration: Drivers need to be added to your project for JDBC to work.
Advantages:
1. Performance: Type-4 drivers are the most efficient since they directly communicate with
the database.
2. Platform Independence: Type-3 and Type-4 drivers work across different platforms.
5. Portability: JDBC drivers can be used in different environments with minimal changes.
Disadvantages:
4. Not Always Available: Some databases may lack suitable JDBC drivers.
5. Outdated Drivers: Type-1 drivers are deprecated and no longer supported in many
modern applications.
• JDBC allows executing various SQL queries like CREATE, INSERT, UPDATE, DELETE, and
SELECT to manage database data.
Example:
1. Create Table:
String createTableSQL = "CREATE TABLE students (id INT PRIMARY KEY, name VARCHAR(50))";
stmt.executeUpdate(createTableSQL);
2. Insert Data:
String insertSQL = "INSERT INTO students (id, name) VALUES (?, ?)";
pstmt.setInt(1, 1);
pstmt.setString(2, "John");
pstmt.executeUpdate();
3. Update Data:
pstmt.setString(1, "Alice");
pstmt.setInt(2, 1);
pstmt.executeUpdate();
4. Delete Data:
pstmt.setInt(1, 1);
pstmt.executeUpdate();
5. Retrieve Data:
ResultSet rs = stmt.executeQuery(selectSQL);
while (rs.next()) {
Features:
1. Support for CRUD Operations: JDBC provides methods for creating, reading, updating,
and deleting records.
2. Prepared Statements: Allows for secure and efficient handling of SQL queries with
parameters.
3. ResultSet: Facilitates retrieving and processing data from SELECT queries.
4. Error Handling: Exception handling is used to catch and manage SQL errors.
5. Auto-commit: By default, JDBC commits changes after each statement, but this can be
controlled.
Advantages:
2. Efficient Data Handling: Prepared statements and batch updates improve performance.
5. Flexibility: Works with all SQL queries, allowing for a wide range of database interactions.
Disadvantages:
1. SQL Syntax Dependence: SQL queries are dependent on the database's syntax.
4. Database-Specific Code: SQL code may need to be adjusted for different database
systems.
Here are detailed notes on Abstract Window Toolkit (AWT), Java Swing, and Event
Handling in Java:
Definition:
• The Abstract Window Toolkit (AWT) is a set of APIs used to create graphical user interfaces
(GUIs) in Java.
• It provides a collection of components, such as buttons, text fields, and checkboxes, for
building desktop applications.
• AWT components are platform-dependent and rely on native operating system components
for rendering.
Features:
1. Platform-Dependent: AWT components are rendered using the underlying OS's native
GUI components.
2. Basic Components: Includes fundamental UI components like buttons, text fields, and
labels.
3. Event Handling: AWT has built-in support for handling events like clicks and key presses.
4. Lightweight: AWT is relatively lightweight compared to Swing, relying on the system's
native libraries.
Advantages:
1. Cross-Platform: Works across different operating systems, as it relies on the native GUI
components.
2. Simple to Use: AWT is easy to use for basic GUI development and learning.
3. Direct OS Integration: Seamless integration with the underlying operating system’s GUI.
4. Event Handling Support: Offers support for user interactions through events.
Disadvantages:
3. Limited Features: AWT does not provide advanced features like complex layouts or UI
elements.
4. Slow Rendering: AWT components may have slower rendering speeds on modern
platforms.
5. Limited Support for Complex Applications: AWT may not be suitable for building
sophisticated or highly interactive applications.
Java Swing
Definition:
• Swing is a more advanced GUI toolkit than AWT. It is a part of the Java Foundation Classes
(JFC).
• Swing provides a richer set of components compared to AWT, with better customization
and a more modern look and feel.
Components:
4. JToggleButton: A button that can have two states: pressed or not pressed.
5. JCheckBox: A checkbox component that allows the user to select or deselect an option.
9. JPasswordField: A text field that hides the input text (commonly used for passwords).
10. JList: A list of items from which the user can select.
11. JComboBox: A drop-down list of items from which the user can choose.
Containers:
Layout Managers:
2. BorderLayout: Divides the container into five regions: North, South, East, West, and
Center.
Swing vs AWT:
4. Swing is more feature-rich, providing advanced features like tooltips, trees, and tables.
5. Swing offers a consistent look and feel across all platforms, while AWT's appearance
may differ based on the OS.
Advantages of Swing:
3. Rich Set of Components: Provides a wide range of components for building modern
GUIs.
4. Event Handling: Swing has a robust event-handling model, making it ideal for interactive
applications.
5. Better Look and Feel: Swing offers a more modern and appealing look compared to AWT.
Disadvantages of Swing:
1. Slower than AWT: Swing has a higher performance overhead as compared to AWT due
to its abstraction.
2. More Complex: Swing can be more complex to learn and use, especially for beginners.
3. Less Support for Lightweight Components: Swing’s use of heavyweight components
can be less efficient than lightweight components in other toolkits.
4. Memory Intensive: Swing applications consume more memory than AWT applications.
5. Not Ideal for Mobile: Swing is more suited for desktop applications and is not commonly
used for mobile development.
Definition:
• Event handling is a mechanism that allows an application to respond to user actions, such
as clicks, keyboard presses, or mouse movements.
• The Event Delegation Model in Java involves an event source that generates an event
and an event listener that handles the event.
Key Components:
3. Event Listener: An interface that listens for specific events and responds to them.
4. Event Delegation Model: In this model, the event is sent to the appropriate listener
method rather than directly within the source object.
import javax.swing.*;
import java.awt.event.*;
button.addActionListener(new ActionListener() {
System.out.println("Button clicked!");
}
});
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Features:
1. Event Delegation Model: Events are passed from the source to the listener, making code
modular.
2. Multiple Event Sources: Multiple components can generate events, and listeners can
handle them.
3. Rich Event Handling: Java provides a comprehensive set of event classes and listeners
for different kinds of user interactions.
5. Separation of Concerns: The model allows for a clean separation between the event
source (component) and the event handler (listener).
Advantages:
1. Separation of Logic: Event handling keeps the event source and listener separate,
making the code easier to manage and debug.
2. Ease of Use: Java provides simple interfaces and classes to implement event handling.
3. Scalability: Event handling is scalable, allowing multiple listeners to handle events from
various components.
5. Reusability: Event listeners can be reused across different components, making your
code modular and maintainable.
Disadvantages:
1. Complexity: For large applications, managing event handling across many components
can become complex.
2. Memory Leaks: Failing to deregister event listeners can lead to memory leaks.
4. Code Bloat: Having many listeners for different events can lead to bloated code.
5. Hard to Debug: Tracking down the flow of events in large applications can be difficult,
especially if events are not well-organized.