0% found this document useful (0 votes)
3 views36 pages

OOP Java Complete Notes

The document provides comprehensive study notes on Object-Oriented Programming (OOP) concepts in Java, covering topics such as static members, access modifiers, inheritance, polymorphism, abstract classes, generics, and exception handling. Each topic includes definitions, examples, and comparisons to enhance understanding. It serves as a guide for students preparing for finals in OOP Java.

Uploaded by

Hareem Farhan
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)
3 views36 pages

OOP Java Complete Notes

The document provides comprehensive study notes on Object-Oriented Programming (OOP) concepts in Java, covering topics such as static members, access modifiers, inheritance, polymorphism, abstract classes, generics, and exception handling. Each topic includes definitions, examples, and comparisons to enhance understanding. It serves as a guide for students preparing for finals in OOP Java.

Uploaded by

Hareem Farhan
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

OOP Java

Complete Finals Study Notes


Object Oriented Programming · Java · C++
All Topics Covered:
Static Members · Access Modifiers · Destructor / GC · Inheritance
Polymorphism · Abstract Classes · Generics · Exception Handling
Object Streams & Serialization · Const vs Non-Const
Classes & Relationships (UML) · Class Templates (C++) · STL (C++)
Table of Contents

1. Static Data Members & Static Methods


2. Access Modifiers
3. Destructor in Java / Garbage Collection
4. Inheritance
5. Polymorphism
6. Abstract Classes
7. Generics & Class Templates (Java)
8. Exception Handling in Java
9. Object Streams & Serialization
10. Const vs Non-Const Functions & Static Members (C++)
11. Classes & Their Relationships (UML)
12. Class Templates (C++)
13. Standard Template Library — STL (C++)
1. Static Data Members & Static Methods

What is the static keyword?


The static keyword in Java is used for memory management. A static
member belongs to the class itself, not to any individual object. Only one
copy is created and shared by all objects of that class.

Static Data Member (Class Variable)


• Declared using the static keyword inside a class.
• Shared by all objects — one value for all instances.
• Stored in the class area (method area) of memory, not in the heap.
• Memory is allocated once when the class is loaded.

Example — Without Static (each object has its own copy):


class Student {
int id;
String uni = "DUET"; // each object gets its own copy
}

Example — With Static (all objects share one copy):


class Student {
int id;
String name;
static String university = "DUET"; // shared

void display() {
[Link](id + " " + name + " " + university);
}
public static void main(String[] args) {
Student s1 = new Student();
[Link] = 1; [Link] = "Ali";
Student s2 = new Student();
[Link] = 2; [Link] = "Rohail";
[Link]();
[Link]();
}
}
// Output:
// 1 Ali DUET
// 2 Rohail DUET <-- university is shared

Static Methods (Static Functions)


• Belong to the class, not to any object.
• Can be called using the class name — no object needed:
[Link]()
• Can only directly access other static members (not instance/non-
static variables).
• Cannot use this or super keywords.

Static Method Example — Object Counter:


class Counter {
static int count = 0;

Counter() {
count++; // increments shared counter each time object
is made
}

static void showCount() {


[Link]("Total Objects: " + count);
}

public static void main(String[] args) {


Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
[Link]();
}
}
// Output: Total Objects: 3

Static vs Non-Static — Quick Comparison


Feature Static Non-Static
Belongs to Class Object
Object needed? No Yes
Called by [Link]() [Link]()
Memory One copy (class area) One copy per object
(heap)
Access Static members only All members
(directly)
Example university name student ID
⚠ Static methods CANNOT access non-static instance variables
directly. This is the most common exam question about static.
2. Access Modifiers

Access modifiers in Java control the visibility (scope) of classes,


variables, methods, constructors, and data members. There are 4 types of
access modifiers in Java.

The Four Access Modifiers


Modifier Within Within Subclass Outside
Class Package (outside pkg) Package
private Yes No No No
default Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes

1. private
Access is only within the same class. Cannot be accessed from outside
the class at all. If you need to access private variables from outside, use
getter/setter methods.
class Data {
private String name; // only accessible inside Data class

// getter method
public String getName() {
return [Link];
}
// setter method
public void setName(String name) {
[Link] = name;
}
}
public class Main {
public static void main(String[] args) {
Data d = new Data();
[Link]("Programiz");
[Link]([Link]());
}
}

2. default (no keyword)


When no access modifier is specified, it defaults to package-level
access. Accessible anywhere within the same package, but NOT from
outside the package.
class Animal {
void display() { // default access — no keyword written
[Link]("Animal");
}
}

