You are on page 1of 61

Write a program with an encapsulated class Student(rollno, name, marks) with

functions to set, display, get and input data. In main function, create 02 student
objects, input and display their data.

#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class Student
{
int rollno;
char name[30];
int marks;
public:
void SetData(int r0, char *n0, int m0)
{
rollno = r0;
strcpy(name, n0);
marks = m0;
}
void DispData()
{
cout << "Rollno=" << rollno << endl;
cout << "Name=" << name << endl;
cout << "Marks=" << marks << endl;
}
void InputData()
{
cout << "give rollno" << endl;
cin >> rollno;
cout << "give name" << endl;
cin >> name;
cout << "give marks" << endl;
cin >> marks;
}
int GetRollno()
{
return rollno;
}
char * GetName()
{
return name;
}
int GetMarks()
{
return marks;
}
};
int main()
{
Student s1, s2;
s1.InputData();
s2.InputData();
s1.DispData();
s2.DispData();
cout <<"Rollno=" << s1.GetRollno() << endl;
s1.SetData(1, "abc", 80);
s1.DispData();
getch();
return 0;
}

Write a program with an encapsulated class Product (PId, PName, Qty) with functions
to set, display, input and get data. In main function, create 02 Product objects,
input and display their data.

Arrrays of Objects
-----------------

Write a program with an encapsulated class Student(rollno, name, marks) with


functions to set, display, get and input data. In main function, create an array of
10 Student objects, input and dipslay their data.

#include...
class Student
{
...
};
int main()
{
Student s[10];//Array of objects
int i;
cout << "Give Student data" << endl;
for (i=0; i<10; i++)
{
s[i].InputData();
}
cout << "You input" << endl;
for (i=0; i<10; i++)
{
s[i].DispData();
}
// code to display data of the students
// having marks in the range of 80 to 100
for (i=0; i<10; i++)
{
if (s[i].GetMarks() >= 80 &&
s[i].GetMarks() <=100 )
s[i].DispData();
}
getch();
return 0;
}
////////////////////////
Paper Work:
Write a program with an encapsulated class Product(PId, Pname, Price) with
functions to set, display, get and input data. In main function, create an array of
10 Product objects, input and dipslay their data.

Write a program with an encapsulated class Student(rollno, name, marks) with


functions to set, display, get and input data. In main function, create an array of
10 Student objects, input and dipslay data of the student having the highest
marks.

int main()
{
Student s[10];//
int i, loc, highest;
cout << "Give Student data" << endl;
for (i=0; i<10; i++)
{
s[i].InputData();
}
loc = 0;
highest = s[0].GetMarks();
for (i=1; i<10; i++)
{
if (s[i].GetMarks() > highest)
{
highest = s[i].GetMarks();
loc = i;
}
}
cout << "Data of the student having the highest marks" << endl;
s[loc].DispData();
getch();
return 0;
}

Assignment:
Write a program with an encapsulated class Employee(EId, Ename, Salary) with
functions to set, display, get and input data. In main function, create an array of
10 Emplopyee objects, input and dipslay their data.

Paper/Lab Work:
Write a program with an encapsulated class Product (PId, Pname, Price). In main
function, input an array of 10 Product objects and display data of the product
having the lowest price.
//////////////////////////////

Pointers and Pointers to Objects


--------------------------------
Pointers contain addresses of memory locations and are used to perform dynamic
memory allocation and de-allocation.
Write a program with an encapsulated class
Student(rollno, name, marks). Create 10 student objects using pointers, input and
display their data.

#include...
class Student
{
....
};
int main()
{
Student * s; // Pointer declaration
s = new Student[10];

// (s+0)->InputData();
// (s+1)->InputData();
int i;
for (i=0; i<10; i++)
{
(s+i)->InputData();
}
for (i=0; i<10; i++)
{
(s+i)->DispData();
}
delete [] s;
getch();
return 0;
}

Paper Work:
For Product (PId, PName, qty) scenario, create 10 Product objects using pointers,
input and display their data.

Quiz:
Write a program with an encapsulated class Employee (EId, Ename, Salary) with
functions to input, set, get and display data. In main function create 10 Employee
objects using pointers and display data of the Employee having the highest salary.

Assignment:
Write a program with an encapsulated class Vehicle (VId, ModelName, Price). In main
function create 10 Vehicle objects using pointers and display count of the Vehicles
having price in the range of 900000 to 1500000 and ModelName starting with 'M'.
if ((v+i)->GetPrice() >= 900000 &&
(v+i)->GetPrice() <= 1500000 &&
(v+i)->GetModelName()[0] == 'M' )
-------------------------------

Constructors
------------
The constructors contain code that is executed when an object is being created.
A constructor has the same name as that of class. It can not return a value.

The constructors are used to perform initialization activities.

Every class has a default constructor that exists when no constructor is written by
the programmer. The default constructor takes no arguments.

Example
-------
class A
{
int i;
public:
A()
{ cout << "Constructor with no args executed"
<< endl;
}
};
int main()
{
A a1;
getch();
return 0;
}
Overloading
-----------
int sum(int a, int b)
{
return a+b;
}
int sum(int a, int b, int c)
{
return a+b+c;
}
Constructor Overloading
-----------------------
The constructors can be overloaded by providing different number or types of
arguments.

e.g.
A()
{
cout << "Constructor with no args executed"
<< endl;
}
A(int a)
{
cout << "Constructor with 01 arg executed"
<< endl;
}
A(int a, int b)
{
cout << "Constructor with 02 args executed"
<< endl;
}
-------------------------------
Write a program with an encapsulated class Student (rollno, name, marks) having
appropriate constructors and functions to set, display, get and input data. In
main function create objects and display data.

#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class Student
{
int rollno;
char name[30];
int marks;
public:
Student()
{
rollno = 0;
strcpy(name,"");
marks = 0;
}
Student (int r, char * n, int m)
{
rollno = r;
strcpy(name,n);
marks = m;
}
void SetData(int r, char * n, int m)
{
rollno = r;
strcpy(name,n);
marks = m;
}
void DispData()
{
cout << "Rollno=" << rollno << endl;
cout << "Name=" << name << endl;
cout << "Marks=" << marks << endl;
}
void InputData()
{
cout << "give rollno" << endl;
cin >> rollno;
cout << "give name" << endl;
cin >> name;
cout << "give marks" << endl;
cin >> marks;
}
int GetRollno()
{
return rollno;
}
char * GetName()
{
return name;
}
int GetMarks()
{
return marks;
}
};
int main()
{
Student s1;
Student s2(7, "abcd", 85);
s1.DispData();
s2.DispData();
getch();
return 0;
}

---------------------------------
Practical Work:
Write a program with an encapsulated class Product (PId, Pname, Qty) having
appropriate constructors and functions to set, display, get and input data. In
main function create objects and display data.
------ ---------------------------

this keyword in C++


--------------------
The "this" keyword in C++ is a pointer to the current object whose member is being
accessed. It may be used to resolve ambiguity while accessing class level members
and function arguments.
int rollno;
Student (int rollno, char * name, int marks)
{
this->rollno = rollno;
strcpy(this->name,name);
this->marks = marks;
}
void SetData(int rollno, char * name, int marks)
{
this->rollno = rollno;
strcpy(this->name,name);
this->marks = marks;
}

--------------------
Access Specifiers in C++
There are 03 access specifiers for class members
private
------
The members declared as private are accessible only within the class in which they
are declared. In C++ class, the members are private by default.
protected
---------
The members declared as protected are accessible in the class in which they are
declared and in the child class.
public
------
The members declared as public are accessible anywhere within the code.
----------------------------------

class A {
private:
int i;
protected:
int j;
public:
int k;
};
class B: public A
{
private:
int l;
protected:
int m;
public:
int n;
void DispData(){
//cout <<"i=" <<i << endl;
cout <<"j=" <<j << endl;
cout <<"k=" <<k << endl;
}
};
int main()
{
A a1;
//a1.i=7;
//a1.j=8;
a1.k = 9;

B b1;
//b1.i=6;
//b1.j=7;
b1.k=8;
// b1.l=9;
// b1.m=10;
b1.n=11;
getch();
return 0;
}
-------------------------------
Inheritance
Using inheritance data members and member functions are inherited to a child class.
In general, there are two types of inheritance:

