[go: up one dir, main page]

0% found this document useful (0 votes)
66 views395 pages

OOPS One Shot Lecture Notes

The document provides an overview of Object-Oriented Programming (OOP) concepts, including the benefits of OOP such as code reusability and simplified software development. It covers key terms like classes, objects, inheritance, encapsulation, and polymorphism, along with practical examples in Java. Additionally, it discusses various programming structures, data types, control statements, and best practices in Java programming.
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)
66 views395 pages

OOPS One Shot Lecture Notes

The document provides an overview of Object-Oriented Programming (OOP) concepts, including the benefits of OOP such as code reusability and simplified software development. It covers key terms like classes, objects, inheritance, encapsulation, and polymorphism, along with practical examples in Java. Additionally, it discusses various programming structures, data types, control statements, and best practices in Java programming.
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/ 395

OOPS

why learn OOP?


benefits of OOP

code reusability

simplified software development

clear program structure

data and functions bundled as a unit

Comparison with procedural programming: OOP leads to more efficient and


maintainable software

an analogy
building a car - each part is an object, put together, they form a functional car

key terms

OOPS 1
OOP vs Procedural

OOPS 2
Overview

objects and class basics


Objects:

instances of a class

have states and behaviors

eg: a “car” object has states like color, model, make etc. and behaviors such
as drive, braking, acceleration.

OOPS 3
Class

blueprint for objects

define possible states and behaviors of object

eg: a “car” class defines the attributes and methods for “car” objects.

creating a class in java


a class is created using the “class” keyword followed by the class name.

eg:

