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

OOAD Java End of Day 14

Uploaded by

avi
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)
21 views30 pages

OOAD Java End of Day 14

Uploaded by

avi
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
You are on page 1/ 30

OOAD

Java

C code java code

JVM

CPU CPU

Compilation Process
javac
→ class file → loaded into Classloader → check for bytecode → interpreter
→ execute
→ send it to the
CPU/hardware
class file = bytecode

terminologies
JVM

JDK
software kit
JRE
Java Runtime Environment
JVM

program I/O
System.out.println()
Scanner(System.in )

nextInt()
nextLong()

nextLine() string

IDEs
IntelliJ
VScode
Eclipse
Visual Studio

Online env:
replit

Java as a language
Statically typed Language
Strongly Typed Language

keywords
boolean byte char
false true
int short long
float double

Data types

Primitive Data Types


int 4
short 2
long 8
float 4
double 8
char 2
boolean 1 bit
byte 1 byte

float
12.36
1236 x 10-2
Non Primitive Data Types
Reference Types

Arrays
Strings
Class
Objects
Interfaces

Operators

arithmetic
+
-
*
/
% modulo

assignment
=
compound
+= a += b
a=a+b
-= a = a -b
…..

relational
<
>
<=
>=
==
!=

logical
&& and
|| or
! not

unary
-
a = -100
++
post
pre

bitwise
& and
| or
^ ex-or

shift
<<
>>
>>>

<<
0011 1100 x
0111 1000 y
0001 1110 z

0011 1100 x
1111 0000 x << 2
0000 1111
+1
0001 0000

1010 0000
1010 0000 0000 0001

0001 1111 31
0000 0011 3

0000 0100 -4

terniray

Flow control

if else
if
else if
else

switch
switch
case
break
default

while
while
do while
break
continue

for
for
break
continue

for-each
loops automatically
assigns too

features:
no index
can not be effectively used to change contents of the array
moves only forward
moves only in single steps

Arrays
- dynamically allocated
- continuous memory allocation
- objects
- []

int [ ] arr = {10, 20, 30}; //length is 3


arr.length → data
String stra = “atlas” // length is 5
stra = “amazon” // length is 6
stra.length() → function

Strings

String
- objects
- immutable

String literal
- String Constant pool
- JVM optimize
new operator
- dynamically allocated
- heap

String methods
str.length()
str.toUpperCase()
str.toLowerCase()
str.indexOf(“”) the index of that particular sub-string
str.charAt() the character the specified index
str.isEmpty()

StringBuffer

at last
01 23 4

StringBuilder
faster than StringBuffer
not thread-safe