Single Inheritance
In single inheritance, a child class may have only one parent. e.g. Java
class B extends A

Multiple Inheritance
In multiple inheritance, a child class may have more than one parent. e.g. C++
Example:
class B: private A
class B: public A, private C, public D
...
Destructors
-----------
The destructors contain code that is executed when an object is being destroyed.
The destructors can not be overloaded. It is used to perform finalization
activities.
closing files, closing network connections
class A
{
public:
~A()
{ cout <<"Object destroyed" << endl;
}
};

Constructors and Destructors in Inheritance


------------------------------------------
Whenever an object of a child class is created, it invokes
the construtctor of the parent class. By default, the constructor
with no arguments of the parent class is invoked. The programmer
can change this behavior by using : with constructor of child class.
When the object of a child class is being destroyed, the part
of the parent class is also destroyed, so the parent's destructor
is also called.

#include<iostream>
using namespace std;
#include<conio.h>
class A
{
public:
A(){cout << " A constructor with No args" << endl;
}
A(int i) {
cout << " A constructor with int args=" <<i << endl;
}
~A()
{
cout << "A dest" << endl;
}
};
class B: public A
{
public:
B(){
cout << "B no args" << endl;
}
B(int i):A(i){
cout << "B int args" << endl;
}
~B()
{cout <<"B object destroyed" << endl;
}
};

int main()
{
B b1(7);

getch();
return 0;

Types of inheritance in C++


--------------------------
Private Inheritance
Using private inheritance, the inherited members become private with reference to
the child class. Such members are not accessible outside the child class. By
default, the inheritance is private in C++.
become private
Public Inheritnace
Using public inheritance, the inherited members
continue their existence and access scope with reference to the child class.
class B: public A
Protected Inheritance
Using protected inheritance, the inerhited members become protected, and therefore,
such members are not accessible outside the child class.

#include<iostream>
using namespace std;
#include<conio.h>
class A
{
int i;
protected:
int j;
public:
int k;
};
class B: public A
{
//j k
int l;
protected:
int m;
public:
int n;

};
class C: public B
{

};
int main()
{
A a;
B b;
C c;
//a.i=5;
//a.j=5;
a.k=5;
//b.i=5;
//b.j=5;
b.k=5;
//c.i=5;
//c.j=5;
c.k=5;
getch();
return 0;
}

#include<iostream>
using namespace std;
#include<conio.h>
class A
{

int i;
protected:
int j;
public:
int k;
};
class B: public A
{

public:
void dispIJK()
{
// cout << "i=" << i << endl;
cout << "j=" << j << endl;
cout << "k=" << k << endl;
}
};
class C: protected B
{
public:
void dispIJK()
{
// cout << "i=" << i << endl;
cout << "j=" << j << endl;
cout << "k=" << k << endl;
}
};
int main()
{
A a;
B b;
C c;
b.dispIJK();
c.dispIJK();

// cout << "i=" << a.i << endl;


//cout << "j=" << a.j << endl;
cout << "k=" << a.k << endl;
//cout << "i=" << b.i << endl;
//cout << "j=" << b.j << endl;
cout << "k=" << b.k << endl;
// cout << "i=" << c.i << endl;
//cout << "j=" << c.j << endl;
//cout << "k=" << c.k << endl;
getch();
return 0;
}

Scope Resolution Operator ::


-------------------------
The scope resolution operator is used to
resolve ambiguity while accessing members of different
classes. :: is the scope resolution operator.
e.g.
Student::DispData()

// Write program with an encapsulated class


// Student (rollno, name). Use inheritance
// for implementation of 02 child classes
// StudentBCS(FScMarks) and StudentMCS(BscMarks).
// In main function, write code to input
// data of 02 objects of BCS and MCS students,
// and display the data.

#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>

class Student
{
protected:
int rollno;
char name[30];
Student()
{
rollno = 0;
strcpy(name, "");
}
Student(int rollno, char * name)
{
this->rollno = rollno;
strcpy(this->name, name);
}
void SetData(int rollno, char * name)
{
this->rollno = rollno;
strcpy(this->name, name);
}
void DispData()
{
cout << "Rollno=" << rollno << endl;
cout << "Name=" << name << endl;
}
void InputData()
{
cin >> rollno;
cin >> name;
}
int GetRollno()
{
return rollno;
}
char * GetName()
{
return name;
}
~Student()
{
cout << "Student memory de-allocated" << endl;
}
};
class StudentMCS: public Student
{
int BScMarks;
public:
StudentMCS()
{
BScMarks = 0;
}
StudentMCS(int rollno, char *name, int BScMarks):
Student(rollno, name)
{
this->BScMarks = BScMarks;
}
void SetData(int rollno, char * name, int BScMarks)
{
Student::SetData(rollno, name);
this->BScMarks = BScMarks;
}
void DispData()
{
Student::DispData();
cout << "BscMarks=" << BScMarks << endl;
}
void InputData()
{
Student::InputData();
cin >> BScMarks;
}
~StudentMCS()
{
cout <<"SMCS deleted" << endl;
}
int GetRollno()
{
return Student::GetRollno();
}
char * GetName()
{
return Student::GetName();
}
int GetBScMarks()
{
return BScMarks;
}
};
class StudentBCS: public Student
{
int FScMarks;
public:
StudentBCS()
{
FScMarks = 0;
}
StudentBCS(int rollno, char *name, int FScMarks):
Student(rollno, name)
{
this->FScMarks = FScMarks;
}
void SetData(int rollno, char * name, int FScMarks)
{
Student::SetData(rollno, name);
this->FScMarks = FScMarks;
}
void DispData()
{
Student::DispData();
cout << "FscMarks=" << FScMarks << endl;
}
void InputData()
{
Student::InputData();
cin >> FScMarks;
}
~StudentBCS()
{
cout <<"SBCS deleted" << endl;
}
int GetRollno()
{
return Student::GetRollno();
}
char * GetName()
{
return Student::GetName();
}
int GetFScMarks()
{
return FScMarks;
}
};

int main()
{
StudentMCS * m = new StudentMCS[2];
int i=0;
for (i=0; i<2; i++)
(m+i)->InputData();
for (i=0; i<2; i++)
(m+i)->DispData();
delete [] m;
/////////////////////////
StudentBCS * b = new StudentBCS[2];
for (i=0; i<2; i++)
(b+i)->InputData();
for (i=0; i<2; i++)
(b+i)->DispData();
delete [] b;
getch();
return 0;
}

// Assignment: Write code with encapsulated class Employee (EId, Ename). Use
inheritance for implementation of 02 child classes EmployeeRegular (ESalary) and
EmployeePartTime (EHours, ERate). In main, create 05 objects of both employees,
input and display their data.

// Practical Assignment: Write a program with encapsulated class Student (rollno,


name). Use inheritance for implementation of 02 child classes StudentBCS(marks[8]
[6]) and StudentMCS(marks[4][6]). In main, create 50 objects of both BCS and MCS
students, input their data and display
1. Students having passed the exam
2. Students with highest marks

-------------------
// Copy constructor
// A copy constructor receives as argument
// an object of the same class.
// When a copy of an object is created,
// the default copy constructor is called
// which copies each member data to new
// object's members.
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
int i;
public:
void setI(int i)
{
this->i = i;
}
void dispI()
{
cout << "i=" << i<< endl;
}
A(){}
A (A& a)
{
cout << "copy constructor called" << endl;
this->i = a.i;
}
};

int main()
{
A a1;
a1.setI(10);
A a2 = a1;
a2.dispI();
A a3(a2);
a3.dispI();
getch();
return 0;
}

---------------
Deep Copy
// Deep Copy
// When a copy of an object is created,
// the default copy constructor is called
// which copies each member data to new
// object's member. For pointer data,
// however, the pointer data must be
// re-initialized and then copied.
// It is accomplished using the programmer
// defined copy constructor which performs
// the Deep Copy.
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
int i;
int * ptr;
public:
void setI(int i)
{
this->i = i;
}