class Car {
String model; // a string var
String color; // a string var
String numberOfDoors; // a string var
void startEngine() { //<logic> } //method
void accelerate() { //<logic> } //method

an object is created using the “new” keyword followed by the class name and
the parantheses

eg:

Car myCar = new Car();

this creates a new object of the car class and assigns it to the variable
myC ar 

attributes of a class
variable within a class

represent the state of an object

OOPS 4
class Car {
String model;
String color;
String numberOfDoors;
}

a simple example of a “Car” class with attributes called model, color and
numberOf Doors 

methods of a class
functions within a class

represent the behavior of an object

class Car {
String model;

void displayModel() {
System.out.println("Model:" + model);
}
}

Method here is displayM odel();

added to the “Car” class

Responsible for retrieving and displaying the model of the car

constructors of a class
construnctors are special methods in a class

they are called when an object of the class is created

constructors are used to initialize the state of an object.

OOPS 5
class Car {
String model;
String color;

//Constructor
Car(String model, String color) {
this.model = model;
this.color = color;
}

void startEngine() {
// Car starting logic here

}
}

abstraction in OOP
abstraction is a fundamental principle in OOP that simplifies complex systems
by setting a focus only on relevant details for the specific context.

eg:

in the case of a car, it is not required to know how it works internally in


order to drive it. the internal workings are abstracted away from us.

in Java, abstraction is achieved by interfaces and abstract classes

importance of abstraction

OOPS 6
abstract class

eg:

abstract class Animal {


abstract void makeSound();
}

OOPS 7
abstract methods

eg:

abstract class Animal {


abstract void makeSound();
}
class Dog extends Animal {
void makeSound() {
System.out.println("Woof Woof");
}
}

interface in java

OOPS 8
eg:

interface Animal {
void makeSound();
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Woof Woof");
}
}

implements is used for the interface whereas extendsis used for the abstract
class.

in a nutshell,

abstraction is like saying “i don’t care how you do it, just do it.” it hides the
complex stuff and shows only the important stuff.

an interface is like a contract. you say “any class that signs this contract must
follow all its rules.”

encapsulation

OOPS 9
access modifiers
determine the scope of a class, constructor, variable, method, or data member

public, private, protected and default access modifiers

eg:

class Car {
private String model;
}

OOPS 10
getters and setters in java

eg:

class Car {
private String model;
//Getter
public String getModel(){
return model;
}

//Setter
public void setModel(String newModel) {
this.model = newModel;
}
}

another example

OOPS 11
inheritance

syntax of inheritance
in java, the “extends” keyword is used to denoted inheritance

eg:

OOPS 12
class ParentClass {
//fields and methods
}
class ChildClass extends ParentClass {
// additional fields and methods
}

types of inheritance: single, multilevel and


hierarchical

OOPS 13
super keyword
the super keyword in java is a reference variable used to refer to the
immediate parent class object.

eg

class ChildClass extends ParentClass {


void myMethod() {
super.myMethods(); //calling ParentClass's method
}
}

OOPS 14
method overriding
if a child class provides a specific implementation of a method that is already
provided by its parent class, it is known as method overriding

eg:

class ParentClass {
void mymethod() {
//some code
}
}
class ChildClass extends ParentClass {
@Override
void myMethod() {
// some different code
}
}

polymorphism

OOPS 15
static polymorphism or method overloading

//example

class MyClass {
void myMethod(int x) {
// some code
}

void myMethod(String x) {
//some code
}
}

dynamic polymorphism or method overriding

OOPS 16
//example
class ParentClass {
void myMethod() {
//some code
}
}
class ChildClass extends ParentClass{
@Override
void myMethod() {
//some different code
}
}

method overloading vs. method overriding

OOPS 17
java program structure

components

OOPS 18
code structure
the structure of a java program includes import statements, class declaration,
the main method, and other methods.

// example
import java.util.Scanner; // import statement
public class Main { // Class declaration
public static void main(String[] args) { // main method
System.out.println("Hello, World!");
}
public static void myMethod() { // Other Methods
// some code
}

Java Packages
way to group related classes and interfaces

helps to keep the codebase organized and prevents naming conflicts

// example
package

OOPS 19
com.mycompany.myapp;
//package declaration

simple java program

//example: area of a circle


public class Main {
public static void main(String[] args) {
//declare radius (double primitive type)
double radius = 5.5;
//Declare pi as constant (final keyword)
final double PI = 3.14159;
//Calculate area
double area = PI * radius * radius;
//Print the result
System.out.println("The area of the circle is:" + area);
}
}

java primitive type


primitive type are the most basic data types available within the java language.

integer

floating point

character

boolean

integer

OOPS 20
floating point types

OOPS 21
character type

boolean type

ranges and default values

OOPS 22
variables

OOPS 23
types of variables

scope of variables

OOPS 24
local variable example:

public void myMethod() {


int localVariable = 5; // this variable is only accessible
// within myMethod()
System.out.println(localVariable);
}

instance variable example:

public class MyClass {


int instanceVariable = 100; // This variable is accessible within any

OOPS 25
// non-static method in MyClass
public void myMethod(){
System.out.println(instanceVariable);
}
}

static variable example

public class MyClass {


static int staticVariable = 200; //this variable is accessible within
// any method in MyClass
public void myMethod(){
System.out.println(staticVariable);
}
}

type casting and type promotion

OOPS 26
OOPS 27
rules of automatic type promotion

OOPS 28
type casting

OOPS 29
rules of type casting

OOPS 30
common pitfalls and best practices

OOPS 31
arithmetic operators

OOPS 32
//example
int a = 10;
int b = 5
System.out.println("a + b =" + (a + b));

relational operators

OOPS 33
// example of relational operators
int a = 5
int b = 3
//equal to (==)
boolean isEqual = a == b;
System.out.println("Equal to:" + isEqual); // Output: false

//not equal to (!=)


boolean isNotEqual = a !=b;
System.out.println("Not equal to:" + isNotEqual); //Output: true

//greater than (>)


boolean isGreater = a > b;
System.out.println("Greater than:" + isGreater); // Output: true

Bitwise Operators

OOPS 34
//example
int a = 5; //Binary: 0101
int b = 3;

//Bitwise AND (&)


int resulAnd = a & b; //Binary: 0001

OOPS 35
//Bitwise OR (|)
int resultOr = a | b; // binary: 0111

Assignment operators

//example
int a = 5;
a += 2; // equivalent to a = a + 2
System.out.println("a = "+ a);

logical operators

OOPS 36
control statements

OOPS 37
if-else statement

//Syntax
if (condition) {

OOPS 38
//code to execute if the condition is true
} else {
//code to execute if the condition is false
}

example:

//checking if a number is positive or negative


int number = 5;
if (number>= 0) {
System.out.println("The number is positive.");
} else {
System.out.println("The number is negative.");

switch statement

//syntax
switch (expression) {
case value1:
//code to be executed if expression equals value1
break;
case value2;
//code to be executed if expression equals value2
break;

OOPS 39
//... more cases ...
default;
//code to be executed if the expression doesn't match any value
}

switch statement: example

// creating a simple calculator


char operator = '+';
int num1 = 5, num2 = 3, result;
switch(operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
//... other cases

default:
System.out.println("Invalid operator!");
}

the for loop

OOPS 40
syntax
for(initialization; condition; increment/decrement) {// code}

example:

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


System.out.println("Count is:" + i);
}

this loo[p will print the numbers 1 to 5, as the loop continues while “i” is less than
or equal to 5, incrementing “i” by 1 at each iteration.

the while loop

syntax
while(condition) {//code}

example:

OOPS 41
int count = 1;
while (count <= 5) {
System.out.println("Count is:" + count);
count++;
}

similar to the “for” loop above this “while” loop will also print the numbers 1 to
5.

the do while loop


syntax:
do {//code} while (condition);

example:

int count = 1;
do {
System.out.println("Count is:" + count);
count++;
} while (count <= 5);

This loop prints the numbers 1 to 5, but it will execute the body of the loop before
checking the condition.

break statement

OOPS 42
// example
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
System.out.println("Count is" + 1);
}

in this example, the “for” loop will break when “i” equals 3, so it will only print the
number 1 and 2.

continue statement

example

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


if (i == 3) {
continue;
}
System.out.println("Count is:" + i);
}

OOPS 43
in this “for” loop, when “i” equals 3, the loop skips the print statement and
proceed to the next iteration. therefore, it will print the number 1, 2, 4, and 5.

OOPS 44
Class
fundamental concept in OOP

OOPS 45
defining a class

class definition: example

public class Dog {


//Field
String breed;
}

OOPS 46
sample code

public class Main {


public static void main(String[] args) {
//create dog object
Dog myDog = new Dog();
//access fields and methods
myDog.breed "Labrador";
myDog.bark();
}
}

access modifiers

OOPS 47
public modifier

private modifier

OOPS 48
protected and default modifiers

example 1:
consider a house class with members having different access modifiers.

public class House{


public String door = "Public DOor";
private String safeBox = "Private SafeBox";
protected String family Room = "Protected Family Room";
String kitchen = "Default Kitchen";
}

example 2

OOPS 49
example 3

objects in java

OOPS 50
classes

creating objects

OOPS 51
example:

objects and memory

OOPS 52
Contructors

OOPS 53
default constructor

parameterized constructor

OOPS 54
example

OOPS 55
default constructors

default values

OOPS 56
example:

using the default constructor

OOPS 57
parameterized constructors

when to use it?

OOPS 58
syntax

OOPS 59
pros and cons

accessing instance fields and methods

OOPS 60
OOPS 61
OOPS 62
class vs. instance variables

characteristics of instance variable

OOPS 63
characteristics of class variables

OOPS 64
mutable and immutable objects

characteristics of mutable objects

OOPS 65
characteristics of immutable objects

OOPS 66
example for mutable objects

example for immutable objects

OOPS 67
command line arguments

the main() method and arguments

OOPS 68
accessing command line arguments

example:

OOPS 69
running the example

scanner class

OOPS 70
constructing a scanner

reading data with scanner

OOPS 71
example to read input

next() vs. nextLine()

reading numeric data with scanner

OOPS 72
example of reading numeric input

reading input using scanner class

OOPS 73
hasNext() and Next()

reading multiple values: example

OOPS 74
delimiters and the scanner class

example: using a different delimiter

OOPS 75
static keyword

role of static keyword

OOPS 76
distinctive nature of static keyword

example

OOPS 77
Overview of static variables

static variable

overview of static methods

OOPS 78
static blocks in java

static nested class in java

OOPS 79
key constraints

static variables in java

OOPS 80
code example

properties of static variables

OOPS 81
static methods in java

code example for static methods

properties of static methods

OOPS 82
relationship between static vars and methods

practical usage of static methods and variables

OOPS 83
final keyword in java

working of final keyword

code example:

brief on static keyword

OOPS 84
brief on final variables

brief on final methods

brief on final classes

OOPS 85
practical usage of final keyword

final variables:

code example

OOPS 86
final instance variables

code example: final instance variables

OOPS 87
final methods

OOPS 88
code example: final methods

final with inheritance

OOPS 89
practical usage of final variables and methods

method overloading basics:

achieve method overloading

OOPS 90
overloading by number of parameters

example:

OOPS 91
overloading by type of parameters

example:

OOPS 92
importance of method overloading

method overloading with different


parameter types

OOPS 93
overloading with different parameter types

example 1

example 2

OOPS 94
overloaded method selection

advantages of method overloading

OOPS 95
constructor overloading

working of contructor overloading

OOPS 96
constructor overloading example

OOPS 97
OOPS 98
advantages of constructor overloading

rules of constructor overloading

properties of static methods

OOPS 99
practical usage of constructor overloading

practical usage of constructor overloading

OOPS 100
objects as method parameters

example code

OOPS 101
usage of objects as method parameters

OOPS 102
changing object state

example code for changing object state

OOPS 103
OOPS 104
note on object references

benefits of passing object

returning objects from methods

OOPS 105
example code

advantages of returning objects

OOPS 106
using method returns

example code for using method returns

OOPS 107
beware of null returns

array

OOPS 108
declaration

instantiation of arrays

OOPS 109
example of array declaration and instantiation

initialization of arrays

OOPS 110
types of arrays

array in java characteristics

1D arrays

OOPS 111
declaration of 1-D arrays

instantiation of 1-D arrays

OOPS 112
example of array declaration and instantiation

accessing elements of 1-D arrays

code example

2-D Arrays

OOPS 113
declaration of arrays

instantiation of 2-D arrays

OOPS 114
initialization of 2-D arrays

code example:

looping through a 2-D array

code example

OOPS 115
arrays class and it’s methods

important method

Arrays.sort() method
sorts all the elements in the array

OOPS 116
code example for arrays.sort

Arrays.binarySearch() Method

code example:

OOPS 117
Arrays.equals() Method

code example for Arrays.equals()

inheritance

OOPS 118
working of inheritance

code example: inheritance

OOPS 119
explanation

OOPS 120
benefits: (optional to read)

inheritance hierarchy

OOPS 121
constructor calling chain

important point and limitations

OOPS 122
TL;DR

extending classes in java

OOPS 123
extends keyword

extending classes: code example

OOPS 124
advantages

OOPS 125
extending classes and constructors

constructors in inheritance: code example

OOPS 126
limitations of extending classes

OOPS 127
TL;DR

super keyword

super keyword to access parent class variables

OOPS 128
code example:

super keyword to access parent class methods

OOPS 129
example code:

OOPS 130
super keyword to access parent class constructors

code example:

TL;DR

OOPS 131
method overriding and polymorphism in
java

method overriding basics

method overriding

OOPS 132
polymorphism basics

OOPS 133
code example: polymorphism

OOPS 134
explanation of the code

OOPS 135
rules of method overriding

benefits of method overriding:

OOPS 136
Super vs. sub-type relationships in java

code example:

OOPS 137
relationship characteristics

polymorphism and super-type vs. sub-type


relationships

code example: polymorphism

OOPS 138
OOPS 139
super-type vs sub-type practical usage

abstract classes in java

OOPS 140
creating an abstract class

code example:

subclasses of abstract classes

OOPS 141
subclass code example:

purpose and use of abstract classes

OOPS 142
when to use abstract classes

abstract methods in java

characteristics

OOPS 143
abstract method declaration: code example

abstract method: implementing

code example:

OOPS 144
explanation

purpose and use

OOPS 145
when to uses abstract methods

note:

interface

OOPS 146
what is interface?

interface declaration:

OOPS 147
implementation of an interface

code example: implementing an interface

benefits

OOPS 148
when to use interfaces

default methods and static methods in interfaces

OOPS 149
quick explanation:

in java,
interfaces are like contracts — they define what a class should do, not how it
should do it. and the cool part? a class can implement as many interfaces as it
wants, which is java’s way of doing multiple inheritance (since it doesn’t allow
multiple class inheritance).

note:

OOPS 150
implementing interfaces

OOPS 151
code example: a simple interface

multiple interfaces

OOPS 152
code example: multi interfaces

OOPS 153
benefits

points to remember:

OOPS 154
notes:

comparable and comparator interfaces

OOPS 155
comparable interfaces

OOPS 156
code example:

OOPS 157
code example: comparable interface

OOPS 158
comparator interface:

code example:

OOPS 159
OOPS 160
difference between comparable and comparator

when to use what?

in simple terms
feature Comparable Comparator

OOPS 161
where it's outside the class (like a separate
in the class itself
implemented custom sorting logic)

interface name java.lang.Comparable java.util.Comparator

method to
compareTo() compare()
implement

affects default
yes no (used for custom sorting)
sorting?

how many can you only one (because it’s inside


as many as you want
have? the class)

nested and inner classes

types of nested classes

OOPS 162
code example: static nested classes

OOPS 163
inner classes

code example:

OOPS 164
benefits

OOPS 165
drawbacks of inner classes

anonymous classes

OOPS 166
usage:

code example: anonymous subclasses

OOPS 167
OOPS 168
anonymous objects

code example:

OOPS 169
OOPS 170
advantages of anonymous classes and objects

disadvantages of anonymous classes and objects

OOPS 171
generic programming

generic classes in java

OOPS 172
generic interfaces in java

bounded types

OOPS 173
wildcards in generics

collections framework introduction

OOPS 174
wrapper classes in java

OOPS 175
generic classes in java

type parameters

code example of using generic type parameter

OOPS 176
creating instances of generic classes

OOPS 177
code eg of creating instance of a generic class

using generic class methods

code example of generic class method

OOPS 178
benefits of generic classes

note:
Typecasting is not needed in generic classes due to type erasure.

when you're creating an instance of a generic class, you need to specify the
actual type you want to use in place of the type parameter (
<T> ).

OOPS 179
eg:

GenericClass<String> obj = new GenericClass<>();

generic class methods can operate on objects of the specified type.

Bounded types, not type parameters, are used to restrict the types that can be
used as arguments in generics. Type parameters represent the types that will
be used within the class and are not used for restriction purposes.

generic interfaces in java

declaring a generic interface

OOPS 180
using type parameters in a generic interface

code example: using type parameters in a generic


interface

OOPS 181
implementing a generic interface

code example:

OOPS 182
benefits

OOPS 183
note:
generic interfaces enable the creation of generic algorithms and data structures
as they allow for the implementation of algorithms and data structures that can
work with different types by using type parameters.

bounded types

upper bounded types

OOPS 184
code example

lower bounded types

OOPS 185
code example

wildcards in generics

note
Bounded types provide additional compile-time type safety and flexibility by
specifying constraints on the types that can be used as type arguments in
generic classes or methods.

Upper bounded types specify that a type argument must be a specific type or
any of its subtypes.

OOPS 186
The syntax for using upper bounded types in a generic class declaration is
“<T extends Number>,” where “Number” is the specific type or its subtypes.

Lower bounded types specify that a type argument must be a specific type or
any of its supertypes.

Wildcards allow for generic types with unknown types or when the type
parameter is not important, providing flexibility in working with generics.

wildcards in generics

upper bounded wildcards

OOPS 187
code example

lower bounded wildcard

OOPS 188
code example

OOPS 189
unbounded wildcards

code example

OOPS 190
using wildcards in method signatures

note

OOPS 191
Wildcards do not allow for unrestricted types to be used as type arguments.
They are used for unknown or unspecified types.

Upper bounded wildcards specify that the unknown type must be a specific
type or any of its subtypes.

Lower bounded wildcards specify that the unknown type must be a specific
type or any of its supertypes.

Unbounded wildcards allow for generic types with unknown or unspecified


types, providing flexibility in working with different types.

Wildcards in generics allow for more flexibility when dealing with unknown types,
enabling code to work with a wider range of types.

collections framework introduction

ArrayList Class and methods

OOPS 192
LinkedList Class and Methods

iterators and listerators

OOPS 193
wrapper classes in java

OOPS 194
set interface and implementations

OOPS 195
map interface and HashMap class

OOPS 196
ArrayList

OOPS 197
adding elements to ArrayList

OOPS 198
modifying elements in ArrayList

OOPS 199
removing elements from ArrayList

checking ArrayList Size

OOPS 200
checking if ArrayList is Empty

OOPS 201
LinkedList

creating a LinkedList

OOPS 202
adding elements

accessing elements in LinkedList

OOPS 203
modifying elements in LinkedList

OOPS 204
removing elements from LinkedList

OOPS 205
checking LinkedList Size

OOPS 206
checking LinkedList is Empty

OOPS 207
intro to iterators

OOPS 208
using an iterator

accessing elements in ArrayList

OOPS 209
removing elements with iterator

Listiterators

OOPS 210
Using ListIterator

iterating through elements with listiterators

OOPS 211
modifying elements with listiterator

OOPS 212
notes
An iterator is used to iterate over elements in a collection, allowing sequential
access to each element.

The “Iterator” class cannot be instantiated directly.

The “hasNext()” method is used to check if there is another element in the


iteration

List iterators, unlike regular iterators, provide additional functionalities such as


bidirectional traversal (using “hasPrevious()” and “previous()” methods) and
modification of elements using the “set()” method.

The “hasNext()” method of an iterator checks if there is another element in the


iteration sequence of a collection. It returns “true” if there is another element,
and “false” otherwise.

wrapper classes

OOPS 213
code example

commonly used wrapper classes

OOPS 214
autoboxing and unboxing

code example

OOPS 215
converting strings to wrapper objects

OOPS 216
code example

converting wrapper objects to strings

code example

OOPS 217
comparison and equality

code example:

OOPS 218
set interface

code example

OOPS 219
common implementations of set interface

OOPS 220
comparison of set implementations

OOPS 221
code example

OOPS 222
set interface methods

code interface methods

OOPS 223
iterating over a set

code example

OOPS 224
notes

OOPS 225
The Set interface in Java is used to represent a collection of unique elements
with no defined ordering. Sets do not allow duplicate elements, and they do
not maintain the insertion order of elements.

LinkedHashSet is an implementation of the Set interface that maintains the


insertion order of elements. It stores elements in the order in which they were
inserted into the set.

The “contains()” method is used to check if a set contains a specific element


in Java. It returns “true” if the set contains the element; otherwise, it returns
“false”.

Sets do not maintain the insertion order of elements. The order of elements in
a set is not predictable.

HashSet allows the inclusion of null elements. You can add null values to a
HashSet.

map interface

features

OOPS 226
HashMap Class

OOPS 227
features of HashMap Class

OOPS 228
iterating over map and HashMap

OOPS 229
code example

OOPS 230
notes
The entrySet() method returns a set of Map.Entry objects, each representing a
key-value pair in the Map. It allows you to iterate over the key-value pairs.

The put() method is used to add a key-value pair to a Map in Java. It takes a
key and a corresponding value as parameters and associates the value with
the key in the Map.

intro to exception handling

why exception handling?

OOPS 231
exception hierarchy

types of exceptions

OOPS 232
code example: exception occurence

OOPS 233
the try-catch block

notes
Exception handling in Java allows us to gracefully handle and manage runtime
errors or exceptional situations that may occur during program execution. It
helps prevent abrupt program termination and provides error-handling
mechanisms.

"Throwable" is the base class for all exceptions and errors in Java. It provides
common functionality and properties for handling exceptional situations.

Both checked and unchecked exceptions can be thrown at runtime.

The try-catch block is used to catch and handle exceptions in Java. The code
that may throw an exception is enclosed within the try block, and the catch
block is used to catch the exception and provide appropriate error handling
code.

OOPS 234
While the program may terminate abruptly in certain cases, it depends on the
availability of an appropriate catch block in the surrounding try-catch blocks.

While custom error messages can be part of exception handling, but not to
create custom error messages.

types of exceptions in java

checked exceptions

code example

OOPS 235
unchecked exception

OOPS 236
code example:

errors in java

OOPS 237
differences bw checked and unchecked exceptions

OOPS 238
notes
Checked exceptions in Java require explicit handling or declaration using the
"throws" keyword. They are checked at compile-time, meaning that the
compiler enforces the programmer to handle or declare them.

Checked exceptions are caused by programming errors or logic flaws.


"IOException" is an example of a checked exception in Java. It is typically
thrown when there is an input/output-related error, such as when reading from
or writing to a file.

The main difference between checked and unchecked exceptions in Java is


that checked exceptions require explicit handling or declaration using the
"throws" keyword, while unchecked exceptions do not.

"ArrayIndexOutOfBoundsException" is an example of an unchecked exception


in Java. It occurs when attempting to access an array element with an invalid
index.

Exceptions are caused by programming errors, while errors are caused by


severe issues like out of memory errors.

try and catch blocks

using try block

OOPS 239
code example:

using catch block

OOPS 240
code example:

OOPS 241
multiple catch blocks

code example

OOPS 242
notes
The purpose of a try block in Java exception handling is to define the code
that may throw an exception. Any exception that occurs within the try block
can be caught and handled by the corresponding catch block.

The purpose of a catch block in Java exception handling is to catch and


handle exceptions that are thrown within the corresponding try block. It allows
the program to take appropriate actions when exceptions occur.

If an exception occurs within the try block and there is no corresponding catch
block to handle it, the program will terminate abruptly. This is because the
exception remains unhandled, and the program does not know how to recover
from it.

OOPS 243
A try block can have multiple catch blocks, and each catch block can catch a
different type of exception. This allows for handling different types of
exceptions in separate catch blocks.

The catch block for the subclass exceptions should be written first, followed
by the catch block for the superclass exceptions.

multiple catch blocks

using multiple catch blocks

OOPS 244
code example:

OOPS 245
catch Blocks’ order

code example: correct order of catch blocks

OOPS 246
code example: incorrect order of catch blocks

OOPS 247
notes
The order of catch blocks is important, but it is not the primary purpose of
using multiple catch blocks.

Multiple catch blocks cannot catch exceptions of any type; they are limited to
catching related exceptions.

OOPS 248
If an exception occurs that is not caught by any of the catch blocks in a
multiple catch block scenario, the program will terminate abruptly. This is
because the exception remains unhandled, and the program does not know
how to recover from it.

When using multiple catch blocks, the catch block for the subclass exceptions
should be written first, followed by the catch block for the superclass
exceptions. This ensures that the catch blocks are ordered correctly based on
the inheritance hierarchy of exceptions.

The catch block with the "Exception" parameter in a multiple catch block
scenario, acts as a fallback catch block. If an exception occurs that is not
caught by any of the preceding catch blocks, it will be caught by this catch
block. It is considered a catch-all for exceptions not explicitly caught by the
preceding catch blocks.

finally block

OOPS 249
using the finally block

code example:

OOPS 250
execution of finally Block

OOPS 251
code example: finally block with no exception

OOPS 252
finally block without catch block

code example: finally Block without catch block

OOPS 253
notes
The purpose of the finally block in Java exception handling is to execute a
section of code regardless of whether an exception occurs or not. It ensures
that the code inside the finally block will always be executed, providing a way
to perform cleanup operations or release resources.

The code inside the finally block always executes, regardless of whether an
exception occurs or not. It ensures that the specified code is executed,
providing a guarantee that cleanup operations or resource release will happen,
even in the presence of exceptions.

A finally block can exist independently without a catch block. It allows you to
specify code that will always execute, regardless of whether an exception
occurs or not. It is commonly used for cleanup operations or resource release,
but it is not required to be accompanied by a catch block.

If an exception is thrown and caught by a catch block, but there is no finally


block, the program continues execution after the catch block. The catch block
handles the exception, and control proceeds to the next statement following
the catch block.

The finally block can rethrow an exception, but it cannot modify the caught
exception itself. the finally block cannot modify the caught exception.

The “finally” block in exception handling is used to ensure that certain code is
always executed, regardless of whether an exception occurs or not. This block
is often used for cleanup operations or releasing resources.

throw and throws keywords

OOPS 254
“throw” keyword

code eample: using throw keyword

OOPS 255
“throws” keyword

OOPS 256
code example

OOPS 257
difference between “throw” and “throws”

notes
The "throw" keyword is not used to declare that a method might throw an
exception; instead, the "throws" keyword is used for that purpose.

The "throws" keyword is not used to handle an exception within a method and
explicitly throw it.

OOPS 258
The main difference between the "throw" and "throws" keywords in Java is
that "throw" is used within a method to explicitly throw an exception, while
"throws" is used in a method declaration to indicate that the method might
throw one or more exceptions. "throw" is for immediate exception handling
within a method, while "throws" is for declaring exceptions that the method
might propagate to its caller.

When an exception is thrown using the "throw" keyword within a method, the
exception is immediately propagated to the caller of the method. The caller
can then catch and handle the exception or propagate it further.

The exception declaration in the "throws" keyword is specified in the method


declaration. It indicates the exceptions that the method might throw to its
caller.

custom exceptions

reasons to use custom exceptions

OOPS 259
code example

OOPS 260
using a custom exception

code example: using a custom exception

OOPS 261
code example: incorrect order of catch blocks

OOPS 262
notes
Custom exceptions in Java are exceptions that are created by extending the
Exception class or one of its subclasses. They allow us to handle specific
exceptional situations that are not covered by built-in exceptions.

Some reasons for using custom exceptions in Java include handling specific
exceptional situations that are unique to an application or domain. Custom
exceptions allow us to provide more meaningful and descriptive exception
messages to communicate the problem clearly.

In Java, you create a custom exception by extending the Exception class or


one of its subclasses. By creating a new class that extends Exception, you can
define your custom exception and its behavior.

Custom exceptions can improve code readability and maintainability by


providing more descriptive exception messages. These messages help
developers understand the exceptional scenarios and the actions taken to
handle them, making the code easier to read and maintain.

Catching and handling all custom exceptions within the same method may not
be appropriate in all cases. The handling of exceptions depends on the
specific requirements of the application.

OOPS 263
The purpose of creating custom exceptions in Java is to provide more specific
information about exceptional situations in a program. Custom exceptions
allow for better categorization and more meaningful error messages.

file handling basics

key concepts in file handling

OOPS 264
file operations in java

Java’s File class

OOPS 265
file class methods

code example: using the file class

OOPS 266
stream classes in java

OOPS 267
importance of proper file handling

notes
File handling in Java refers to interacting with files stored on disk or other
storage devices. It involves operations like creating, opening, reading, writing,
and closing files.

OOPS 268
The purpose of the File class in Java is to represent a file or directory and
provide methods for file-related operations. It allows you to create, delete,
check existence, and perform other operations on files.

FileReader and FileWriter are used for reading and writing character-based
data from and to files, respectively, but they are not the only stream classes
for file handling.

Proper file handling is important in Java to prevent data corruption in files. It


involves practices such as error handling, closing files after use, and handling
exceptions that may occur during file operations. Adhering to proper file
handling practices helps ensure data integrity and prevents file corruption.

Key concepts in file handling include file path (location of a file in a file
system) and file type (indicated by the file extension). These concepts are
essential for working with files and performing file operations.

file class in java

OOPS 269
commonly used file class methods

OOPS 270
code example: creating a file object

creating a new file

OOPS 271
creating a new file: code example

OOPS 272
reading file information

code example: reading file information

OOPS 273
notes
The File class in Java is used to perform file-related operations such as
creating, deleting, renaming, checking existence, and retrieving file
information.

To create a File object representing a file in the file system, you use the "new
File()" constructor with the file name as a parameter. For example, “File file =
new File("test.txt");”

The "createNewFile()" method of the File class is used to create a new file in
the file system. It returns a boolean value indicating whether the file was
successfully created.

You can retrieve the size of a file using the "length()" method of the File class.
It returns the size of the file in bytes as a long value.

FileReader and FileWriter

filereader

OOPS 274
filereader methods

code example

OOPS 275
filewriter

OOPS 276
methods

code example: using FileWriter

try-with-resources statement

OOPS 277
code example: try-with-resources

OOPS 278
notes
While you can manually call the “close()” method to close the resources, this is
not the recommended approach to ensure that resources are properly closed
after using FileReader or FileWriter objects.

Both FileReader and FileWriter classes implement the “AutoCloseable”


interface, which allows them to be used with the try-with-resources statement
for automatic resource management.

FileReader and FileWriter are the classes used for reading and writing text data
to files in a character-oriented manner.

BufferedReader and BufferedWriter

BufferedReader

OOPS 279
methods

code example: BufferedReader

OOPS 280
BufferedWriter

OOPS 281
methods

code example: using BufferedWriter

OOPS 282
importance of buffering

OOPS 283
notes
The BufferedReader class in Java is used for efficient reading of character-
based data from files, particularly by using buffering mechanisms.

The “readLine()” method is used to read lines of text from a file using the
BufferedReader class. It returns a string containing the line read, or “null” if the
end of the file is reached.

You can ensure that resources are properly closed after using BufferedReader
or BufferedWriter objects by using the try-with-resources statement. The try-
with-resources statement automatically closes the resources at the end of the
block.

Writing a line of text to a file is achieved using the “write()” method, not the
“newLine()” method.

Buffering in file handling reduces the number of disk reads and writes, which
can significantly improve performance by minimizing costly I/O operations.
Buffering allows data to be read or written in larger chunks, reducing the
frequency of disk access.

OOPS 284
FileInputStream and FileOutputStream

FileInputStream

methods

OOPS 285
code example: using FileInputStream

OOPS 286
FileOutputStream

FileOutputStream Methods

OOPS 287
code example

code example: using BufferedWriter

OOPS 288
notes
The “read()” method is used to read bytes from a file using the FileInputStream
class. It returns an integer value representing the byte read or “−1” if the end
of the file is reached.

You can ensure that resources are properly closed after using FileInputStream
or FileOutputStream objects by using the try-with-resources statement. The
try-with-resources statement automatically closes the resources at the end of
the block.

The “write()” method in the FileOutputStream class is used to write bytes to a


file.

Understanding how to efficiently handle file operations is important because it


improves the performance of file operations by reducing the number of disk
I/O operations. Efficient file handling can significantly enhance the overall
performance of a program.

FileInputStream and FileOutputStream are the classes used for reading and
writing byte data to files in a byte-oriented manner.

OOPS 289
BufferedInputStream

key methods of BufferedInputStream

code example:

OOPS 290
OOPS 291
BufferedOutputStream

code example: BufferedOutputStream

OOPS 292
code example: BufferedOutputStream

OOPS 293
importance of buffered streams

reading and writing with streams

OOPS 294
understanding streams

reading from streams

code example:

OOPS 295
reading from a file:

writing to streams

OOPS 296
code example: writing to a file

OOPS 297
importance of buffered streams

notes
Streams in Java are used to efficiently handle input and output operations,
allowing the flow of data between a program and a source or destination.

OOPS 298
InputStream is the abstract base class for all input streams but is not directly
used for reading data from a file.

appending to files

FileOutputStream for file appending

BufferedWriter for file appending

OOPS 299
code example: appending with FileOutputStream

OOPS 300
code example: appending with BufferedWriter

OOPS 301
comparing FileOutputStream and BufferedWriter

notes:
FileOutputStream is more suitable for appending binary data, while
BufferedWriter is often used for appending text data.

FileOutputStream works with binary data, not specifically for appending text
data.

OOPS 302
To open a file in append mode using FileOutputStream, you can pass true as
the second argument to the FileOutputStream constructor.

deleting and renaming files

the file class

deleting files in java

OOPS 303
code example: deleting a file in java

OOPS 304
code example: renaming a file

OOPS 305
notes
The purpose of deleting files in Java is to remove unnecessary or outdated
files from the file system.

The File class can be used for deleting files in Java.

To delete a file in Java using the File class, you can call the delete() method on
a File object.

The purpose of renaming files in Java is to change the names of existing files.

The renameTo() method of the File class can be used to rename a file in Java.

OOPS 306
practicing file handling

operations of file handling

OOPS 307
creating a file: code example

reading a file: code example

OOPS 308
writing to a file: code example

OOPS 309
appending to a file: code example

deleting a file: code example

OOPS 310
deleting a file

notes
To append content to an existing file in Java, you can use the “write()” method
of the FileWriter class with the “append” parameter set to true.

Exception handling in Java is important because it ensures the stability of


programs and handles runtime errors gracefully. It allows for error
management and the implementation of appropriate error recovery
mechanisms.

The purpose of file I/O in Java is to manage data persistence and interact with
external resources. It involves reading from and writing to files, as well as file
manipulation operations like deletion and renaming.

OOPS 311
java object model

elements of java object model

classes and objects

OOPS 312
relationships b/w objects

behavior of objects

OOPS 313
object diagram: example

OOPS 314
importance

notes:
The key elements of the Java Object Model are classes and objects. Classes
define structure and behavior, while objects are instances of those classes.

Classes encapsulate data and behaviors, while objects represent individual


entities in Java.

Aggregation represents a "has-a" relationship in Java, where an object


contains other objects.

Inheritance allows objects to share attributes and behaviors with a superclass,


promoting code reuse and hierarchy.

The behavior of objects in Java is determined by their methods. Methods


define the behavior and operations that objects can perform.

The Java object model encompasses object-oriented programming concepts


and the type system in Java. It involves understanding the Object class,
methods like equals(), hashCode(), and toString(), and concepts like type
conversion and type inquiry.

java type system

OOPS 315
primitive types

reference types

OOPS 316
type conversion

type conversion example

type checking and type safety

OOPS 317
importance of java type system

notes
The two main categories of types in the Java Type System are primitive and
reference types, also known as object types.

Boolean is an example of a primitive type in Java.

OOPS 318
The purpose of type conversion in Java is to convert values between different
types.

Implicit casting is done automatically by the compiler when assigning a value


of one type to a variable of another compatible type. Explicit casting, on the
other hand, requires a manual type conversion using casting operators.

One of the benefits of the Java Type System is that it enhances code
readability by providing meaningful information about the data being used.

type inquiry and casting

type inquiry in java

OOPS 319
type inquiry example:

type casting

OOPS 320
type inquiry and casting: points to remember

OOPS 321
notes
Type inquiry in Java refers to dynamically determining the type of an object at
runtime.

The “instanceof” operator is used for performing type inquiry in Java.

Type casting in Java refers to the process of converting an object from one
type to another.

Type casting should be used cautiously to avoid potential ClassCastException if the


object’s actual type is not compatible with the target type.

One of the benefits of type inquiry and casting in Java is that it ensures type
safety and reduces the chances of runtime errors.

OOPS 322
object class and its methods

overview of object class methods

equals() method

OOPS 323
hashCode() Method

code example: overriding equals() and hashCode()

OOPS 324
toString() Method

OOPS 325
code example: overriding toString() Method

importance of object class methods

OOPS 326
notes
The Object class is the root class of all classes in Java.

The Object class provides the equals(), hashCode(), and toString() methods.

The equals() method in the Object class compares the equality of two objects.

The toString() method in the Object class obtains a string representation of an


object

The methods provided by the Object class, such as equals(), hashCode(), and
toString(), provide essential functionality for equality comparison, generating
hash codes, and representing objects as strings.

shallow copy

OOPS 327
code example: shallow copy

code example: shallow copy

OOPS 328
what is deep copy?

code example: deep copy

OOPS 329
notes:
Shallow copy indeed copies the contents of an object as a reference, while
deep copy duplicates the contents, including any referenced objects.

Shallow copy creates a copy of the object as a reference to the original object.
Therefore, any changes made to the copied object will also affect the original
object.

Deep copy duplicates the contents of an object, including any referenced


objects. Therefore, any changes made to the copied object will not affect the
original object.

Shallow copy is preferred when memory efficiency is important, and


modifications to the copied object should not affect the original object.

Understanding the concepts of shallow copy and deep copy helps in


managing memory efficiently and choosing the appropriate copy mechanism
based on the requirements.

serialization and deserialization

OOPS 330
why use serialization?

serializable interface

OOPS 331
code example: serialization

OOPS 332
deserialization in java

OOPS 333
code example: deserialization

OOPS 334
notes
Deserialization is the process of converting a byte stream into an object.

Serialization allows us to store objects for later use or transfer objects


between different applications or systems.

OOPS 335
A class is serializable in Java by implementing the Serializable interface. The
interface acts as a marker interface to indicate that the class can be serialized.

Deserialization is the process of reconstructing an object from a serialized


byte stream.

Deserialization in Java is performed using the readObject() method of the


class. This method reads the serialized byte stream and
ObjectInputStream

reconstructs the object.

reflection API in java

uses of reflection API

OOPS 336
inspecting class using reflection

code example: inspecting class

OOPS 337
OOPS 338
using reflection API

notes
The Reflection API in Java is a feature that allows us to inspect and manipulate
classes, fields, methods, and constructors at runtime. It provides the ability to
dynamically examine and modify the structure and behavior of Java classes.

OOPS 339
The Reflection API has various uses, including introspection (examining the
structure, properties, and metadata of classes at runtime), dynamic
instantiation (creating instances of classes dynamically), accessing and
modifying fields, invoking methods, and obtaining annotations.

We can inspect a class using reflection by calling the getClass() method on an


object. This method returns the Class object representing the runtime class of
the object.

We can create instances of classes dynamically using reflection by calling the


newInstance() method on the Class object. This method creates a new instance of

the class.

Using reflection, we can access and modify fields, invoke methods (including
private ones), and work with both public and private members of a class.

The Reflection API with dynamic class loading allows for loading classes at
runtime and manipulating them dynamically. It provides capabilities for
inspecting and modifying classes, fields, methods, and constructors at
runtime.

dyanamic class loading

dynamic class loading

OOPS 340
how dynamic class loading works

code example: dynamic class loading

OOPS 341
custom class loaders

consideration and pitfalls

OOPS 342
notes
Dynamic class loading in Java refers to loading classes at runtime instead of
during compilation. It provides flexibility and enables loading classes based on
specific conditions or requirements.

Dynamic class loading is useful when different versions of a class need to be


loaded based on runtime conditions. It allows for adaptability and modularity in
applications.

Dynamic class loading in Java is achieved using the Class.forName() method. This
method takes the fully qualified name of the class as a string parameter and
returns a Class object representing that class.

The provided code example demonstrates loading the ArrayList class


dynamically using the Class.forName() method and printing its name.

When working with dynamic class loading, it is important to consider the


impact on performance and memory usage. Excessive or unnecessary class
loading can degrade performance. Proper exception handling is also essential.

The topics covered in the module on essential Java concepts include


exception handling, file I/O, the Java object model, and the Reflection API with
dynamic class loading.

OOPS 343
multithreading

importance of multithreading

code example: creating a thread

OOPS 344
OOPS 345
multithreading vs. single threading

the main thread

OOPS 346
notes
The main thread is the entry point of execution for a Java program.

The “run()” method is the entry point of execution for a thread but should not
be called directly.

Multithreading enables parallel execution of tasks, leading to improved


responsiveness and performance.

The main thread is automatically created when the program starts. It serves as
the entry point of execution for the program.

multithreading vs. multitasking

OOPS 347
understanding multithreading

code example: multithreading in java

OOPS 348
OOPS 349
multitasking

multithreading vs. multitasking

OOPS 350
advantages of multithreading

OOPS 351
choosing bw multithreading and multitasking

thread class in java

OOPS 352
thread class in multithreading

key constructors in thread class

OOPS 353
essential methods in thread class

OOPS 354
code example: using thread class

OOPS 355
OOPS 356
importance of thread class

creating threads with thread class

OOPS 357
thread creation steps

the run() method

OOPS 358
the start() method

code example: creating a thread with thread

OOPS 359
OOPS 360
benefits of creating threads with thread class

disadvantages and alternatives

OOPS 361
implementing runnable interface

creating and starting threads

OOPS 362
benefits of using runnable interface

code example: creating a thread with runnable


interface

OOPS 363
OOPS 364
runnable vs. thread

OOPS 365
creating threads with runnable interface

the runnable interface

OOPS 366
implementing the runnable interface

creating an instance of thread

code example: runnable interface

OOPS 367
benefits of using runnable interface

OOPS 368
runnable vs. thread class

thread states and life cycle

OOPS 369
thread states

new state

OOPS 370
runnable state

blocked state

waiting state

OOPS 371
timed waiting state

terminate state

OOPS 372
understanding thread transitions

thread priority and daemon threads

OOPS 373
thread priorities in java

setting thread priority

OOPS 374
code example: setting thread priority

daemon threads in java

OOPS 375
setting daemon threads

code example: daemon thread

OOPS 376
thread synchronization

the need for thread synchronization

OOPS 377
how synchronization works

synchronization in java

OOPS 378
benefits of thread synchronization

drawbacks of thread synchronization

OOPS 379
synchronized methods and blocks

OOPS 380
synchronized methods

code example: synchronized method

OOPS 381
synchronized blocks

code example: synchronized block

OOPS 382
deadlocks in java

OOPS 383
how deadlocks occur?

code example: deadlock

OOPS 384
OOPS 385
OOPS 386
OOPS 387
HOW TO AVOID DEADLOCKS?

handling deadlocks in java

OOPS 388
inter thread communication

Wait, Notify and NotifyAll methods

OOPS 389
need for inter thread communication

code example:

OOPS 390
OOPS 391
practicing inter thread comunication

understanding wait(), notify() and notifyAll()

OOPS 392
using wait()

code example: using wait()

OOPS 393
notify() and notifyAll()

OOPS 394
code example: using notify()

OOPS 395

You might also like