3. protected
Accessible within the package AND by subclasses outside the package
through inheritance. If you do not create a child class, it cannot be
accessed from outside the package.
class Animal {
protected void display() {
[Link]("Animal");
}
}
class Dog extends Animal {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // OK — Dog is a subclass
}
}

4. public
The access level is everywhere. It can be accessed from within the class,
outside the class, within the package, and outside the package. No
restrictions.
public class Animal {
public void display() {
[Link]("Animal");
}
}

✅ Memory tip: private < default < protected < public (increasing
visibility order)
3. Destructor in Java / Garbage Collection

What is a Destructor?
A destructor is a special method used to destroy an object and free
memory when the object is no longer needed. It works opposite to a
constructor: constructor creates/initializes, destructor destroys.
⚠ Java does NOT have explicit destructors like C++. Java uses
automatic Garbage Collection (GC) instead.

How Objects are Destroyed in Java


The Garbage Collector (GC) automatically removes objects when:
• The object is no longer referenced by any variable.
• The program ends.
• A reference is explicitly set to null.

The finalize() Method


Java provides the finalize() method (deprecated in Java 9+) which is called
by the GC before destroying an object. You can override it to perform
cleanup. Use [Link]() to request GC (not guaranteed to run
immediately).
class Test {
protected void finalize() {
[Link]("Object destroyed");
}
public static void main(String[] args) {
Test t1 = new Test();
t1 = null; // object is now eligible for GC
[Link](); // request garbage collector to run
}
}
// Output: Object destroyed

Constructor vs Destructor
Feature Constructor Destructor
Purpose Initialize object Destroy object
Called when Object is created Object is removed/GC
runs
Feature Constructor Destructor
In Java Yes (explicit) No explicit — GC
handles it
Automatic? No — you write it Yes — GC does it
automatically
Keyword Same name as class finalize() method (Java)

✅ One-line viva answer: "Java does not have destructors; memory is


released automatically by the Garbage Collector."
4. Inheritance

What is Inheritance?
Inheritance is a mechanism in Java where one class acquires all the
properties and behaviors of a parent class. It represents an IS-A
relationship between two classes. The main purpose is code reusability
— child classes can reuse methods of the parent class.
Keyword used: extends
class Parent {
// parent code
}

class Child extends Parent {


// child code — inherits everything from Parent
}

Simple Example:
class super {
public void display() {
[Link]("I am parent class");
}
}
class sub extends super {
public static void main(String[] args) {
sub message = new sub();
[Link](); // calls parent method
}
}
// Output: I am parent class

Types of Inheritance in Java


Type Description Supported in
Java?
Single One child inherits from one parent Yes
Multi-level A inherits B, B inherits C (chain) Yes
Hierarchical Multiple children from one parent Yes
Multiple One child inherits from multiple NO — not via
parents classes
Type Description Supported in
Java?
Hybrid Mix of multiple types Partially (via
interfaces)

⚠ Multiple inheritance is NOT supported in Java through classes to


avoid the "Diamond Problem". It can be achieved through Interfaces.

Key Terms
• Superclass (Parent class) — the class being inherited from.
• Subclass (Child class) — the class that inherits.
• IS-A relationship — e.g., a Car IS-A Vehicle.
• Method Overriding — child class redefines a method of the parent
class.
• super keyword — used to call parent class constructor or method.
5. Polymorphism

What is Polymorphism?
Polymorphism means "many forms". It is the ability of an object to take
more than one form. In Java, it allows multiple objects of different
subclasses to be treated as objects of a single parent class, while
automatically selecting the proper method to apply based on the actual
object type.
More precisely: it means a call to a member function will cause a different
function to be executed depending on the type of object that invokes it.

Types of Polymorphism
Type Also Called How Achieved When
Resolved
Compile-time Static / Early Method Overloading, At compile
Binding Operator Overloading time
Run-time Dynamic / Late Method Overriding At runtime
Binding (Virtual Functions) by JVM

1. Method Overloading (Compile-time Polymorphism)


Multiple methods with the same name but different parameters (different
number, type, or order). Resolved at compile time.
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) { // same name, different
params
return a + b;
}
int add(int a, int b, int c) { // same name, 3 params
return a + b + c;
}
}

2. Method Overriding (Run-time Polymorphism)