void dispIPtr()
{
cout << "i=" << i<< endl;
cout << ptr[0] << " " << ptr[1] << endl;
}
A(){ptr = new int [2];
ptr[0] = 5; ptr[1] = 7;}
A (A& a)
{
cout << "copy constructor called" << endl;
this->i = a.i;
ptr = new int [2];
ptr[0] = 6; ptr[1] = 8;
}
};

int main()
{
A a1;
a1.setI(10);
a1.dispIPtr();
A a2 = a1;
a2.dispIPtr();
A a3(a2);
a3.dispIPtr();
getch();
return 0;
}
--------------------------
Nested Class in C++
In C++, a class can be embedded within another class. The members of a nested class
can be accessed by using reference of outer class.

#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class C1
{
int i;
public:
class C2
{
private:
int j;
public:
void setJ(int j)
{
this->j = j;
}
void dispJ()
{
cout << "j=" << j << endl;
}
};
private:
C2 c02;
public:
void setData(int i, C2 c02)
{
this->i = i;
this->c02 = c02;
}
void dispData()
{
cout << "i=" << i << endl;
c02.dispJ();
}
};

int main()
{
C1 c01;
C1::C2 c02;
c02.setJ(8);
c01.setData(5, c02);
c01.dispData();
getch();
return 0;
}
------------------------------
Friend Functions
A function declared to be a friend of a class can access private members of that
class.
e.g.
friend void function1();

#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
int i;
friend void function1();
};
void function1()
{
A a;
a.i=10;
cout << "a.i=" << a.i << endl;
}
int main()
{
function1();
getch();
return 0;
}
Friend Classes
----------------
If a class Y is declared to be a friend of class X, then all methods of the class Y
can access private members of the class X.
// Friend classes
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
int i;
friend class B;
};
class B
{
public:
void function1()
{
A a;
a.i=10;
cout << " In function1, a.i=" << a.i << endl;
}
void function2()
{
A a;
a.i=10;
cout << "In function2, a.i=" << a.i << endl;
}

};

int main()
{
B b;
b.function1();
b.function2();
getch();
return 0;
}
------------------------------
Operator Overloading
-------------------
The existing C++ operators can be overloaded to make them work for other than pre-
defined data types. For instance, we can use ++ operator with objects in addition
to simple data types.
int i=5;
++i;
A a1,a2;
++a;
a2 = a1 + a2;

The operators can be overloaded by defining function using the following format:

return-type classname::operator op(argtype)


{

}
e.g.
++i; i++; ++a;
A A::operator++(void)
{
++i;
return *this;
}
A a;
++a;

// Operator overloading
// Overloading Unary operators
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
int i;
public:
void setI(int i)
{
this->i = i;
}
void dispI()
{
cout << "i=" << i<< endl;
}
A operator ++(void);
A operator ++(int);
};

A A::operator++(void)
{
++i;
return *this;
}
A A::operator++(int)
{
i++;
return *this;
/*
A a3;
i++;
a3.setI(i);
return a3;*/
}

int main()
{
A a;
a.setI(10);
++a;
a.dispI();
a++;
a.dispI();
A a5;
++a;
getch();
return 0;
}

// Operator overloading
// Overloading Binary operators
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
int i;
public:
void setI(int i)
{
this->i = i;
}
void dispI()
{
cout << "i=" << i<< endl;
}
A operator +(A a0);
A operator -(A a0);
};
++a1
a3 = a1 + a2;
/*A a1, a2;
a1.setI(7);
a2.setI(5);
A a3;
a3 = a1 + a2;
*/

int k =5;
int i = 6;
int j = 7;
a3 = a1 + a2;
A A::operator + (A a0)
{
A a5;
a5.setI(this->i+a0.i);
return a5;
}
A A::operator - (A a0)
{
this->i = this->i - a0.i;
return *this;
}
/*A A::operator + (int k)
{
A a3;
a3.setI(this->i+k);
return a3;
}*/

int main()
{
A a1, a2, a3;
a1.setI(10);
a2.setI(20);
a3 = a1 + a2;
a3.dispI();
a3 = a1 - a2;
a3.dispI();
getch();
return 0;
}
cout << i << endl;
cout <<a2 ;
cin >> a2;
ostream cout;
// Operator overloading
// Overloading << and >> operators

#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>

class A
{
int i;
public:
void setI(int i)
{
this->i = i;
}
void dispI()
{
cout << "i=" << i<< endl;
}
friend ostream & operator << ( ostream &os, const A &a);
friend istream & operator >> ( istream &is, A &a);
};

ostream & operator << ( ostream & os, const A & a)


{
os << " i=" << a.i << endl;
return os;
}

istream & operator >> ( istream & is, A & a)


{
cout << "Give i " << endl;
is >> a.i;
return is;
}

int main()
{
A a1;
cin >> a1;
cout << a1 << endl;
getch();
return 0;
}

Assignment:
1. Write an encapsulated class Student and

a) overload the operators ++, -- to perform pre and post increment/decrement in the
marks of the object and return the same object.
b) overload the operator * to multiply marks with an integer.
c) overload the << and >> operator to display all and input all data members of
Student

In main function call the operators and display the output.

++s1; s1++; --s1; s1--;

s2 = s1 * 2;
cout << s1<< endl;
cin >> s1;

Static Keyword
---------------
The static keyword is used with variables that retain their existence during
multiple calls of functions. In classes, the static keyword is used for class-level
members that may be accessed without using object reference.
Example
// Static data
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
public:
static int i;
static void f1()
{
i++;
cout << "f1 called" << endl;
}
};
int A::i = 0;

int main()
{
A a;
a.i=5;
A a2;
A::i=7;
cout << a.i << " " << A::i << " " << a2.i << endl;
A::f1();
a.f1();
getch();
return 0;
}

// Exceptions
// Exceptions are the error conditions
// which may occur during execution of
// the program. An exception must
// be caught to avoid abnormal termination
// of the program. This is called
// exception handling.

// Exception Handling
// throw statement
// The throw statement is used to raise
// an exception.
// try-block
// The try block contains statements
// which may raise an exception.
// catch-block
// The catch block contains statements
// which are executed when an exception
// occurs. It contains the exception
// handler code.

// Built-in exceptions
// The C++ language contains a few
// built-in exceptions such as
// bad_alloc
// Programmer-defined exceptions
// A programmer may define his own
// exception by inheriting the exception
// class.

#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>

int main()
{
int i, j;
cout << "Give i and j" << endl;
cin >> i >> j;
try{
if (j==0)
{
throw string("Division by zero");
} else
cout << "Result=" << i/j << endl;
}catch( string s)
{
cout << s << endl;
}
cout << "abc" << endl;
getch();
return 0;
}

// Exception Handling
// Built-in exceptions
// bad_alloc
// bad_cast
// bad_typeid
// bad_exception
// out_of_range
// invalid_argument
// overflow_error
// ios_base::failure
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>

int main()
{
try{
float * f = new float [9900000000];
f[0] = 5;
cout << f[0] << endl;
delete [] f;
}catch( bad_alloc ba)
{
cout <<"Some error occured, Details:" << endl;
cout << ba.what() << endl;
}
getch();
return 0;
}
// Exception Handling
// Programmer-defined exceptions
// To implement the programmer defined
// exceptions, the built-in exception class
// must be inherited. The
// const char * what() function
// may be overriden in the child class
// to return customized error message.

#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>

class MyException: public exception


{
char msg [100];
public:
MyException(char * msg)
{
strcpy(this->msg, msg);
}
const char * what()
{
return msg;
}
void printError()
{
cout << "Error:" << msg << endl;
}
};
int main()
{
float i, j;
cout << "Give i and j" << endl;
cin >> i >> j;
try{
if (j==0)
throw MyException("Div by zero");
else
cout << "Result=" << i/j << endl;

}catch(MyException me)
{
cout << me.what() << endl;
me.printError();
}
getch();
return 0;
}
// Exception Handling
// Catching all exceptions
try{
.....
....
} catch(Exception1 e){
} catch(Exception2 e){
}
try{
...
......
}catch(...){
}
//All exceptions may be caught by using
// ... in catch block arguments
//try{
//}catch(...)
//{
//}

// To handle uncaught exceptions,


// a function may be defined which is
// set to be executed by using the
// set_terminate function.
// e.g. set_terminate(stopper);

Namespaces in C++
------------------
The namespaces are used to organize data and code to avoid ambiguities.