Recursion
-- function/method calling itself
public static int add(int num){
if (num > 0){
return num + add (num -1);
}
else {
return 0;
}

4 + add(3)
4 + 3 + add(2)
4 + 3 + 2 + add(1)
4 + 3 + 2 + 1 + add(0)
4+3+2+1+0
10

OOPs

general concepts
Object class is a superclass

DRY
Do not repeat yourself

vocabulary
state
(values)
properties
behaviour
methods
identity

class (memory) division


class has:
- account number
- deposit amount
- type of account

- display()

- static data (interest rate)


objw objx objy

0 234680 234682
0 2000 3000
null null savings
display()
interest rate (static data)

class declarations, in general:


modifiers
public
private
constructor
methods

declaring member variables


various kinds:
within a class → fields
within a method (or block of code) → local data
in method declaration → parameters

method name (conventions)


speak
speakLoudly
getData
runFast
changeRoomTemperature

objects
Bank objy = new Bank(234682, 3000, "savings");
Bank objy → declaration
new → instantiate
Bank(xxx, yy) → initialisation
garbage collection
JRE deletes objects when it feels that those objects are no longer being used
runs automatically
an object can be deleted, when:
-- no references to that object

Features
Encapsulation
Inheritance
Polymorphism
function/methods overloading
C++ Java
operator
C++ Python

Abstraction

static

static variable
only one memory location
shared among all objects
if changed for one object, gets changed for another object too

static methods
can access only static methods & static variables
can not use non static data/method
no this keyword
no super keyword
can be accessed without creating an object

Polymorphism
4+6
“hello” + varx

Static
compile time
go_for_dinner(Saturday)
Runtime
Run time
Function/Method Overloading (points to remember)
- num of parameters
- data types of parameters
- order of type of parameters
- not on the return type
- static method can be overloaded

Function Overriding (points to remember)


- different (or specific) implementation in a child/subclass
- static methods can not be overridden
- unless inherited class also makes it static (hides the parent’s implementation)
- method name in parent & child should be same
- parameter list & order should be same in parent & child

Encapsulation
capsule
hide the data

Inheritance
parent class or super class
child class or subclass

Unix()
Linux()

IS-A
inheritance (points to remember)
private attributes are not inherited
multiple inheritance not supported through class

super
- used to invoke parent class constructor
- use to invoke parent class method
super.method()
- used to refer parent class data variable

final
- final variables (data) can not change their value
- final methods can not be overridden
- final class can not be inherited
- final methods can be overloaded

Object & Class Relationships


Association
Composition
Aggregation

Association
association manages:
one-to-one
one-to-many
many-to-many

two forms of association:


composition
aggregation

Example
flight_one
Seat:
[empty] [empty] [empty] [empty]
[food] [food] [food] [food]
[empty] [empty] [empty] [empty]
[food] [food] [food] [food]

[empty] [empty] [empty] [empty]


[food] [food] [food] [food]

[empty] [empty] [empty] [empty]


[food] [food] [food] [food]

flight_number =

single object
Seat obja = new Seat();

Seat(){
// constructor
}

multiple objects (array form)


Seat[] arr = new Seat[2];

arr[0] = new Seat();


arr[1] = new Seat();

Seat(){
// constructor
}

constructor
same name as that of the class
no return type
can not be called explicitly
gets called implicitly (automatically) when an object is created
if not defined, then JVM will provide a default (empty) constructor
can not be static
can not be abstract
can not overridden
can be overloaded (parameterised)
can not be final

invoked when a new object is created


can have all access modifiers
abstraction
hiding the details

- abstract
- interfaces (100% abstraction)

Starters indian curries


breads rice desserts
extras

S
o masala
manchuria
u papad

abstract classes

points to remember
- abstract keyword for class (mandate)
- abstract & non-abstract methods
- even one abstract method means, class should be abstract
- no instantiation (no objects can be created)
- can have final methods
- can have constructors
- can have static methods
-

interfaces

points to remember
- it's not a class, its an interface
- interface keyword (mandate)
- all methods have to be abstract & public, unless static
- data variables
- public
- static
- final
- no instantiation (no objects can be created)
- multiple inheritance
- interface can extend one or more interface
- interface can extend only another interface
- class can implement more than one interface
- abstract
- non-abstract
- non-abstract class implementing an interface
- concrete implementation of all abstract methods
- maintain exact signature of a method
- can have private methods (java 9 onwards)
- can have static methods (java 8 onwards)
- can have overloaded methods
- can not have constructors in interfaces

inner classes and nested classes

nested classes
inner classes
- inner class
- within method (local classes)
- anonymous inner class
static nested classes

terminology/vocabulary
nested class
outer class

points to remember
- need outer class for instantiating inner class object
- local inner classes can not be invoked from outside the method
- nested interfaces (static)
- will not be private
- object of static nested class can be created without outer class object
- anonymous class
- can be abstract too

packages
collection of classes, interfaces & sub packages
helps organise classes into a folder structure
easy to find them
reusability

namespace

access specifiers
public
can be accessed from outside/within the package/within the class
private
can be accessed from within the class
protected
can be accessed from within the package/within the class

Exception Handling
Object
-- Throwable
-- Error
-- stack overflow
-- no memory
-- OS send a signal
-- JRE/JVM error
-- Exceptions
-- Checked Exceptions
discovered during compile time
-- Unchecked Exceptions
-- user defined Exceptions

Throwable
Exception
RuntimeException
NullPointerException

IOException

java.lang

keywords
try
catch
finally

finally
1. exception occurs, is handled
catch block executes
finally block executes
code continues

2. exception occurs, is not handled


finally block executes
code crashes

3. exception does not occur


finally block executes
code continues

throw
can explicitly raise exceptions
while throwing unchecked exceptions
can either catch it
or let system display the exception & stop the code
while throwing checked exceptions
mandatory to catch the exceptions

Math
Math.min(x,y)
Math.max(100, 200)
Math.pow()
Math.sqrt()
x = 23 x = -12
y = Math.abs(x)

intervals = [[3,4],[2,3],[1,2], [5,6], [4536789012, 5]

i =0
intervals[0] = [3, 4]
j = ? (0, 1, 2, 3)
res = [-1, 0, 1]

i =1
intervals[1] = [2, 3]
j = 0, 3
[3, 4] or [5, 6]

i =2
intervals[2] = [1, 2]
j = ? (0, 1, 2, 3)
0, 1, 3

i=3
intervals[3] = [5,6]
j = ? (0, 1, 2, 3)

avinatan
bkna
thakusid

Data Structures (Java)


types of DS
primitive
byte, short, int ….
non primitive
1. Linear Data Structure
a. Array
b. Linked List
c. Stack
d. Queue
…..

2. Non-Linear Data Structure


a. Tree
b. Graph
Array
linear data structure
collection of data/variables/objects
int, float
Strings
objects
referenced by a common name
contiguous memory location
data type = base type

Arrays are considered as objects


heap area (dynamic memory)
new
size of array = int
length
public final length
Object class is a superclass of array
Linear Data Structure

advantages:
random access of elements (using index)
access is faster
sorting, iteration is easier
modification (of values )

disadvantages:
size is fixed
modification (insertion, deletion) cumbersome
time taking
capacity is huge, used section is less, then memory is wasted
always needs contiguous memory locations

for(int val : arr)


{
// body of the loop
}

clone

while passing to a function:


arr
10 20 30 40 50 60

brr = arr
brr was referencing back to arr
crr = arr
crr was referencing back to arr
any changes done to crr, effects arr too

while passing to a function by clone, or by equating using cloning:


arr
10 20 30 40 50 60

brr = arr.clone()
brr is a new copied version of arr
separate area in the memory is created
crr = arr.clone()
crr is a new copied version of arr
any changes done to crr, does not effect arr

crr
6 16 26 36 46 56

multi dimensional arrays


arr[m][n]
m rows
n columns
m number of n arrays
arr [6][4]
6 one-dimensional arrays
each one dimensional array is of the size 4

ways of creating multi dimensional array:


int arr [ ] [ ] = new int [6] [4]
int [ ] [ ] arr = new int [6] [4]

Linked List
tiffin box mould

start = 7000

8055

chole bhature
7054
7000
7000

momos

8000
7054
7054

pasta (red sauce)

9011
8000
9011

shawarma

8055
8020

8020

biryani

7000
8055

8000

chicken masala

8020
9011
1st

last

Stack
- LIFO
- top
insertion & deletion

major operations
push
insert element at the top
pop
removes the top element
-------
isEmpty()
return True if it is empty
look() peek()
take the value from the top, but do not delete it

Queue
- FIFO
- Q

Hashing
key value (pairs)
319540
→ 42605
→ 665

A
B
C
D
XYZ

-- one-directional process
-- deterministic
-- uniformity
-- fixed size output
-- avoid collision
-- Message Digest

SHA-256
Secure Hash Algorithm

-- large amount of data


smaller table

Hash Functions
-- Message Digest Functions

340: ironman:suit
341: captain: hammer_shield
357: thor: hammer_thunder

Hash table
Hash Map

0 to n

division method
remainder
Data Hash Function Hash Value

23 23 % 10 = 3 3

37 7

29 9

48 8

54 4

35 5

0 1 2 3 4 5 6 7 8 9

23 54 35 37 48 29

table size = 10
load factor = num of items/ table size
6/10

H(77) = 7

i 105
d 100
l 108
e 101

“abcf” “bcfw” “cvrh” “guio”


396 418

“idle” 414
“idel” 414
“deli” 414
“lied” 414

“idle” (105*10 + 100*20 + 108*30 + 101*40)%599 =


“idel” 414
“deli” 414
“lied” 414
Collision / Clash

Linear Probing

Sorting Algorithms
rearrange the positions

Bubble Sort

{88, 14, 32, 25, 79}

88 14 32 25 79
14 88 32 25 79
14 32 88 25 79
14 32 25 88 79
-------------------------------------------
14 32 25 79 88
14 32 25 79 88
14 25 32 79 88
14 25 32 79 88

- two loops (inner & outer)


- keep swapping in the inner loop
- if current element is smaller than the adjacent element (then swap)
- repeat till the outer loop exhausts

Insertion Sort

13 15 17 18 14 12 11 19 16
13 15 17 18 14 12 11 19 16

13 15 17 14 18 12 11 19 16
13 15 14 17 18 12 11 19 16
13 14 15 17 18 12 11 19 16

13 14 15 17 18 12 11 19 16

1. pick a key (an index actually)


2. repeat steps 2 to 4 till the end of array is reached
3. compare the element at current index with the left values, if it is smaller then repeat
step 3
4. keep shifting elements from the “sorted” section of the array till the correct location of
the key is found
5. increment the loop variable (i)

Selection Sort

Merge Sort
divided & conquer algorithm

8 3 1 6 17 14

8 3 1 6 17 14

8 3 1 6 17 14
3 8 1 6 17 14

1 3 8 6 14 17

1 3 6 8 14 17

a b c d e
a b c d e
a b c

mergeSort()

merge()

Quick Sort
{ 88, 14, 32, 25, 79 }
25
14 25 88 32 79
32 88 79
79 88
14 25 32 79 88

Graphs
-- Finite Graph
-- Infinite Graph

complete graph
(every node is adjacent to every other node)
vertices = n
each vertex’s degree = n-1
number of edges = (n * (n-1) )/2

max cut vertex n-2

A 10 B
20
C D

A 10 B
20
C D

D E

Digraph

Connected Graph

edge connections
vertex node
degree
out-degree
in-degree
source vertex (in degree = zero)
path
strongly connected
(or has a path, in terms of directed graphs)

Adjacency matrix
adjacency list

cut vertex

BFS
A
D

B E
Visited → A,
Queue → B, C, D

Visited → A, B
Queue → C, D

Visited → A, B ,C
Queue → D, E

Visited → A, B , C, D
Queue → E

Visited → A, B , C, D, E
Queue →

O (ver + ed)

DFS

A
D

B E
Visited → A,
Stack → B, C, D

Visited → A, B
Stack → C, D

Visited → A, B, C
Stack → E, D

Visited → A, B, C, E,
Stack → D

Visited → A, B, C, E, D
Stack →

S A

B
D

S.visited = true
A.visited = true
D.visited = true
B.visited = true
C.visited = true

stack → S
SA
SAD
SADB
SADC
SAD
SA
S
(empty)

Display:
SADBC
Colouring
A
D

B E

You might also like