A child class provides a different implementation of a method already
defined in the parent class. Same name, same parameters. Resolved at
runtime by JVM.
class Animal {
void sound() {
[Link]("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Woof");
}
}
class Cat extends Animal {
@Override
void sound() {
[Link]("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal a;
a = new Dog(); [Link](); // Woof
a = new Cat(); [Link](); // Meow
}
}

Overloading vs Overriding
Feature Overloading Overriding
Occurs in Same class Parent and child class
Parameters Must be different Must be same
Return type Can differ Must be same (or
covariant)
Binding Compile time (static) Runtime (dynamic)
Polymorphism Compile-time Runtime
Keyword None needed @Override
(recommended)
6. Abstract Classes

What is Abstraction?
Abstraction is the process of hiding implementation details and showing
only the functionality to the user. It lets you focus on what the object does,
not how it does it.
Two ways to achieve abstraction in Java:
• Abstract class (0% to 100% abstraction)
• Interface (100% abstraction)

Abstract Class
A class declared with the abstract keyword. It can have both abstract
methods (no body) and non-abstract methods (with body).
Key Rules:
• Must be declared with abstract keyword.
• Can have abstract AND non-abstract methods.
• Cannot be instantiated — you cannot create objects of an abstract
class directly.
• Can have constructors and static methods.
• Can have final methods (which force subclass not to override them).
• Subclass must implement all abstract methods (or itself be
abstract).
// Abstract class — cannot create object of it directly
abstract class Bike {
abstract void run(); // abstract method — no body
}

class Honda extends Bike {


void run() { // must implement abstract
method
[Link]("running safely");
}
public static void main(String[] args) {
Bike obj = new Honda(); // OK — Honda is concrete
[Link]();
}
}
// Output: running safely
Cannot Instantiate an Abstract Class:
abstract class Language {
// fields and methods
}

// This will throw an error:


Language obj = new Language(); // ERROR: cannot instantiate
abstract class

// This is correct:
class English extends Language { /* implement methods */ }
Language obj = new English(); // OK

Abstract Method
A method declared with abstract keyword that has no body. The subclass
must provide the implementation.
abstract void printStatus(); // no method body — subclass must
implement

Abstract Class vs Interface


Feature Abstract Class Interface
Abstraction 0% to 100% 100%
Methods Abstract + concrete Only abstract
methods (default/static in Java 8+)
Variables Any type Only public static final
Inheritance extends (single) implements (multiple)
Constructor Can have Cannot have
Access modifiers Any public by default
7. Generics & Class Templates (Java)

C++ Templates vs Java Generics


Java does NOT support templates like C++. Instead, Java provides
Generics — a similar concept that allows classes and methods to work
with different data types while maintaining type safety.
C++ Concept Java Equivalent
Templates Generics
Class Templates Generic Classes
Function Templates Generic Methods

Generic Class — Box Example


The <T> is a type parameter. It can be replaced with any object type
(Integer, String, etc.) when creating an instance.
class Box<T> {
T value;

void setValue(T value) {


[Link] = value;
}

T getValue() {
return value;
}
}

// Using the generic class:


Box<Integer> intBox = new Box<>();
[Link](10);
[Link]([Link]()); // 10

Box<String> strBox = new Box<>();


[Link]("Hello");
[Link]([Link]()); // Hello

Generic Method
class Printer {
public <T> void print(T item) {
[Link](item);
}
}

Printer p = new Printer();


[Link](100); // prints integer
[Link]("Hello"); // prints string

Benefits of Generics
• Type safety — detects type errors at compile time.
• Code reusability — one class works for multiple types.
• Eliminates need for explicit type casting.
8. Exception Handling in Java

What is an Exception?
An exception is an unwanted or unexpected event that disrupts the normal
flow of a program. Exception handling allows the program to gracefully
handle runtime errors.

Exception Hierarchy
• Throwable — root of all exceptions.
• Error — serious problems (StackOverflowError, OutOfMemoryError)
— not recoverable.
• Exception — recoverable problems.
• — Checked exceptions: must be handled (IOException,
SQLException).
• — Unchecked exceptions (RuntimeException):
NullPointerException, ArrayIndexOutOfBoundsException, etc.

try-catch-finally Block
try {
// code that might throw an exception
int result = 10 / 0;
} catch (ArithmeticException e) {
// handle the exception
[Link]("Cannot divide by zero: " +
[Link]());
} catch (Exception e) {
// catch any other exception
[Link]("Error: " + [Link]());
} finally {
// always executes — used for cleanup (closing files, etc.)
[Link]("This always runs");
}

throw and throws Keywords


Keyword Usage Example
throw Used to explicitly throw an throw new
exception ArithmeticException("error");
throws Declares that a method may void myMethod() throws
Keyword Usage Example
throw an exception IOException { }

throw Example:
public class Main {
static void checkAge(int age) {
if (age < 18)
throw new ArithmeticException("Not eligible to
vote");
else
[Link]("Eligible to vote");
}
public static void main(String[] args) {
checkAge(15); // throws exception
}
}
// Output: Exception in thread "main"
[Link]: Not eligible to vote

Custom Exception
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}

public class Main {


public static void main(String[] args) {
try {
throw new MyException("This is my custom exception");
} catch (MyException e) {
[Link]("Caught: " + [Link]());
}
}
}

Common Exception Types


Exception Cause
NullPointerException Accessing method/field on null
reference
ArrayIndexOutOfBoundsException Accessing invalid array index
ArithmeticException Divide by zero
Exception Cause
ClassCastException Invalid type cast
NumberFormatException Invalid string to number conversion
IOException File/IO operation failure
FileNotFoundException File does not exist
9. Object Streams & Serialization

What is Serialization?
Serialization is the process of converting an object into a byte stream so
it can be saved to a file, database, or sent over a network. Deserialization
is the reverse — converting the byte stream back into an object.

Key Points
• A class must implement the Serializable interface to be serialized.
• The Serializable interface is a marker interface — it has no
methods.
• Use ObjectOutputStream to serialize (write) objects.
• Use ObjectInputStream to deserialize (read) objects.
• Fields marked with transient keyword are NOT serialized.
• The class must have the same serialVersionUID for deserialization
to work.

Serialization Example (Writing Object to File)


import [Link].*;

class Student implements Serializable {


int id;
String name;

Student(int id, String name) {


[Link] = id;
[Link] = name;
}
}

public class SerializeDemo {


public static void main(String[] args) {
Student s = new Student(1, "Ali");
try {
FileOutputStream fos = new
FileOutputStream("[Link]");
ObjectOutputStream oos = new ObjectOutputStream(fos);
[Link](s); // serialize the object
[Link]();
[Link]("Object serialized successfully");
} catch (IOException e) {
[Link]();
}
}
}

Deserialization Example (Reading Object from File)


public class DeserializeDemo {
public static void main(String[] args) {
try {
FileInputStream fis = new
FileInputStream("[Link]");
ObjectInputStream ois = new ObjectInputStream(fis);
Student s = (Student) [Link](); //
deserialize
[Link]();
[Link]("ID: " + [Link] + ", Name: " +
[Link]);
} catch (IOException | ClassNotFoundException e) {
[Link]();
}
}
}
// Output: ID: 1, Name: Ali

transient Keyword
Fields marked as transient are skipped during serialization. Use this for
sensitive data like passwords.
class Student implements Serializable {
int id;
String name;
transient String password; // will NOT be serialized
}

Object Streams Summary


Class Purpose
ObjectOutputStream Writes (serializes) an object to a
stream
ObjectInputStream Reads (deserializes) an object from
a stream
FileOutputStream Writes bytes to a file
FileInputStream Reads bytes from a file
Serializable Marker interface — enables
serialization
Class Purpose
transient Keyword to exclude fields from
serialization
10. Const vs Non-Const Functions & Static
Members (C++)

Constant Member Function


A const member function is declared with the const keyword at the end
of the function signature. It guarantees that the function will NOT modify
the object it is called on. It is recommended to use const to avoid
accidental changes.
• A const member function can be called by any type of object (const
or non-const).
• A non-const function can only be called by non-const objects.
• Syntax: ReturnType functionName() const { function body }
#include<iostream>
using namespace std;

class Test {
int value;
public:
Test(int v = 0) { value = v; }
int getValue() const { return value; } // const function —
cannot modify
void setValue(int v) { value = v; } // non-const
function
};

int main() {
const Test t(10);
cout << [Link](); // OK — calling const function on
const object
// [Link](20); // ERROR — cannot call non-const on
const object
}

Non-Constant Function
A non-const function can modify the object's data. It can only be called on
non-const objects. If you try to call a non-const function on a const object,
the compiler gives an error.
⚠ If a const object tries to call a non-const function, the error is:
"passing const X as this argument discards qualifiers"
Data Members & Member Functions — Memory
Representation
• Each newly created object has its own copies of the class's data
members.
• Member functions are stored only ONCE in memory — shared by all
objects.
• This makes sense because all objects use the same function code.
• Data items hold different values per object — each object gets a
separate copy.
• Functions are identical across objects — created once when class is
defined.
Diagram concept: Object 1 has data1, data2. Object 2 has data1, data2.
Object 3 has data1, data2. All three share the same function1() and
function2() in memory.

Static Data Member


• Declared using the static keyword.
• No matter how many objects are created, there is only ONE copy of
the static member.
• Shared by all objects of the class.
• All static data is initialized to zero when the first object is created (if
no other initialization).
• Cannot be initialized inside the class — initialized outside using
scope resolution operator ::

Static Member Functions


• By declaring a function as static, you make it independent of any
particular object.
• Can be called even if no objects of the class exist.
• Accessed using class name and scope resolution operator:
ClassName::functionName()
• Can only access static data members, other static functions, and
functions from outside the class.
• Have class scope — not tied to any instance.

Const vs Non-Const Comparison


Feature Const Function Non-Const Function
Can modify object? No Yes
Called by const Yes No (error)
object?
Called by non-const Yes Yes
object?
Keyword placement After parameter list: No keyword needed
void f() const
11. Classes & Their Relationships (UML)

Defining a Class
A CLASS is a template (specification, blueprint) for a collection of objects
that share a common set of attributes and operations. Objects are
instances of a class.

UML Class Diagram


A Class Diagram describes the structure of a system. It shows the
system's classes, attributes, operations (methods), and relationships
among classes.
A UML class is represented as a rectangle with 3 sections: Top = Class
Name, Middle = Attributes, Bottom = Operations (methods).

Essential Elements of a UML Class Diagram


• Class — the entity being modeled.
• Attributes — data/properties of the class.
• Operations — methods/behaviors of the class.
• Relationships — how classes connect to each other.

Types of Relationships
Relationship Symbol/Line Description Example
Association Solid line with A general connection Employee
arrow between two classes works for
Company
Aggregation Open diamond HAS-A (weak): parts Faculty has
can exist without the CourseTeachi
whole ng
Composition Filled diamond HAS-A (strong): parts SalesOrder
cannot exist without has LineItems
the whole
Dependency Dashed arrow A change in one class Dependent
may affect another class uses
(weaker) Reference
Relationship Symbol/Line Description Example
class
Generalization Solid line + IS-A relationship Car IS-A
open triangle (inheritance). Arrow Vehicle
arrow points to parent
Realization Dashed line + Class is derived from Interface class
open triangle an interface instead of -> Derived
a base class class

Aggregation vs Composition — Key Difference


Feature Aggregation Composition
Relationship type Weak HAS-A Strong HAS-A
Parts exist without Yes No — parts die with
whole? whole
Ownership Shared Exclusive
UML symbol Open (hollow) Filled (solid) diamond
diamond
Example Faculty has SalesOrder has
CourseTeaching LineItems

Generalization
Deriving a class out of a parent class, having some inherited property (from
the parent) and some new property of the derived class. The term
generalization refers to inheritance viewed from the bottom up — from
derived class to parent class. Represented by a solid line with a large open
arrowhead pointing towards the parent class.

Dependency
A dependency is a weaker form of relationship. It states that a change in
specification of one class may affect another class that uses it, but not vice
versa. Represented by dashed lines with an arrow.

Realization
Realization is very similar to inheritance. The difference is that a class is
derived from an interface instead of a base class. An interface is an
abstract class. Represented by a dashed line with an open arrowhead.
12. Class Templates (C++)

What are Templates?


Templates allow writing generic code — code that works with any data
type. The simple idea is to pass data type as a parameter so that we don't
need to write the same code for different data types. C++ adds two
keywords to support templates: template and typename (typename can
always be replaced by class).

How Templates Work


• Templates are expanded at compiler time (like macros, but with
type checking).
• The compiler does type checking before template expansion.
• Source code contains only one function/class, but compiled code may
contain multiple copies for each type used.

Function Template — Example


template <typename T>
T myMax(T x, T y) {
return (x > y) ? x : y;
}

int main() {
cout << myMax<int>(3, 7) << endl; // uses int version
-> 7
cout << myMax<char>('g', 'e') << endl; // uses char version
-> g
return 0;
}
// Compiler internally generates:
// int myMax(int x, int y) { return (x>y)?x:y; }
// char myMax(char x, char y) { return (x>y)?x:y; }

Class Template — Example


template <typename T>
class Box {
T value;
public:
void setValue(T v) { value = v; }
T getValue() { return value; }
};
int main() {
Box<int> intBox;
[Link](10);
cout << [Link](); // 10

Box<string> strBox;
[Link]("Hello");
cout << [Link](); // Hello
}

✅ Java equivalent of C++ Templates is Generics. C++ uses


template<typename T>, Java uses <T>.
C++ Concept Java Equivalent
template<typename T> <T> (Generics)
Class Templates Generic Classes
Function Templates Generic Methods
template keyword No keyword — just <T>
13. Standard Template Library (STL) — C++

What is the Standard Library?


In C++, the Standard Library is a collection of classes and functions. It
can be categorized into two parts: (1) The Standard Function Library and
(2) The Object-Oriented Class Library.

What is the Standard Template Library (STL)?


The STL is a set of C++ template classes that provide common
programming data structures and functions such as lists, stacks, arrays,
etc. A working knowledge of template classes is a prerequisite for working
with STL.

3 Components of STL
Component Purpose Analogy
Containers Store and hold data (objects) Data Storage
Algorithms Manipulate and process data Data Access /
in containers Operations
Iterators Pointer-like objects to access Like array indexes
individual elements in but for any container
containers

1. Containers
Container classes store objects and data. There are 7 standard first-class
container classes and 3 container adaptor classes.
Sequence Containers — accessed in sequential order:
Container Description
vector Dynamic array — resizable, random access, fast at
end
list Doubly linked list — fast insert/erase anywhere, no
random access
Container Description
deque Double-ended queue — fast insert/erase at both front
and back

Associative Containers — key-based access (sorted):


Container Description
set Stores unique keys in sorted order
map Stores key-value pairs, sorted by key
multiset Like set but allows duplicate keys
multimap Like map but allows duplicate keys

Container Adaptors — built on top of sequence containers:


Adaptor Description
stack LIFO — Last In First Out. Built on deque or vector
queue FIFO — First In First Out. Built on list or deque
priority_queue Elements inserted in sorted order; removal from front

2. Iterators
Iterators are pointer-like entries used to access individual elements in a
container. They are commonly used to move sequentially from element to
element — a process called iterating through the container.
#include<vector>
#include<iostream>
using namespace std;

int main() {
vector<int> v = {10, 20, 30, 40};

// Using iterator to traverse vector


vector<int>::iterator it;
for (it = [Link](); it != [Link](); it++) {
cout << *it << " ";
}
// Output: 10 20 30 40
}
3. Algorithms
STL provides many built-in algorithms that work on containers via iterators.
Include <algorithm> header.
#include<algorithm>
#include<vector>
using namespace std;

int main() {
vector<int> v = {3, 1, 4, 1, 5, 9};

sort([Link](), [Link]()); // sort in ascending order


// v is now: 1 1 3 4 5 9

auto it = find([Link](), [Link](), 4); // find element 4


if (it != [Link]()) cout << "Found: " << *it;

int total = 0;
for (int x : v) total += x;
cout << "Sum: " << total;
}

STL Quick Summary


Concept One-liner
STL Set of C++ template classes for data
structures & algorithms
Container Stores/holds data (vector, list, map, etc.)
Sequence Container Accessed sequentially — vector, list, deque
Associative Container Key-based access — set, map
Container Adaptor Built on others — stack (LIFO), queue (FIFO)
Iterator Pointer-like object to traverse container
elements
Algorithm Reusable operations — sort(), find(), count()
Template keyword template<typename T> — used to write
generic code

Quick Viva Reference


Concept Answer
static belongs to Class (not object)
static copies One single copy
static method object needed? No — call via [Link]()
Most restrictive modifier private
Least restrictive modifier public
Java destructor? No — uses Garbage Collector (GC)
finalize() purpose Called before GC destroys an
object
Inheritance keyword extends
Multiple inheritance in Java Not supported via classes — use
interfaces
Polymorphism types Compile-time (overloading) and
Runtime (overriding)
Abstract class instantiated? No — cannot create objects
Abstract method has body? No — subclass must implement
Java generics = C++ ? Java Generics = C++ Templates
Serialization interface Serializable (marker interface)
Skip field in serialization Use transient keyword
C++ const function can modify No
object?
C++ const function called by? Any object — both const and non-
const
UML Aggregation symbol Open (hollow) diamond
UML Composition symbol Filled (solid) diamond
STL 3 components Containers, Algorithms, Iterators
C++ template keywords template and typename
Stack order LIFO — Last In First Out
Concept Answer
Queue order FIFO — First In First Out

You might also like