#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>

namespace NS
{
string s1("first");
int p1=10;
void f1(){cout << s1 << endl;
}
}
using namespace NS;

int main()
{
cout << NS::s1;
NS::f1();
cout << p1 << endl;
getch();
return 0;
}

---------------------------------
// Early Binding and Late Binding

// Using early binding, the compiler


// makes decision at the compile time
// regarding which function
// should be called by using a pointer
// to object.
// Using late biding, the compiler generates
// code
// to make decision at runtime regarding
// which function should be called
// by using a pointer to object.
// To perform late binding, the virtual
// keyword is used with the function
// in the base class.

#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
public:
virtual void f1()
{
cout << "f1 of A called" << endl;
}
};
class B: public A
{
public:
void f1()
{
cout << "f1 of B called" << endl;
}
};

int main()
{
A * ptr;
A a2;
B b;
ptr = &a2;
ptr->f1();
ptr = &b;
ptr->f1();
getch();
return 0;
}
-----------------------------
// Runtime Polymorphism
// A method written in a base class
// is overridden by another method in
// derived class. A pointer to a base
// class is used with virtual keyword
// to decide which function to call at
// runtime. This is termed as
// runtime polymorphism.

#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
public:
virtual void f1()
{
cout << "f1 of A called" << endl;
}
};
class B: public A
{
public:
void f1()
{
cout << "f1 of B called" << endl;
}
};

class C: public A
{
public:
void f1()
{
cout << "f1 of C called" << endl;
}
};
int main()
{
A * ptr;
B b;
C c;
ptr = &b;
ptr->f1();
ptr = &c;
ptr->f1();
getch();
return 0;
}
--------------------------
// Pure Virtual Functions and Abstract
// Classes
// A pure virtual function is a function
// without its implementation in a base
// class. e.g. virtual void f1() = 0;
// A class containing a pure virtual
// function is termed as an abstract class.
// It is not possible to create objects
// of an abstract class. A child class
// of an abstract class should implement
// the pure virtual functions of the
// parent abstract class otherwise the
// child class also becomes the abstract
// class.
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
public:
virtual void f1() = 0;
};
class B: public A
{
public:
void f1()
{
cout << "f1 of B called" << endl;
}
};

class C: public A
{
public:
void f1()
{
cout << "f1 of C called" << endl;
}
};

int main()
{
//A a;
A * ptr;
B b;
C c;
ptr = &b;
ptr->f1();
ptr = &c;
ptr->f1();
getch();
return 0;
}
--------------------------
The Standard Template Library (STL)
----------------------------------
The Standard Template Library contains different data structures as containers
which can be used to store data.
The STL consists of
i) Containers
ii) Iterators
iii) Function objects
iv) Algorithms

Containers
-----------
The containers are built-in data structures in STL which are used to store
data.

list -- double linked list


queue -- FIFO queue
deque -- double-ended-queue
priority_queue -- priority queue
stack -- LIFO
vector -- A 1-dim array
map -- to store keys and values
multimap -- to store multiple values against each key
set -- sorted collection of unique items
multiset -- set with multiple values per key
bitset -- to set, reset and check individual bits

Iterators
---------
Iterators in STL are used for traversal within containers.
vector <int>::iterator v;
Function Objects
---------------
Function objects are used to customize behavior of the algorithms in STL.
Algorithms
-----------
Different predefined algorithms such as those for sorting, searching, finding
minimum and maximum are given in STL.

Examples STL -- Vector


-------------
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
#include<vector>
int main()
{
vector <int> v(3);
v[0] = 5;
v[1] = 6;
v[2] = 7;
for (int i=0; i < v.size(); i++)
cout << v[i] << endl;
v.push_back(8);
v.pop_back();

vector <int>::iterator itr;

for (itr=v.begin(); itr!=v.end(); itr++)


cout << *itr << endl;
getch();
return 0;
}

Example STL -- Deque


#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
#include<deque>
int main()
{
deque <int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.pop_back();
v.push_back(4);
v.pop_front();
v.push_back(5);

deque <int>::iterator itr;


for (itr=v.begin(); itr!=v.end(); itr++)
cout << *itr << endl;
getch();
return 0;
}
-----
Example STL -- MAP
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
#include<map>
int main()
{
map <int, string> m;
m[0] = "abc";
m[1] = "ghi";
m[2] = "def";
m[1] = "pqr";
//pair<int, string> item (1, "rst");
//m.insert(item);// function works for new keys only

map <int, string>::iterator itr;


for (itr=m.begin(); itr!=m.end(); itr++)
cout << itr->first << itr->second << endl;
getch();
return 0;
}
Example STL -- Stack
---------
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
#include<stack>
// There is no iterator for stack
int main()
{
stack <int> v;
v.push(1);
v.push(2);
v.push(3);
v.pop();

while (!v.empty())
{
cout << v.top() << endl;
v.pop();
}

getch();
return 0;
}

#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
#include<queue>
int main()
{
queue <int> v;
v.push(1);
v.push(2);
v.push(3);
v.pop();

while (!v.empty())
{
cout << v.front() << endl;
v.pop();
}
getch();
return 0;
}
--------------------
Virtual destructors
--------------------
In C++, if the delete keyword is used with the pointer to base class, then only the
destructor of the base class is called. Consequently, we have to use the virtual
keyword with the destructor of the base class to destroy both parts, i.e. the child
and the parent.
// Virtual Destructor
#include<iostream>
using namespace std;
#include<conio.h>
class A
{
protected:
int i;
public:
virtual ~A(){cout <<"Destructor A executed" << endl;
}
};
class B: public A
{
public:
~B(){cout <<"Destructor B executed" << endl;
}
};
int main()
{
A *a;
B *b = new B;
a = b;
delete a;
getch();
return 0;
}

virtual base classes


--------------------
Consider the hierarchy for the following scenario using inheritance.

In C++, using multiple inheritance, the ambiguity may occur while accessing member
of grandparent in th grandchild class. It is not clear to the compiler which copy
of the parent will be used in the grandchild class. Using the virtual keyword, the
virtual base classes share the same copy during inheritance which resolves the
ambiguity.

// Virtual Base Classes

#include<iostream>
using namespace std;
#include<conio.h>
class A
{
protected:
int X;

};
class B: virtual public A
{

};
class C: virtual public A
{

};
class D: public B, public C
{
public:
int GetData()
{
return X;
}
void SetData(int X)
{
this->X = X;
}
};
int main()
{

D d;
d.SetData(50);
cout << "X=" << d.GetData() << endl;
getch();
return 0;
}

Association, Generalization, Specialization, Aggregation and Composition


---------------------
In Software Engineering, the Unified Modelling language (UML) is used to visualize
design of a system, It has various sumbols for describing design in object-oriented
software engineering.
Association
-----------
It is used to represent relationship between objects. e.g.
- owners feed pets, pets please owners (association)
- a tail is part of dogs and cats (aggregation/composition)
- a cat is a kind of pet (inheritance/generalization/specialization)

Assocations are represented by lines between classes with an arrow indicating the
direction.

Symbol: Association __________


Aggregation -- diamond white
Composition -- diamond filled
Inheritnace -- arrow with triangle

Association vs Aggregation vs Composition


--------------------------
Aggregation and composition are types of association
Aggregation: A relationship where the child can exist independently of the parent
Class (parent) Student (Child)
If the class is removed, and student continues to exist, then
Composition: A relation where the child can not exist independently of the parent
e.g. House (Parent) Room (Child)
If we remove house object and room object is also removed, then ..

Composition Example-2
-------
Person |
------

----- ---- ----


Head | Hand | Leg|

Aggregation example-2

EngineInspection Car

Engine Wheel

Generalization vs Specialization
-------------------------------
Generaliztion is combining similar classes into a single general class.

Specialization is reverse of generalization which means creating sub-classes from


an existing class.

IS-A and HAS-A Relationships


----------------------------
IS-A relationship represents inheritance

StudentMCS IS-A Student

HAS-A relation represents membership

class C1{
};
class C2{
C1 c00;
};

C2 HAS-A C1

File Handling in C++


---------------------
// Writing data to a text file
#include<iostream>
using namespace std;
#include<conio.h>
#include<fstream>
int main()
{
ofstream ofs ("f1.txt");// Open for writing
ofs << "First Line " << endl;
ofs << "Second line" << endl;
ofs << "Third line" << endl;
ofs.close();
getch();
return 0;
}
// Reading data from a text file
#include<iostream>
using namespace std;
#include<conio.h>
#include<fstream>
int main()
{
ifstream ifs ("f1.txt");
char str1[80];
while (1)
{
ifs.getline(str1, 80);
if (ifs.eof()) break;
cout << str1 << endl;
}
ifs.close();
getch();
return 0;
}

// Writing data to a binary file


#include<iostream>
using namespace std;
#include<conio.h>
#include<fstream>
#include<string.h>
class Student
{
int rollno;
char name[30];
int marks;
public:
Student()
{
rollno = 0;
strcpy(name, "");
marks = 0;
}
Student (int rollno, char *name, int marks)
{
this->rollno = rollno;
strcpy(this->name,name);
this->marks = marks;
}
void setData(int rollno, char *name, int marks)
{
this->rollno = rollno;
strcpy(this->name,name);
this->marks = marks;
}
void inputData()
{
cout<< "Give student data" << endl;
cin >> rollno >> name >> marks;
}
void dispData()
{
cout << "rollno =" <<rollno << endl;
cout << "Name=" << name << endl;
cout << "Marks=" << marks << endl;
}
int getRollno()
{
return rollno;
}
char * getName()
{
return name;
}
int getMarks()
{
return marks;
}
};

int main()
{
ofstream ofs ("f1.bin", ios_base::app);// Append ; Creation mode
Student s;
s.inputData();
ofs.write (reinterpret_cast<char*>(&s), sizeof(s));
ofs.close();
cout << "Data successfully written" << endl;
getch();
return 0;
}

//Reading data from a binary file


#include<iostream>
using namespace std;
#include<conio.h>
#include<fstream>
#include<string.h>
class Student
{
int rollno;
char name[30];
int marks;
public:
Student()
{
rollno = 0;
strcpy(name, "");
marks = 0;
}
Student (int rollno, char *name, int marks)
{
this->rollno = rollno;
strcpy(this->name,name);
this->marks = marks;
}
void setData(int rollno, char *name, int marks)
{
this->rollno = rollno;
strcpy(this->name,name);
this->marks = marks;
}
void inputData()
{
cout<< "Give student data" << endl;
cin >> rollno >> name >> marks;
}
void dispData()
{
cout << "rollno =" <<rollno << endl;
cout << "Name=" << name << endl;
cout << "Marks=" << marks << endl;
}
int getRollno()
{
return rollno;
}
char * getName()
{
return name;
}
int getMarks()
{
return marks;
}
};

int main()
{
ifstream ifs ("f1.bin");
Student s;
while (ifs.read (reinterpret_cast<char*> (&s), sizeof(s)))
{
cout << "*** The student data ***" << endl;
s.dispData();
}
ifs.close();
getch();
return 0;
}

// File Handling Project with Menu


#include<iostream>
using namespace std;
#include<conio.h>
#include<fstream>
#include<string.h>
class Student
{
int rollno;
char name[30];
int marks;
public:
Student()
{
rollno = 0;
strcpy(name, "");
marks = 0;
}
Student (int rollno, char *name, int marks)
{
this->rollno = rollno;
strcpy(this->name,name);
this->marks = marks;
}
void setData(int rollno, char *name, int marks)
{
this->rollno = rollno;
strcpy(this->name,name);
this->marks = marks;
}
void inputData()
{
cout<< "Give student data" << endl;
cin >> rollno >> name >> marks;
}
void dispData()
{
cout << "rollno =" <<rollno << endl;
cout << "Name=" << name << endl;
cout << "Marks=" << marks << endl;
}
int getRollno()
{
return rollno;
}
char * getName()
{
return name;
}
int getMarks()
{
return marks;
}
};

void AddData()
{
Student s;
s.inputData();
ofstream ofs("student.bin", ios_base::app);
ofs.write(reinterpret_cast<char*>(&s), sizeof(s));
ofs.close();
cout << "Data successfully stored" << endl;
}
void DisplayData()
{
ifstream ifs ("student.bin");
Student s;
while (ifs.read (reinterpret_cast<char*> (&s), sizeof(s)))
{
cout << "*** The student data ***" << endl;
s.dispData();
}
ifs.close();
}
void ModifyData()
{
int r;
cout << "Enter rollno whose record is to be modified" << endl;
cin >> r;
ifstream ifs ("student.bin");
ofstream ofs ("temp.bin");
Student s;
while (ifs.read (reinterpret_cast<char*> (&s), sizeof(s)))
{
if (s.getRollno() == r)
{
s.inputData();
}
ofs.write (reinterpret_cast<char*> (&s), sizeof(s));
}
ifs.close();
ofs.close();
ofstream ofs2 ("student.bin");
ifstream ifs2 ("temp.bin");
while (ifs2.read (reinterpret_cast<char*> (&s), sizeof(s)))
{
ofs2.write (reinterpret_cast<char*> (&s), sizeof(s));
}
ifs2.close();
ofs2.close();
cout << "Data successfully modified" << endl;
}
void DeleteData()
{
int r;
cout << "Enter rollno whose record is to be deleted" << endl;
cin >> r;
ifstream ifs ("student.bin");
ofstream ofs ("temp.bin");
Student s;
while (ifs.read (reinterpret_cast<char*> (&s), sizeof(s)))
{
if (s.getRollno() != r)
{
ofs.write (reinterpret_cast<char*> (&s), sizeof(s));
}
}
ifs.close();
ofs.close();
ofstream ofs2 ("student.bin");
ifstream ifs2 ("temp.bin");
while (ifs2.read (reinterpret_cast<char*> (&s), sizeof(s)))
{
ofs2.write (reinterpret_cast<char*> (&s), sizeof(s));
}
ifs2.close();
ofs2.close();
cout << "Data successfully deleted" << endl;
}
void DisplayHighest()
{
ifstream ifs ("student.bin");
Student s;
int count = 0;
while (ifs.read (reinterpret_cast<char*> (&s), sizeof(s)))
{
count++;
}
ifs.close();
Student s2[count];
ifstream ifs2 ("student.bin");
int i = 0;
while (ifs2.read (reinterpret_cast<char*> (&s), sizeof(s)))
{
s2[i] = s;
i++;
}
ifs2.close();

int large = s2[0].getMarks();


int loc = 0;
for (i=1; i<count; i++)
{
if (s2[i].getMarks() > large)
{
large = s2[i].getMarks();
loc = i;
}
}
cout << "Student with the highest marks" << endl;
s2[loc].dispData();
}
int main()
{
char ch;
while (1)
{
cout <<"1. Add Student data" << endl;
cout <<"2. Display all Students data" << endl;
cout <<"3. Modify Student data" << endl;
cout <<"4. Delete Student data" << endl;
cout <<"5. Display student with highest marks" <<endl;
cout <<"6. Exit" << endl;
ch = getche();
cout << endl;
if (ch =='1')
AddData();
else if (ch =='2')
DisplayData();
else if (ch =='3')
ModifyData();
else if (ch =='4')
DeleteData();
else if (ch =='5')
DisplayHighest();
else if (ch =='6')
break;
else
cout << "Invalid option" << endl;
}

getch();
return 0;
}

Python OOP Concepts


--------------------
Python supports object-oriented programming.
class keyword
For each method within the class, there is "self" argument which should be present
to represent the current object/instance.
By default the members of classes are public. They can be made private or
protected
__ _

class MyClass:
def method1(self):
print("Method1 called")

obj1 = MyClass()
obj1.method1()

########## Constructors and Overloading

#Constructors and overloading of constructors


#__init__(self)
class MyClass:
j=0
def __init__(self,j=None):
if j==None:
self.j=0
else:
self.j = j
def dispData(self):
print("j=", self.j)

obj1 = MyClass(7)
obj1.dispData()

###### Student Class Scenario


#Student class Scenario
class Student:
rollno=0
name=""
marks=0
def __init__(self,rollno=None,name=None,marks=None):
if rollno == None:
self.rollno=0
self.name=""
self.marks=0
else:
self.rollno=rollno
self.name=name
self.marks=marks
def setData(self, rollno, name, marks):
self.rollno = rollno
self.name = name
self.marks = marks
def dispData(self):
print("Rollno=", self.rollno)
print("Name=", self.name)
print("Marks=", self.marks)
def inputData(self):
self.rollno = int(input("Give rollno: "))
self.name = input("Give name: ")
self.marks = int(input("Give marks: "))
def getMarks(self):
return self.marks
def __del__(self):
print("Object deleted")

s= Student()
s2 = Student(1,"abc", 78)
print("Marks=",s2.getMarks())
s.dispData()
s2.dispData()
########## List of Objects in Python

#List of objects
s3=[]
for i in range(0,3):
temp = Student()
s3.append(temp)

for i in range(0,3):
s3[i].inputData()
for i in range(0,3):
s3[i].dispData()

print("Marks=", s3[2].marks)
print("Marks=", s3[2].getMarks())

'''
Assignment: Write a program in Python with Product(PId, PName, Qty) class having
proper functions to set, input, display data with constructors and destructor.
Write code to input data of list of 10 Product objects and display the input data.
'''

############## Inheritance in Python

#Inheritance
class Student:
rollno=0
name=""

def __init__(self,rollno=None,name=None):
if rollno == None:
self.rollno=0
self.name=""
else:
self.rollno=rollno
self.name=name
def setData(self, rollno, name):
self.rollno = rollno
self.name = name
def dispData(self):
print("Rollno=", self.rollno)
print("Name=", self.name)
def inputData(self):
self.rollno = int(input("Give rollno: "))
self.name = input("Give name: ")
def getName(self):
return self.name
def __del__(self):
print("Object deleted")

class StudentBCS(Student):
fscMarks=0
def __init__(self,rollno=None, name=None, fscMarks=None):
if rollno==None:
Student.__init__(self)
self.fscMarks=0
else:
Student.__init__(self,rollno, name)
self.fscMarks = fscMarks
def inputData(self):
Student.inputData(self)
self.fscMarks = int(input("Give Fsc marks: "))
def setData(self, rollno, name, fscMarks):
Student.setData(self, rollno, name)
self.fscMarks = fscMarks
def dispData(self):
Student.dispData(self)
print("FScmarks=", self.fscMarks)
def __del__(self):
print("deleted StudentBCS")
Student.__del__(self)

#List of objects
s3=[]
for i in range(0,3):
temp = StudentBCS()
s3.append(temp)
s3[i].inputData()

for i in range(0,3):
s3[i].dispData()

'''
Assignment: Write code in Python with encapsulated class Employee(EId, Ename). Use
inheritance for implementation of 02 child classes EmployeeRegular(ESalary) and
EmployeePartTime(EHours, ERate). In main code, create 05 objects of both
EmployeeRegular and Employee PartTime classes, input their data and display the
employee earning the highest salary.
'''

#File Handling in Python


# Object Serialization
'''
Serialization is the process of storing object data to a file which can be
retrieved later through de-serialization. The term "Pickling" is used to refer
conversion to byte stream, whereas, "un-pickling" means conversion from byte stream
to object. Another term marshalling is used as alternative to pickling.
Using Pickle module
import pickle
pickle.HIGHEST_PROTOCOL
for large objects
pickle.DEFAULT_PROTOCOL
for text formats and backward compatibility
pickle.dump(obj, file, protocol=None) to serialize
pickle.load(file) to de-serialize
'''

class Student:
rollno=0
name=""
marks=0
def __init__(self,rollno=None,name=None,marks=None):
if rollno == None:
self.rollno=0
self.name=""
self.marks=0
else:
self.rollno=rollno
self.name=name
self.marks=marks
def setData(self, rollno, name, marks):
self.rollno = rollno
self.name = name
self.marks = marks
def dispData(self):
print("Rollno=", self.rollno)
print("Name=", self.name)
print("Marks=", self.marks)
def inputData(self):
self.rollno = int(input("Give rollno: "))
self.name = input("Give name: ")
self.marks = int(input("Give marks: "))
def getMarks(self):
return self.marks
def __del__(self):
print("Object deleted")

#File processing
import pickle
#fp = open("student.bin","ab")
fp = open("student.bin","wb")
s= Student()
s2 = Student(1,"abc", 78)
s3= Student()
s3.inputData()
pickle.dump(s,fp,pickle.DEFAULT_PROTOCOL)
pickle.dump(s2,fp,pickle.DEFAULT_PROTOCOL)
pickle.dump(s3,fp,pickle.DEFAULT_PROTOCOL)
print("Data written to file")
fp.close()
print("Student file data")
try:
fp2 = open("student.bin","rb")
s = pickle.load(fp2)
while s:
s.dispData()
s = pickle.load(fp2)
except EOFError:
pass
fp2.close()

'''
Assignment: Write a program in Python with Product(PId, PName, Qty) class having
proper functions to set, input, display data with constructors and destructor.
Write code to input data of 10 Product objects, store the data to a binary file
"Product.bin". Write another program to read data from the binary file and display
it.
'''
#Reading data into List of objects
import pickle
class Student:
....
ar1 = []
s= Student()
try:
fp2 = open("student.bin","rb")
s = pickle.load(fp2)
while s:
s.dispData()
ar1.append(s)
s = pickle.load(fp2)
except EOFError:
pass
fp2.close()

# Display highest
high = ar1[0].marks
loc = 0
for i in range (1, len(ar1)):
if ar1[i].marks > high:
high = ar1[i].marks
loc = i
print("Data of student with highest marks")
ar1[loc].dispData()

'''
Assignment: Write a program in Python with Product(PId, PName, Qty) class having
proper functions to set, input, display data with constructors and destructor.
Write code to input data of 10 Product objects, store the data to a binary file
"Product.bin". Write another program to read data from the binary file and display
data of the student having the highest marks.
'''

Java OOP Concepts


--------------------
// JDK with NetBeans
/*
// Java is an object-oriented language.
// Java programs are portable and secure. These are executed by the Java Virtual
Machine (JVM).
After compilation, bytecode is generated that may be executed by JVM.
for-loop
while
do while
continue break
switch
while (true)
Array of Objects

Student s[] = new Student[10];


s.length
for (i=0; i<10; i++){
s[i] = new Student();
s[i].inputData();
}
for (i=0; i<10; i++){
s[i].dispData();
}
final int i= 5;

Scope
------- Same Same different diff
class package package pack
subclass non-subcla
private Y N N N
default Y Y N N
protected Y Y Y N
public Y Y Y Y

javac test0.java
java Test

General format:
package statements
import statements
classes and interfaces
*/
//package pk1;
import java.io.*;
import java.util.Scanner;
class Input{
//private int q = 0;
public static int getInt(){
int r=0;
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
r = Integer.parseInt(s);
}catch(Exception e){}
return r;
}
public static float getFloat(){
float r=0;
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
r = Float.parseFloat(s);
}catch(Exception e){}
return r;
}
public static String getString(){
String s="";
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine();
}catch(Exception e){}
return s;
}
}
class Test {
static int i=5;
public static void main(String args[]) {
System.out.println("Hello world");
Test2 t2 = new Test2();
t2.method1();
System.out.println("i="+i);
Student s = new Student();
s.setData(1,"abc",80);
s.dispData();
s.inputData();
s.dispData();
}
}
class Test2{
public void method1() {
System.out.println("method1 of Test2");
}
}
class Student {
int rollno;
String name;
int marks;
Student(){
rollno = 0;
name="";
marks = 0;
}
Student(int rollno, String name, int marks){
this.rollno = rollno;
this.name = name;
this.marks = marks;
}
//a
//b
//b = a
// Garbage collector
//public void finalize() {
//}
public void setData(int rollno, String name, int marks){
this.rollno = rollno;
this.name = name;
this.marks = marks;
}
public void inputData(){
System.out.println("give rollno, name, marks");
/*
rollno = Input.getInt();
name = Input.getString();
marks = Input.getInt();
*/
Scanner sc = new Scanner(System.in);
rollno = sc.nextInt();

sc.nextLine();
name = sc.nextLine();
marks = sc.nextInt();

}
public void dispData(){
System.out.println("Rollno="+rollno);
System.out.println("Name="+name);
System.out.println("Marks="+marks);
//...
}
public int getRollno(){
return rollno;
}
}
///////////////////
this keyword and super keyword
super()
for current object and parent object
////////////////////
Nested classes
class Outer
{
int outer_x = 100;
void test()
{
Inner in = new Inner();
in.test2();
}
class Inner
{
void test2()
{
System.out.println("Outer_x=" + outer_x);
}
}
}

class Test {
public static void main(String args[]) throws Exception {
Outer o = new Outer();
o.test();
}
}

/////////////////////
/*
String class in Java
-----------------------
String s0 = new String ("abc"); // new created
String s1 = "abc"; //a string is allocated from a pool
String s2 = "abc";

if (s1 == s2) // works when pool


if (s0.equals(s1))
{
SOP("yes");
}
int i =s0.length();
char ch = s0.charAt(0);

Write a program to input a string, and display its first and last character.

///String class

String s = "abcdef"; // Pool of strings


Sring s2 = new String ("abcdef");
String s3 = "abcdef";
if (s == s2)
if (s.equals(s2))
...
if (s == s3)
Concatenation
SOP("abc2" + 4)
String s4 = s+ s2;
charAt
char str1[30];
char ch = s3.charAt(0);
void getChars(int sourceStart, int sourceEnd, char target[], int targetStart)
char s5[] =new char[30];
s3.getChars(0, 4, s5, 0);
byte [] getBytes()
byte[] b= s3.getBytes();
char [] toCharArray()
char [] ch = s3.toCharArray();
int length() -- returns length of the string
SOP(s3.length());
boolean equals(String str2)
if (s.equals(s2))
...
else
...
"abcdef" "ABCDEF"
boolean equalsIgnoreCase(String str)
if (s3.equalsIgnoreCase(s4) )
boolean startsWith(String str2)

if ((s3.startsWith("ab"))
....

boolean endsWith (String str2)


if ((s3.endsWith("cd"))
...
else
....

indexOf-- searches for first occurrence of the character in the string


lastIndexOf -- searches for last occurrence of the character in the string
int indexOf(String str)
int indexOf(String str, int startIndex)
int indexOf(char ch)
int indexOf(char ch, int startIndex)
int lastIndexOf(String str)
int lastIndexOf(String str, int startIndex)
int lastIndexOf(char ch)
int lastIndexOf(char ch, int startIndex)

String s = "abcdefcgh";
String s2 ="fc";
int k = s.indexOf(s2,7);
int i = s. indexOf('c');
int i = s. lastIndexOf('c');
Write a program to input two strings s1 and s2, and display all occurrences of s2
in string s1.

String substring(int startindex)

String s6 = s3.substring(1);

String substring(int startindex,int endindex)


String s = s3.substring(1, 4);
"bcd"

String concat(String str)

String s = s3.concat("ghi");
SOP(2+"abc"+4);

StringBuffer represents a growable and writeable object containing characters.


StringBuffer sb= new StringBuffer("abcdef");
int length()-- gives the number of characters
int capacity() -- allocated capacity
char charAt( int location)
void setCharAt(int location, char ch)
sb.setCharAt(2, 'm');
void getChars (int sourceStart, int sourceEnd, char target [], int targetStart)

StringBuffer append(String str)


StringBuffer append(int num)
StringBuffer append(Object obj)
sb.insert(1,"pqr");
StringBuffer insert (int index, String str)
StringBuffer inser (int index, char ch)
StringBuffer insert (int index, Object obj)

StringBuffer reverse()

SOP(sb.reverse())
StringBuffer delete (int startIndex, int endIndex)
StringBuffer deleteCharAt(int location)

StringBuffer replace (int startIndex, int endIndex, String str)

String s= "abbbbbbbbbadfasdf";
StringBuffer sb= new StringBuffer(s);
inser
delete
replace
String substring(int startIndex)
String substring(int startIndex, int endIndex)
String s = sb.substring(0);

/*
File Processing In Java
a) Byte Streams in Java
FileOutputStream
FileInputStream
0 to 127 ASCII
65 A
b) Character Streams in Java
FileWriter
FileReader
0 to 65535
Unicode
*/
import java.io.*;
class Test
{
public static void main(String args[]) throws Exception
{

FileWriter fw = new FileWriter("a.txt");


String s = "First Line\n";
String s2 = s +"Second Line";
char ch[] = s2.toCharArray();
fw.write(ch);
fw.close();

String s3;
FileReader fr = new FileReader("a.txt");
BufferedReader br = new BufferedReader(fr);
while ((s3= br.readLine())!=null)
{
System.out.println(s3);
}
br.close();
fr.close();
}
}

// Write a program to input data of 10 Student (rollno, name, marks) objects. Write
code to store data on text file "student.txt". Also write code to read data from
the file and display the students whose name starts with "A".

// Graphical interface using java


// AWT Abstract Window Toolkit
// or Swing package
import java.awt.*;
import java.awt.event.*;

class Test2
{
public static void main(String args[]){
Frame fr = new Frame ("My Window Title");
Button b1 = new Button("First");
TextField tf = new TextField();
fr.setLayout(null);
b1.setBounds(100,100,50,50);
tf.setBounds(160,100,150,50);
//left top width height
fr.add(b1);
fr.add(tf);
b1.addActionListener (new MyListener());
fr.addWindowListener (new MyListener2());

//fr.show();
//fr.pack();
fr.setSize(300,200);
fr.setVisible(true);
}
}
// ActionListener interface
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
System.out.println("button clicked");
}
}
class MyListener2 extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}

// Graphical interface using java


// AWT Abstract Window Toolkit
// or Swing package
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Test2
{
static JLabel l1;
static JButton b1;
static JButton b2;

public static void main(String args[]){


JFrame fr = new JFrame ("My Window Title");
Icon i1 = new ImageIcon("D:\\air_cooler_icon.png");
Icon i2 = new ImageIcon("D:\\hel.png");
b1 = new JButton("First", i1);
l1 =new JLabel("Hello World AWT");
b2 = new JButton("Second", i2);
fr.setLayout(null);
b1.setBounds(100,100,60,60);
b2.setBounds(160,100,150,60);
l1.setBounds(100,160, 300, 50);
//Container c = //fr.getContentPane();
fr.add(b1);
fr.add(b2);
fr.add(l1);

b1.addActionListener (new MyListener());


b2.addActionListener (new MyListener());
fr.addWindowListener (new MyListener2());

//fr.show();
//fr.pack();
fr.setSize(400,400);
fr.setVisible(true);
}
}

// ActionListener interface
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String s0 = ae.getActionCommand();
if (s0.equals("First")) {

System.out.println("button b1 clicked");
Test2.l1.setText("New Message");

} else if (s0.equals("Second")) {
String s = Test2.l1.getText();
System.out.println(s);
Test2.b1.setLabel("Yes");
}
}
}
class MyListener2 extends WindowAdapter {
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.sql.*;

class Database
{
static Connection cn;
static JTextField t1, t2, t3;
public static void main(String args[]){
JFrame fr = new JFrame ("My Window Title");
JButton b1 = new JButton("First");
t1 = new JTextField();
t2 = new JTextField();
t3 = new JTextField();
fr.setLayout(null);
b1.setBounds(100,100,150,50);
t1.setBounds(10,10,150,50);
t2.setBounds(160, 10, 150, 50);
t3.setBounds(310, 10, 150, 50);

fr.add(b1);
fr.add(t1);
fr.add(t2);
fr.add(t3);
// Create Connection
try{
/* Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver={Microsoft Access
Driver(*.mdb)};DBQ=db1.accdb;";
//DriverManager.getConnection//(database, "mak", "mak");
*/
Class.forName("com.mysql.jdbc.Driver").newInstance();
String database = "jdbc:mysql://localhost/mak1?";
cn =
DriverManager.getConnection(database, "root", "");
// root, ""
}catch(Exception e){
System.out.println(e);
}

b1.addActionListener (new MyListener());


fr.addWindowListener (new MyListener2());
fr.setSize(800,500);
fr.setVisible(true);
fr.show();
}
}
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
try{
System.out.println("button clicked");
// Insert query.
Statement s = Database.cn.createStatement();
int r = Integer.parseInt(Database.t1.getText());
String n = Database.t2.getText();
int m = Integer.parseInt(Database.t3.getText());
String q1 = "Insert into Student (Rollno, Name, Marks) values (" + r +",'" +
n + "'," + m+");";
System.out.println(q1);
s.execute(q1);

// Select Query
String q2 = "Select * from Student";
ResultSet rs =null;
rs = s.executeQuery(q2);
while (rs.next())
{
System.out.println("Rollno=" + rs.getString(1));
System.out.println("Name=" + rs.getString(2));
System.out.println("Marks=" + rs.getString(3));
}
s.close();
}catch(Exception e){
System.out.println(e);
}
}
}
class MyListener2 extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
/* Develop program to manage
employee data to perform the following functionality

Employee (EID Ename Salary)


Insert Data
Update Data --
Delete Data -- delete by EID
Display All -- display on consolee

Project
-------
Menu
=>Product (PID, Pname, StockQty)
Add Product
Modify Product
Delete Product
Search

=> Purchase (PRID, PID, Qty, PricePerUnit)


Purchase Transaction
Search transaction
=> Sales (SLID, PID, Qty, PricePerUnit)
Sales Transaction
Search Transaction

=>Balance
View Stock Balance
Search product balance
*/

/*
Command line arguments
-----------------------
int main(int argc, char * argv[])
{
}
*/

class Test {
public static void main(String args[]) {
int i=0;
for (i=0; i<args.length; i++)
System.out.println(args[i]);
}
}

/*
Inheritance in Java
-------------
The data and methods can be inherited to child class.
Parent class is called base class and child class is called derived class. The code
written in parent class can be reused in child class.
Private Members
---------------
A child class access can access all members of its parent except the private
members.
private int i;
Super Keyword
-------------
In java, the super keyword is used to access members of the parent class.
*/
class A{
int i, j;
void dispIJ()
{
System.out.println("i=" +i + "j=" +j);
}
}
/// overriding
/*The dispIJ method of the parent class has been overridden with the new
implementation in the child class.*/
class B extends A{
int k; int i;
void dispK()
{
System.out.println("k=" + k);
}
void dispIJ()
{
super.dispIJ();
System.out.println("i="+i+"j="+j);
}
void showSum()
{
System.out.println("Sum=" + (super.i+j+k));
}
}

class Test {
public static void main(String args[]) {
A a = new A();
a.i = 10; a.j = 40;
a.dispIJ();
/////////
B b = new B();
b.i= 20;
b.j= 30;
b.k = 30;
b.dispK();
b.showSum();
b.dispIJ();
}
}
/*
Constructors in Inheritance
-------------
*/
class A{
int i, j;
A()
{System.out.println("A Constructor with no args");
}
A(int i)
{System.out.println("A Constructor with int args");
}
}
class B extends A{
B()
{System.out.println("B Constructor with no args");
}
B(int i)
{ super(i);
System.out.println("B Constructor with int args");
}
}
////////////
Exceptions in Java
Definition

throw keyword
----------
it is used to raise an exception

class TestE {
public static void main(String args[]) {
try{
method1();
System.out.println("program completed");
}catch(Exception e) {
System.out.println(e);
}
}
public static void method1() throws Exception {
method2();
System.out.println("last method1");
}
public static void method2() throws Exception{
int i = 5;
int j = 0;
System.out.println(i/j);
}
}
Java's Builtin Exception
------------------------
Unchecked Exceptions

ArithmeticException
ArrayIndexOutofBoundsException
ArrayStoreException
ClassCastException
IllegalArgumentExceoption
IllegalMonitorStateException
IndexOutOfBoundsException
NegativeArraySizeExceoption
NullPointerException
NumberFormatException
-------------------
Checked Exceptions
ClassNotFoundException
CloneNotsupportedException
IllegalAccessException
InstantiationException
InterruptedException
NoSuchFieldException
NoSuchMethodExceoption

public void method1() throws ClassNotFoundException, NoSuchFieldException

try{
obj1.method1();
}catch(Exception e){
...
}

/*
// Threads in Java
Java supports multi-threading for concurrent execution of tasks. A thread
represents a sequence of execution. There is always a main thread executing when
the main function is executed. There are two ways for creating threads in java.
a) Implementing Runnable interface
b) Extending Thread class
public void run()*/

class MyThread extends Thread


{
public void run()
{
for (int i=0; i<20; i++)
{
try{
Thread.sleep(500);
} catch(Exception e){}
Thread t = Thread.currentThread();
String s= t.getName();
int pr = t.getPriority();
System.out.println("i=" + i +" " + s + " pr=" + pr);
}
}
}
class Test
{
public static void main(String args[]) throws Exception
{
MyThread mt1 = new MyThread();
MyThread mt2 = new MyThread();

mt1.start();
mt2.start();

mt1.join();
mt2.join();
System.out.println("Main completed");
}
}

Java AWT/SWING
--------------------

String, Thread, Checked Unchecked, AWT, Swingdatabase.

AWT
--------------

// Graphical interface using java


// AWT Abstract Window Toolkit
// or Swing package
import java.awt.*;
import java.awt.event.*;

class Test2
{
public static void main(String args[]){
Frame fr = new Frame ("My Window Title");
Button b1 = new Button("First");
TextField tf = new TextField();
fr.setLayout(null);
b1.setBounds(100,100,50,50);
fr.add(b1);
fr.add(tf);

b1.addActionListener (new MyListener());


fr.addWindowListener (new MyListener2());

//fr.show();
//fr.pack();
fr.setSize(300,200);
fr.setVisible(true);
}
}
// ActionListener interface
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
System.out.println("button clicked");
}
}
class MyListener2 extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
---------------------
SWING and Databases
---------------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.sql.*;

class Database
{
static Connection cn;
static JTextField t1, t2, t3;
public static void main(String args[]){
JFrame fr = new JFrame ("My Window Title");
JButton b1 = new JButton("First");
t1 = new JTextField();
t2 = new JTextField();
t3 = new JTextField();
fr.setLayout(null);

b1.setBounds(100,100,150,50);
t1.setBounds(10,10,150,50);
t2.setBounds(160, 10, 150, 50);
t3.setBounds(310, 10, 150, 50);

fr.add(b1);
fr.add(t1);
fr.add(t2);
fr.add(t3);
// Create Connection
try{
/* Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver={Microsoft Access
Driver(*.mdb)};DBQ=db1.accdb;";
//DriverManager.getConnection//(database, "mak", "mak");
*/
Class.forName("com.mysql.jdbc.Driver").newInstance();
String database = "jdbc:mysql://localhost/mak1?";
cn =
DriverManager.getConnection(database, "root", "");
// root, ""
}catch(Exception e){
System.out.println(e);
}

b1.addActionListener (new MyListener());


fr.addWindowListener (new MyListener2());
fr.setSize(800,500);
fr.setVisible(true);
fr.show();
}
}
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
try{
System.out.println("button clicked");
// Insert query.
Statement s = Database.cn.createStatement();
int r = Integer.parseInt(Database.t1.getText());
String n = Database.t2.getText();
int m = Integer.parseInt(Database.t3.getText());
String q1 = "Insert into Student (Rollno, Name, Marks) values (" + r +",'" +
n + "'," + m+");";
System.out.println(q1);
s.execute(q1);

// Select Query
String q2 = "Select * from Student";
ResultSet rs =null;
rs = s.executeQuery(q2);
while (rs.next())
{
System.out.println("Rollno=" + rs.getString(1));
System.out.println("Name=" + rs.getString(2));
System.out.println("Marks=" + rs.getString(3));
}
s.close();
}catch(Exception e){
System.out.println(e);
}
}
}
class MyListener2 extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
/* Develop program to manage
employee data to perform the following functionality

Employee (EID Ename Salary)


Insert Data
Update Data --
Delete Data -- delete by EID
Display All -- display on consolee

Project
-------
Menu
=>Product (PID, Pname, StockQty)
Add Product
Modify Product
Delete Product
Search

=> Purchase (PRID, PID, Qty, PricePerUnit)


Purchase Transaction
Search transaction
=> Sales (SLID, PID, Qty, PricePerUnit)
Sales Transaction
Search Transaction

=>Balance
View Stock Balance
Search product balance
*/

You might also like