Ecm II II LM 212pages

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 212

(An Autonomous Institution approved by UGC and affiliated to JNTUH))

Yamnampet, Ghatkesar Mandal, Hyderabad - 501 301

LAB MANUALS
For
DATABASE MANAGEMENT SYSTEMS
(Page No: 1 to 55 )

&
OBJECT ORIENTED PROGRAMMING
THROUGH JAVA
(Page No:56 to 136)

&
ANALOG AND PULSE CIRCUITS
(Page No: 137 to End)

FOR
B. Tech. II-II (AY-2022-2023)
ELECTRONICS AND COMPUTER ENGINEERING

Department of Electronics and Computer Engineering


SREENIDHI INSTITUTE OF SCIENCE AND TECHNOLOGY
(AN AUTONOMOUS INSTITUTION UNDER JNTUH)
(Approved by AICTE & Aided by World Bank under TEQIP )
Yamnampet, Ghatkesar Mandal, Hyderabad - 501 301.

LAB MANUAL
For
DATABASE MANAGEMENT SYSTEMS
(Common to all branches)

DEPARTMENT
OF
ELECTRONICS AND COMPUTER ENGINEERING

1|Page
1 2 3 4 5 6 7 8 9 10 11 12 13
X X X X
M H L L
H: High M: Medium L: Low

Syllabus for B. Tech II Year II semester


Electronics and Computer Engineering
DATABASE MANAGEMENT SYSTEMS LAB
(Common to all branches)

Code: 8EC63 L T P/D C


- - 4 2
1. Creation, altering and droping of tables and inserting rows into a table (use
constraints while creating tables) examples using SELECT command.
2. Queries (along with sub Queries) using ANY, ALL, IN, EXISTS,
NOTEXISTS, UNION, INTERSET, Constraints.
Example: - Select the roll number and name of the student who secured fourth
rank in the class.
3. Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN),
GROUP BY, HAVING and Creation and dropping of Views.
4. Queries using Conversion functions (to_char, to_number and to_date), string
functions (Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap,
length, substr and instr), date functions (Sysdate, next_day, add_months,
last_day, months_between, least, greatest, trunc, round, to_char, to_date).
5. i)Creation of simple PL/SQL program which includes declaration section,
executable section and exception –Handling section (Ex. Student marks can
be selected from the table and printed for those who secured first class and
an exception can be raised if no records were found)
ii)Insert data into student table and use COMMIT, ROLLBACK and
SAVEPOINT in
PL/SQL block.
6. Develop a program that includes the features NESTED IF, CASE and CASE
expression. The program can be extended using the NULLIF and
COALESCE functions.
7. Program development using WHILE LOOPS, numeric FOR LOOPS, nested
loops using ERROR Handling, BUILT –IN Exceptions, USE defined
Exceptions, RAISE- APPLICATION ERROR.
8. Programs development using creation of procedures, passing parameters IN
and OUT of PROCEDURES.

2|Page
9. Program development using creation of stored functions, invoke functions in
SQL Statement and write complex functions.
10. Program development using creation of package specification, package
bodies, private objects, package variables and cursors and calling stored
packages.
11. Develop programs using features parameters in a CURSOR, FOR UPDATE
CURSOR, WHERE CURRENT of clause and CURSOR variables.
12. Develop Programs using BEFORE and AFTER Triggers, Row and Statement
Triggers and INSTEAD OF Triggers.

TEXT BOOKS :
1)ORACLE PL/SQL by example. Benjamin Rosenzweig, Elena Silvestrova,
Pearson Education 3 Edition
2)ORACLE DATA BASE LOG PL/SQL Programming SCOTT URMAN, Tata
Mc- Graw Hill.
3)SQL & PL/SQL for Oracle 10g, Black Book, Dr.P.S. Deshpande.

3|Page
List 1
1. Create Sailors table with the following fields and describe the table (sid:
integer, sname: string, rating: integer)

2. Add field (age: integer) to the Sailors table and describe the table

3. Modify field age to real in the Sailors table and describe the table

4. Delete age field from the Sailors table and describe the table

5. Add field (age: real) to the Sailors table and describe the table

6. Delete Sailors table

7. Create Sailors table with the following fields and describe the table (sid:
integer, sname: string, rating: integer, age: real)

8. Insert the following records in to the Sailors table

4|Page
9. Retrieve all Records from the Sailors table

10. Retrieve all Records (unique) from the Sailors table

11. Retrieve the names and ages of all sailors from the Sailors table

12. Find all sailors with a rating above 7

13. Create Sailors1 table with the following fields and describe the table (sid:
integer, sname: string, rating: integer, age: real)

14. Insert tuples of Sailors table in to the Sailors1 table

15. Retrieve all Records from the Sailors1 table

16. Delete sailor from the Sailors1 table whose sid is 58

17. Retrieve all Records from the Sailors1 table

18. Delete all tuples from the Sailors1 table

19. Create Boats table with the following fields and describe the table (bid: integer,
bname: string, color: string)

20. Insert the following records in to the Boats table

21. Retrieve all Records from the Boats table

22. Create Reserves table with the following fields and describe the table (sid: integer,
bid: integer, day: date)
5|Page
23. Insert the following records in to the Reserves table

24. Retrieve all Records from the Reserves table

6|Page
List -1 Solutions

1. Create Sailors table with the following fields and describe the
table (sid: integer, sname: string, rating: integer)
Query: Create table Sailors(sid number(2),sname varchar2(20),rating number(2))
Output: Table Created
Query: desc Sailors
Output:
Bottom of Form
Name Null? Type
SID NUMBER(2)
SNAME VARCHAR2(20)
RATING NUMBER(2)

2. Add field (age: integer) to the Sailors table and describe the table

Query: ALTER TABLE Sailors


ADD (age NUMBER(2))
Output: Table Altered
Query: desc Sailors
Output:
Bottom of Form
Name Null? Type
SID NUMBER(2)
SNAME VARCHAR2(10)
RATING NUMBER(2)
AGE NUMBER(2)

3. Modify field age to real in the Sailors table and describe the table

Query: ALTER TABLE Sailors


MODIFY (age NUMBER(3,1))
Output: Table Altered
Query: desc Sailors
Output:
Bottom of Form

7|Page
Name Null? Type
SID NUMBER(2)
SNAME VARCHAR2(10)
RATING NUMBER(2)
AGE NUMBER(3,1)

4. Delete age field from the Sailors table and describe the table

Query: ALTER TABLE Sailors


DROP COLUMN age
Output: Table Altered
Query: desc Sailors
Output:
Bottom of Form
Name Null? Type
SID NUMBER(2)
SNAME VARCHAR2(10)
RATING NUMBER(2)

5. Add field (age: real) to the Sailors table and describe the table

Query: ALTER TABLE Sailors


ADD (age NUMBER(3,1))
Output: Table Altered
Query: desc Sailors
Output:
Bottom of Form
Name Null? Type
SID NUMBER(2)
SNAME VARCHAR2(10)
RATING NUMBER(2)
AGE NUMBER(3,1)

6. Delete Sailors table

Query: DROP TABLE Sailors


Output: Table dropped.
8|Page
7. Create Sailors table with the following fields and describe the
table (sid: integer, sname: string, rating: integer, age: real)

Query: CREATE TABLE Sailors (sid NUMBER(2), sname VARCHAR2(20),


rating NUMBER(2),age NUMBER(3,1))
Output: Table Created
Query: desc Sailors
Output:
Bottom of Form
Name Null? Type
SID NUMBER(2)
SNAME VARCHAR2(20)
RATING NUMBER(2)
AGE NUMBER(3,1)

8. Insert the following records in to the Sailors table

Query:
insert into Sailors values(22,'Dustin',7,45.0);
insert into Sailors values(29,'Brutus',1,33.0);
insert into Sailors values(31,'Lubber',8,55.5);
insert into Sailors values(32,'Andy',8,25.5);
insert into Sailors values(58,'Rusty',10,35.0);
insert into Sailors values(64,'Horatio',7,35.0);
insert into Sailors values(71,'Zorba',10,16.0);

9|Page
insert into Sailors values(74,'Horatio',9,35.0);
insert into Sailors values(85,'Art',3,25.5);
insert into Sailors values(95,'Bob',3,63.5);
Output:
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.

9. Retrieve all Records from the Sailors table

Query: select * from Sailors


Output:
Bottom of Form
SID SNAME RATING AGE
22 Dustin 7 45
29 Brutus 1 33
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35
64 Horatio 7 35
71 Zorba 10 16
74 Horatio 9 35
85 Art 3 25.5
95 Bob 3 63.5
10 records selected.

10 | P a g e
10. Retrieve all Records (unique) from the Sailors table
Query: select distinct sname,age from Sailors
Output:
Bottom of Form
SNAME AGE
Andy 25.5
Art 25.5
Bob 63.5
Brutus 33
Dustin 45
Horatio 35
Lubber 55.5
Rusty 35
Zorba 16
9 records selected.
11. Retrieve the names and ages of all sailors from the Sailors table
Query: select sname,age from sailors
Output:
Bottom of Form
SNAME AGE
Dustin 45
Brutus 33
Lubber 55.5
Andy 25.5
Rusty 35
Horatio 35
Zorba 16
Horatio 35
Art 25.5
Bob 63.5
10 records selected.

11 | P a g e
12. Find all sailors with a rating above 7
Query: select * from sailors where rating>7
Output:
Bottom of Form
SID SNAME RATING AGE
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35
71 Zorba 10 16
74 Horatio 9 35
5 records selected

13. Create Sailors1 table with the following fields and describe the table
(sid: integer, sname: string, rating: integer, age: real)

Query: CREATE TABLE Sailors1 (sid NUMBER(2), sname VARCHAR2(20),


rating NUMBER(2),age NUMBER(3,1))
Output: Table created.
Query: desc Sailors1
Output:
Bottom of Form
Name Null? Type
SID NUMBER(2)
SNAME VARCHAR2(20)
RATING NUMBER(2)
AGE NUMBER(3,1)

14. Insert tuples of Sailors table in to the Sailors1 table

Query: INSERT INTO Sailors1 SELECT * FROM Sailors


Output: 10 rows created.

15. Retrieve all Records from the Sailors1 table

Query: select * from Sailors1


Output:
12 | P a g e
Bottom of Form
SID SNAME RATING AGE
22 Dustin 7 45
29 Brutus 1 33
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35
64 Horatio 7 35
71 Zorba 10 16
74 Horatio 9 35
85 Art 3 25.5
95 Bob 3 63.5
10 records selected

16. Delete sailor from the Sailors1 table whose sid is 58


Query: DELETE FROM Sailors1
WHERE sid=58
Output: 1 row deleted.

17. Retrieve all Records from the Sailors1 table


Query: SELECT * FROM Sailors1
Output:
Bottom of Form
SID SNAME RATING AGE
22 Dustin 7 45
29 Brutus 1 33
31 Lubber 8 55.5
32 Andy 8 25.5
64 Horatio 7 35
71 Zorba 10 16
74 Horatio 9 35
85 Art 3 25.5
95 Bob 3 63.5
9 records selected
18. Delete all tuples from the Sailors1 table
Query: DELETE FROM Sailors1
13 | P a g e
Output: 9 rows deleted.

19. Create Boats table with the following fields and describe the table
(bid: integer, bname: string, color: string)

Query: create table boats(bid number(3),bname varchar2(9),color varchar2(5))


Output: Table Created
Query: desc boats
Output:
Top of Form

Bottom of Form
Name Null? Type
BID NUMBER(3)
BNAME VARCHAR2(9)
COLOR VARCHAR2(5)

20. Insert the following records in to the Boats table

Query:
insert into boats values(101,'Interlake','blue');
insert into boats values(102,'Interlake','red');
insert into boats values(103,'Clipper','green');
insert into boats values(104,'Marine','red');

Output:
1 row created.
1 row created.
1 row created.
14 | P a g e
1 row created.

21. Retrieve all Records from the Boats table

Query: select * from boats


Output:
Bottom of Form
BID BNAME COLOR
101 Interlake blue
102 Interlake red
103 Clipper green
104 Marine red
4 records selected
22. Create Reserves table with the following fields and describe the table
(sid: integer, bid: integer, day: date)

Query: create table reserves(sid number(2), bid number(3), day date)


Output: Table Created.
Query: desc reserves
Output:
Top of Form

Bottom of Form
Name Null? Type
SID NUMBER(2)
BID NUMBER(3)
DAY DATE

15 | P a g e
23. Insert the following records in to the Reserves table

Query:
insert into reserves values(22,101,'10-oct-98');
insert into reserves values(22,102,'10-oct-98');
insert into reserves values(22,103,'10-aug-98');
insert into reserves values(22,104,'10-jul-98');
insert into reserves values(31,102,'11-oct-98');
insert into reserves values(31,103,'11-jun-98');
insert into reserves values(31,104,'11-dec-98');
insert into reserves values(64,101,'9-may-98');
insert into reserves values(64,102,'9-aug-98');
insert into reserves values(74,103,'9-aug-98');

Output:
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.

16 | P a g e
24. Retrieve all Records from the Reserves table

Query: select * from reserves


Output:
Bottom of Form
SID BID DAY
22 101 10-OCT-98
22 102 10-OCT-98
22 103 10-AUG-98
22 104 10-JUL-98
31 102 11-OCT-98
31 103 11-JUN-98
31 104 11-DEC-98
64 101 09-MAY-98
64 102 09-AUG-98
74 103 09-AUG-98
10 records selected

17 | P a g e
List 2
1. Find the names of sailors who have reserved boat number 103 (using AND op-
erator)
2. Find all sailors whose age is in between 45.0 and 63.5 (using BETWEEN oper-
ator)
3. Find all sailors whose age is in the list of values(15.0,33.2,45.7,63.5) (using IN
operator)
4. Find all sailors whose second letter in the names contain ‘u’
5. Find all sailors whose first letter and third letter in the names are ‘A’ and ‘d’
6. Find all sailors from sailors and sailors1 table by using UNION operator
7. Find all sailors from sailors and sailors1 table by using INTERSECT operator
8. Find all sailors from sailors and sailors1 table by using MINUS operator
9. Find the names of sailors who have reserved boat 103 (using nested query)
10.Find the names of sailors who have reserved a blue boat (using nested query)
11.Find the names of sailors who have not reserved a red boat (using nested query)
12.Find the names of sailors who have reserved boat 103 (using Correlated Nested
Query)
13.Find sailors whose rating is better than some sailor called Horatio (using ANY
operator)
14.Find sailors whose rating is better than some sailor called Horatio (using ALL
operator)
15.Find the sailors with the highest rating
16.Find the average age of all sailors
17.Find the minimum age of the sailor
18.Find the maximum age of the sailor
19.Count the number of sailors
20.Count the number of different sailor names

18 | P a g e
List -2 Solutions
1. Find the names of sailors who have reserved boat number 103
(using AND operator)
Query: select sname from Sailors S,reserves R
where S.sid=R.sid and R.bid=103;
Output:
Bottom of Form
SNAME
Dustin
Lubber
Horatio

2. Find all sailors whose age is in between 45.0 and 63.5 (using
BETWEEN operator)
Query: select * from Sailors
where age between 45.0 and 63.5
Output:
Bottom of Form
SID SNAME RATING AGE
31 Lubber 8 55.5
95 Bob 3 63.5
22 Dustin 7 45

3. Find all sailors whose age is in the list of values (15.0,33.2,45.7,63.5)


(using IN operator)
Query: select * from Sailors
where age in(15.0,33.2,45.7,63.5)
Output:
Bottom of Form
SID SNAME RATING AGE
95 Bob 3 63.5

4. Find all sailors whose second letter in the names contain ‘u’
Query: select * from Sailors
where sname like '_u%'
Output:
Bottom of Form
19 | P a g e
SID SNAME RATING AGE
31 Lubber 8 55.5
58 Rusty 10 35
22 Dustin 7 45

5. Find all sailors whose first letter and third letter in the names are
‘A’ and ‘d’
Query: select * from Sailors
where sname like 'A_d%'
Output:
Bottom of Form
SID SNAME RATING AGE
32 Andy 8 25.5

6. Find all sailors from sailors and sailors1 table by using (UNION
operator)
Query: select * from Sailors
union select * from Sailors1
Output:
Bottom of Form
SID SNAME RATING AGE
22 Dustin 7 45
29 Brutus 1 33
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35
64 Horatio 7 35
71 Zorba 10 16
74 Horatio 9 35
85 Art 3 25.5
95 Bob 3 63.5

10 rows selected.

7. Find all sailors from sailors and sailors1 table by using


INTERSECT operator

20 | P a g e
Query: select * from Sailors
intersect select * from Sailors1
Output:
Bottom of Form
SID SNAME RATING AGE
22 Dustin 7 45
29 Brutus 1 33
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35
64 Horatio 7 35
71 Zorba 10 16
74 Horatio 9 35
85 Art 3 25.5
95 Bob 3 63.5

8. Find all sailors from sailors and sailors1 table by using MINUS
operator
Query: select * from Sailors
minus select * from Sailors1
Output:
Bottom of Form
SID SNAME RATING AGE
58 Rusty 10 35

9. Find the names of sailors who have reserved boat 103 (using
nested query)
Query: select sname from Sailors
where sid in(select sid from reserves where bid =103);
Output:
Bottom of Form
SNAME
Dustin
Lubber
Horatio

21 | P a g e
10. Find the names of sailors who have reserved a blue boat (using
nested query)
Query: select sname from Sailors
where sid in(select sid from reserves where bid in(select bid from boats
where color='blue'));
Output:
Bottom of Form
SNAME
Dustin
Horatio

11. Find the names of sailors who have not reserved a red boat
(using nested query)
Query: select sname from Sailors
where sid in(select sid from reserves where bid in(select bid from boats
where color!='red'));
Output:
Bottom of Form
SNAME
Dustin
Lubber
Horatio
Horatio

12. Find the names of sailors who have reserved boat 103 (using
Correlated Nested Query)
Query: select s.sname from Sailors s
where exists(select * from reserves r where
r.bid=103 and r.sid=s.sid);
Output:
Bottom of Form
SNAME
Lubber
Horatio
Dustin

22 | P a g e
13. Find sailors whose rating is better than some sailor called
Horatio (using ANY operator)
Query: select * from Sailors
where rating> any(select rating from Sailors where sname='Horatio');
Output:
Bottom of Form
SID SNAME RATING AGE
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35
71 Zorba 10 16
74 Horatio 9 35

14. Find sailors whose rating is better than some sailor called
Horatio (using ALL operator)
Query: select * from Sailors
where rating> all(select rating from Sailors where sname='Horatio');
Output:
Bottom of Form
SID SNAME RATING AGE
58 Rusty 10 35
71 Zorba 10 16

15. Find the sailors with the highest rating


Query: select * from Sailors
where rating=(select max(rating) from Sailors)
Output:
Bottom of Form
SID SNAME RATING AGE
58 Rusty 10 35
71 Zorba 10 16
16. Find the average age of all sailors
Query: select avg(age) from Sailors
Output:
Bottom of Form
AVG(AGE)

23 | P a g e
36.9
17. Find the minimum age of the sailor
Query: select min(age) from Sailors
Output:
Bottom of Form
MIN(AGE)
16
18. Find the maximum age of the sailor
Query: select max(age) from Sailors
Output:
Bottom of Form
MAX(AGE)
63.5
19. Count the number of sailors
Query: select count(*) from Sailors
Output:
Bottom of Form
COUNT(*)
10
20. Count the number of different sailor names
Query: select count(distinct sname) from Sailors
Output:
Bottom of Form
COUNT(DISTINCT SNAME)
9

24 | P a g e
List – 3
1. Find the sum of ratings of all sailors
2. Find the second maximum age of the sailor
3. Find the name of the sailor whose age is second maximum
4. Find the name and age of the oldest sailor
5. Find the number of sailors belongs to each rating level
6. Find the age of the youngest sailor for each rating level
7. Find the age of the youngest sailor for each rating level, which is greater than 7
8. Find the age of the youngest sailor who is eligible to vote (i.e., is at least 18 years
old) for each rating level with at least two such sailors
9. Find the average age of sailors for each rating level that has at least two sailors
10.Drop sailors table
11. Create Sailors table with the following fields and describe the table (sid: inte-
ger, sname: string, rating: integer, age: real)
Note: Underlined attribute represents the primary key
12.Insert records in to the Sailors table
13.Drop Reserves table
14.Create Reserves table with the following fields and describe the table (sid: integer,
bid: integer, day: date)
15.Insert records in to the Reserves table
16.Drop Boats table
17.Create Boats table with the following fields and describe the table (bid: integer,
bname: string, color: string).
18.Insert records in to the Boats table
19.For each red boat, find the number of reservations for this boat.
20.Find those ratings for which the average age of sailors is the minimum over all rat-
ings
21.Count the number of sailors who have reserved boats between '9/5/98' and
'10/10/98'
22.Find the names of sailors who have reserved boats between '9/4/98' and '1/8/98'
23.Find the number of reservations made for each boat
24.Find the number of reservations (with at least three) made for each boat
25.Find the number of reservations made for each boat during '9/5/98' and '10/10/98'
26.Find the days on which blue color boat is reserved
27.Find the days on which 'Horatio' reserved the boats
28.Find the number of boat reservations made by each sailor
29.Find the number of boats in each color
30.Find the colors of boats reserved by ‘Lubber’

25 | P a g e
LIST – 3 Solutions

1. Find the sum of ratings of all sailors


Query: select sum(rating) from Sailors
Output:
Bottom of Form
SUM(RATING)
66

2. Find the second maximum age of the sailor


Query: select max(age) from Sailors
where age!=(select max(age) from Sailors)
Output:
Bottom of Form
MAX(AGE)
55.5

3. Find the name of the sailor whose age is second maximum


Query: select sname from Sailors
where age=(select max(age) from Sailors
where age!=(select max(age) from Sailors));
Output:
Bottom of Form
SNAME
Lubber

4. Find the name and age of the oldest sailor


Query: select sname,age from Sailors
where age=(select max(age) from Sailors)
Output:
Bottom of Form
SNAME AGE
Bob 63.5
5. Find the number of sailors belongs to each rating level
Query: select rating,count(rating) from Sailors
group by rating
Output:

26 | P a g e
Bottom of Form
RATIN COUNT(RATI
G NG)
1 1
3 2
7 2
8 2
9 1
10 2

6. Find the age of the youngest sailor for each rating level
Query: select rating,min(age) from Sailors
group by rating
Output:
Bottom of Form
RATING MIN(AGE)
1 33
3 25.5
7 35
8 25.5
9 35
10 16
7. Find the age of the youngest sailor for each rating level, which is
greater than 7
Query: select rating,min(age) from Sailors
group by rating
having rating>7
Bottom of Form
RATING MIN(AGE)
8 25.5
9 35
10 16

8. Find the age of the youngest sailor who is eligible to vote (i.e., is at
least 18 years old) for each rating level with at least two such sailors
Query: select rating,min(age) from Sailors

27 | P a g e
where age>=18
group by rating
having count (rating)>=2
Output:
Bottom of Form
RATING MIN(AGE)
3 25.5
7 35
8 25.5

9. Find the average age of sailors for each rating level that has at
least two sailors
Query: select rating,avg(age) from Sailors
group by rating
having count (rating)>=2
Output:
Bottom of Form
RATING AVG(AGE)
3 44.5
7 40
8 40.5
10 25.5

10. Drop sailors table


Query: DROP TABLE Sailors
Output: Table dropped.

11. Create Sailors table with the following fields and describe the
table (sid: integer, sname: string, rating: integer, age: real)
Note: Underlined attribute represents the primary key
Query: CREATE TABLE Sailors (sid NUMBER(2) primary key, sname
VARCHAR2(20),rating NUMBER(2),age NUMBER(3,1))
Output:
Table created.
Query: desc Sailors
Output:
Bottom of Form

28 | P a g e
Name Null? Type
SID NOT NULL NUMBER(2)
SNAME VARCHAR2(20)
RATING NUMBER(2)
AGE NUMBER(3,1)

12. Insert records in to the Sailors table


Query:
insert into Sailors values(22,'Dustin',7,45.0);
insert into Sailors values(29,'Brutus',1,33.0);
insert into Sailors values(31,'Lubber',8,55.5);
insert into Sailors values(32,'Andy',8,25.5);
insert into Sailors values(58,'Rusty',10,35.0);
insert into Sailors values(64,'Horatio',7,35.0);
insert into Sailors values(71,'Zorba',10,16.0);
insert into Sailors values(74,'Horatio',9,35.0);
insert into Sailors values(85,'Art',3,25.5);
insert into Sailors values(95,'Bob',3,63.5);
Output:
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.

13. Drop Reserves table


Query: DROP TABLE reserves
Output: Table dropped.

14. Create Reserves table with the following fields and


describe the table (sid: integer, bid: integer, day: date)
Query: create table reserves(sid number(2), bid number(3), day date,primary
key(sid,bid))

29 | P a g e
Output: Table Created.
Query: desc reserves
Output:
Bottom of Form
Name Null? Type
SID NOT NULL NUMBER(2)
BID NOT NULL NUMBER(3)
DAY DATE

15. Insert records in to the Reserves table


Query:
insert into reserves values(22,101,'10-oct-98');
insert into reserves values(22,102,'10-oct-98');
insert into reserves values(22,103,'10-aug-98');
insert into reserves values(22,104,'10-jul-98');
insert into reserves values(31,102,'11-oct-98');
insert into reserves values(31,103,'11-jun-98');
insert into reserves values(31,104,'11-dec-98');
insert into reserves values(64,101,'9-may-98');
insert into reserves values(64,102,'9-aug-98');
insert into reserves values(74,103,'9-aug-98');
Output:
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
16. Drop Boats table
Query: drop table boats
Output: table dropped.

17. Create Boats table with the following fields and describe the
table (bid: integer, bname: string, color: string).

30 | P a g e
Query: create table boats(bid number(3) primary key,bname varchar2(9),color
varchar2(5))
Output: Table Created
Query: desc boats
Output:
Bottom of Form
Name Null? Type
BID NOT NULL NUMBER(3)
BNAME VARCHAR2(9)
COLOR VARCHAR2(5)
18. Insert records in to the Boats table
Query:
insert into boats values(101,'Interlake','blue');
insert into boats values(102,'Interlake','red');
insert into boats values(103,'Clipper','green');
insert into boats values(104,'Marine','red');

Output:
1 row created.
1 row created.
1 row created.
1 row created.

19. For each red boat, find the number of reservations for this boat.
Query: select bid,count(bid) from reserves
where bid in(select bid from boats where color='red')
group by bid
Output:
Bottom of Form
BID COUNT(BID)
102 3
104 2
20. Find those ratings for which the average age of sailors is
the minimum over all ratings
Query: select temp1.rating,temp1.ave age from (select rating,avg(age) ave from
sailors group by rating) temp1

31 | P a g e
where temp1.ave=(select min(temp2.ave) from (select rating,avg(age) ave
from sailors group by rating) temp2)
Output:
Bottom of Form
RATING AGE
10 25.5
21. Count the number of sailors who have reserved boats between
'9/5/98' and '10/10/98'
Query: select count(sid) from reserves
where day between '9-may-98' and '10-oct-98'
Output:
Bottom of Form
COUNT(SID)
8

22. Find the names of sailors who have reserved boats between
'9/4/98' and '1/8/98'
Query: select sname from sailors
where sid in(select sid from reserves where day between '9-apr-98' and '1-aug-
98')
Output:
Bottom of Form
SNAME
Dustin
Lubber
Horatio

23. Find the number of reservations made for each boat


Query: select bid, count(bid) from reserves
group by bid
Output:
Bottom of Form
BID COUNT(BID)
101 2
102 3
103 3
104 2

32 | P a g e
24. Find the number of reservations (with at least three) made for
each boat
Query: select bid,count(bid) from reserves
group by bid
having count(bid)>=3
Output:
Bottom of Form
BID COUNT(BID)
102 3
103 3
25. Find the number of reservations made for each boat during
'9/5/98' and '10/10/98'
Query: select bid,count(bid) from reserves
where day between '9-may-98' and '10-oct-98'
group by bid
Output:
Bottom of Form
BID COUNT(BID)
101 2
102 2
103 3
104 1
26. Find the days on which blue color boat is reserved
Query: select day from reserves where bid in( select bid from boats where
color='blue')
Output:
Bottom of Form
DAY
10-OCT-98
09-MAY-98
27. Find the days on which 'Horatio' reserved the boats
Query: select day from reserves where sid in(select sid from sailors where
sname='Horatio')
Output:
Bottom of Form
DAY
09-MAY-98

33 | P a g e
09-AUG-98
09-AUG-98
28. Find the number of boat reservations made by each sailor
Query: select s.sname,count(*)from sailors s, reserves r
where s.sid=r.sid
group by s.sname;

Output:
Bottom of Form
SNAME COUNT(*)
Dustin 4
Horatio 3
Lubber 3
29. Find the number of boats in each color
Query: select count(bid),color from boats
group by color
Output:
Bottom of Form
COUNT(BID) COLOR
1 blue
1 green
2 red

34 | P a g e
30. Find the colors of boats reserved by ‘Lubber’
Query: select distinct color from boats where bid in
(select bid from reserves where sid in
(select sid from sailors where sname='Lubber'))
Output:
Bottom of Form
COLOR
green
red

35 | P a g e
List4
1.Create Persons table with the following fields (declare FirstName as DE-
FAULT 'Ola') and describe the table

Pid FirstName LastName Address City


1 Ola Hansen Timoteivn 10 Sandnes
2 Tove Svendson Borgvn 23 Sandnes
3 Kari Pettersen Storgt 20 Stavanger
2. Specify UNIQUE constraint on field LastName in the Persons table
3. Specify PRIMARY KEY constraint on field Pid in the Persons table
4. Create Orders table with the following fields (declare Oid as Primary Key and
Pid as Foreign Key) and describe the table
Oid OrderNo Pid
31.Insert the Per- 1 77895 3 sons records in to
the Persons ta- 2 44678 3 ble
32.Insert the Or- 3 22456 2 ders records in to
the Orders table 4 24562 1
33.Insert
(4,'Andy','Hansen','Storgt 20','Stavanger') record in to the Persons table and ob-
serve the result
34.Insert (3,'Andy','Tahsen','Storgt 20','Stavanger') record in to the Persons table
and observe the result
35.Insert (5,51212,4) record in to the Orders table and observe the result
36.Delete record from the Persons table whose Pid is 3 and observe the result
37.Give example which includes all Arithmetic functions
38.Give example which includes all String functions
39.Give example which includes all Date and Time functions
40.Retrieve tuples from the reserves table (display ‘day’ as dd-mon-yyyy)
41.Retrieve tuples from the boats table, in which trim ‘In’ from left side on
‘bname’
42.Retrieve tuples from the sailors table, in which trim ‘io’ from right side on
‘sname’
43.Convert ‘2010 10 feb’ in to date
44.Give example which includes all General functions

36 | P a g e
List-4 Solutions

1. Create Persons table with the following fields (declare FirstName as


DEFAULT 'Ola') and describe the table
Pid FirstName LastName Address City
1 Ola Hansen Timoteivn 10 Sandnes
2 Tove Svendson Borgvn 23 Sandnes
3 Kari Pettersen Storgt 20 Stavanger
Query:
create table Persons(Pid number(5),FirstName varchar2(10) default
'Ola',LastName varchar2(10), Address varchar2(15),City varchar2(10));
Output:
Table created.
2. Specify UNIQUE constraint on field LastName in the Persons table
Query:
alter table Persons add unique(LastName);
Output:
Table altered.
3. Specify PRIMARY KEY constraint on field Pid in the Persons table
Query:
alter table Persons add primary key(Pid);
Output:
Table altered.
4. Create Orders table with the following fields (declare Oid as Primary
Key and Pid as Foreign Key) and describe the table

Oid OrderNo Pid


1 77895 3
2 44678 3
3 22456 2
4 24562 1
Query:
create table Orders (Oid number(2) PRIMARY KEY,OrderNo number(5),Pid
number(2),FOREIGN KEY(Pid ) REFERENCES Persons(Pid));
Output:
Table created.

37 | P a g e
5. Insert Persons records in to Persons table
Query:
insert into persons(pid,lastname,address,city) values(1,'Hansen','Timotevin
10','Sandnes');
Output:
1 row created.
Query:
Select * from persons;
Output:

PID FIRSTNAME LASTNAME ADDRESS CITY


1 Ola Hansen Timotevin 10 Sandnes
Query:
insert into persons values(2,'Tove','Svendson','Borgvn 23','Sandnes');
insert into persons values(3,'Kari','Pettersen','Storgt 20','Stavanger');
Query:
Select * from persons;
Output:

PID FIRSTNAME LASTNAME ADDRESS CITY


1 Ola Hansen Timotevin 10 Sandnes
2 Tove Svendson Borgvn 23 Sandnes
3 Kari Pettersen Storgt 20 Stavanger
6. Insert Orders records in to Orders table
Query:
insert into orders values(1,77895,3);
insert into orders values(2,44678,3);
insert into orders values(3,22456,2);
insert into orders values(4,24562,1);
Output:
Top of Form

Bottom of Form
OID ORDERNO PID
1 77895 3

38 | P a g e
2 44678 3
3 22456 2
4 24562 1
7. Insert (4,'Andy','Hansen','Storgt 20','Stavanger') record in to Persons ta-
ble and observe the result
Query:
insert into persons values(4,'Andy','Hansen','Storgt 20','Stavanger');
Output:
ERROR: ORA-00001: unique constraint (SCOTT.SYS_C005118) violated
8. Insert (3,'Andy','Tahsen','Storgt 20','Stavanger') record in to Persons table
and observe the result
Query:
insert into persons values(3,'Andy','Tahsen','Storgt 20','Stavanger');
Output:
ERROR: ORA-00001: unique constraint (SCOTT.SYS_C005119) violated
9. Insert (5,51212,4) record in to Orders table and observe the result
Query:
insert into orders values(5,51212,4);
Output:
ERROR: ORA-02291: integrity constraint (SCOTT.SYS_C005121) violated -
parent key not found
10.Delete record from the Persons table whose Pid is 3 and observe the result
Query:
delete from Persons where Pid=3;
Output:
ERROR: ORA-02292: integrity constraint (SCOTT.SYS_C005121) violated -
child record found
11.Give example which includes all Arithmetic functions
Query:
select abs(4.55),ceil(4.55),floor(4.55), mod(5,4),power(2,3),sign(-10), sign(10),
sqrt(9),round(4.333,2),trunc(4.333,2) from dual
Output:
Top of Form

Bottom of Form
SIG
ABS(4. CEIL(4. FLOOR( MOD( POWER( SIGN( SQRT ROUND(4.3 TRUNC(4.3
N(-
55) 55) 4.55) 5,4) 2,3) 10) (9) 33,2) 33,2)
10)

39 | P a g e
4.55 5 4 1 8 -1 1 3 4.33 4.33
12.Give example which includes all String functions
Query:
select ascii('A'),chr(65),concat('abc','def'),instr('abaabcab','ab',1,2),substr('abcd',2)
from dual
Output:
Top of Form

Bottom of Form
ASCII('A') C CONCAT INSTR('ABAABCAB','AB',1,2) SUB
65 A abcdef 4 bcd
select length('abcd'),lengthb('abcde'),lower('ABCD'),lpad('abcd',7,'e'),
ltrim('abcd','a') from dual
Output:
Bottom of Form
LENGTH('ABCD') LENGTHB('ABCDE') LOWE LPAD('A LTR
4 5 abcd eeeabcd bcd
select replace('abcd','a','ef'),rtrim('abcd','d'),rpad('abcd',7,'e'),to_char(123) from dual
Output:
Top of Form

Bottom of Form
REPLA RTR RPAD('A TO_
efbcd abc abcdeee 123
select substr('abcdef',2,3),translate('abcdef','bc','ef'),upper('abcd'),initcap('abcd')
from dual
Output:
Top of Form

Bottom of Form
SUB TRANSL UPPE INIT
bcd aefdef ABCD Abcd
13.Give example which includes all Date and Time functions
Query:
select add_months(current_date,5),current_date,current_timestamp(2),to_date('10-
10-2011','dd-mm-yy'),months_between('10-oct-2011','10-oct-2010'),
EXTRACT(year from current_date),to_char(current_date,'mon dd yyyy')

40 | P a g e
from dual
Output:
Bottom of Form
MONTHS_
ADD_ CURR CURRENT_ TO_ BETWEEN( EXTRACT(YEARF TO_CH
MONT ENT_ TIMESTAM DAT '10-OCT- ROMCURRENT_D AR(CU
H D P(2) E(' 2011','10- ATE) R
OCT-2010')
10- 10- 10-NOV-12 10-
nov 10
APR- NOV- 02.25.41.00 OCT- 12 2012
2012
13 12 PM +05:30 11

14.Retrieve tuples from the reserves table (display ‘day’ as dd-mon-yyyy)


Query:
select sid,bid,to_char(day,'dd-mon-yyyy') day from reserves
Output:
Top of Form

Bottom of Form
SID BID DAY
22 101 10-OCT-1998
22 102 10-OCT-1998
22 103 10-AUG-1998
22 104 10-JUL-1998
31 102 11-OCT-1998
31 103 11-JUN-1998
31 104 11-DEC-1998
64 101 09-MAY-1998
64 102 09-AUG-1998
74 103 09-AUG-1998
15. Retrieve tuples from the boats table, in which trim 'In' from left side on
‘bname’
Query:
select ltrim(bname,'In') from boats
Output:
Top of Form

Bottom of Form

41 | P a g e
LTRIM(BNAME,'IN)
terlake
terlake
Clipper
Marine
16.Retrieve tuples from the sailors table, in which trim 'io' from right side on
‘sname’
Query:
select rtrim(sname,'io') from sailors
Output:
Bottom of Form
RTRIM(SNAM
Dustin
Brutus
Lubber
Andy
Rusty
Horat
Zorba
Horat
Art
Bob
17.Convert ‘2010 10 feb’ in to date
Query:
select to_date('2010 10 feb','yyyy dd mon') todate from dual
Output:
TODATE
10-FEB-10

18. Give example which includes all General functions


Query:
select sid,sname,cast(sid as varchar2(10)) from sailors
Output:
Top of Form

Bottom of Form

42 | P a g e
SID SNAME CAST(SIDAS
22 Dustin 22
29 Brutus 29
31 Lubber 31
32 Andy 32
58 Rusty 58
64 Horatio 64
71 Zorba 71
74 Horatio 74
85 Art 85
95 Bob 95
Query:
create table cal(id number);
Output:
Table created.
Query:
insert into cal values(10);
insert into cal(id) values(null);
insert into cal values(20);
Query:
select * from cal
Output:
ID
10

20

Query:
select id,nullif(id,10),nvl(id,88),nvl2(id,66,88) from cal
Output:
Top of Form

Bottom of Form
ID NULLIF(ID,10) NVL(ID,88) NVL2(ID,66,88)
10 10 66
88 88
20 20 20 66

43 | P a g e
Query:
select sid,decode(sid,22,'A',31,'B','ZZ') results from sailors
Output:
Top of Form

Bottom of Form
SID RE
22 A
29 ZZ
31 B
32 ZZ
58 ZZ
64 ZZ
71 ZZ
74 ZZ
85 ZZ
95 ZZ

44 | P a g e
List 5
1. Write a PL/SQL program to perform the following:

Insert <99,'John',9,25.6> into the Sailors table, Update sname 'John' to 'Joe' in the
Sailors table, Delete tuple from the Sailors table whose sname is 'Joe'

2. Retrieve tuple from the Sailors table whose sname is 'Lubber' using PL/SQL pro-
gram
3. Write a PL/SQL program to find largest and smallest of three numbers
4. Write a PL/SQL program to check whether a number is prime or not?
5. Write a PL/SQL program to check whether a number is palindrome or not?
6. Write a PL/SQL program to show handling of Pre-defined exception
7. Write a PL/SQL program to show handling of User-defined exception
8. Write a PL/SQL program to print the following values

0 if a=0

1 if a>0

-1 if a<0

9. Write a PL/SQL program to find even numbers and odd numbers in a given range
m to n
10.Write a PL/SQL program to retrieve records from the sailors table using cursor
11.Write a PL/SQL procedure to find factorial of a given number
12.Write a PL/SQL function to find sum of digits of a number
13.Write a PL/SQL recursive function to find factorial of a number

45 | P a g e
List-5 Solutions
1. Write a PL/SQL program to perform the following: Insert
<99,'John',9,25.6> into the Sailors table, Update sname 'John' to 'Joe' in the
Sailors table, Delete tuple from the Sailorstable whose sname is 'Joe'
Program:
DECLARE
s_id number(2):=99;
s_name varchar2(20):='john';
s_rating number(2):=9;
s_age number(3,1):=25.6;
BEGIN
INSERT INTO Sailors VALUES(s_id,s_name,s_rating,s_age);
end;
Output:
SID SNAME RATING AGE
22 Dustin 7 45
29 Brutus 1 33
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35
64 Horatio 7 35
71 Zorba 10 16
74 Horatio 9 35
85 Art 3 25.5
95 Bob 3 63.5
99 john 9 25.6
11 rows selected.
Program:
begin
update sailors set sname='joe' where sname='john';
end;
Output:
SID SNAME RATING AGE
22 Dustin 7 45
29 Brutus 1 33
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35
64 Horatio 7 35
71 Zorba 10 16
46 | P a g e
74 Horatio 9 35
85 Art 3 25.5
95 Bob 3 63.5
99 joe 9 25.6
11 rows selected.
Program:
begin
delete from sailors where sname='joe';
end;
Output:
SID SNAME RATING AGE
22 Dustin 7 45
29 Brutus 1 33
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35
64 Horatio 7 35
71 Zorba 10 16
74 Horatio 9 35
85 Art 3 25.5
95 Bob 3 63.5
10 rows selected.
2. Retrieve tuple from the Sailors table whose sname is 'Lubber' using
PL/SQL program
Program:
declare
s_id sailors.sid%type;
s_sname sailors.sname%type;
s_rating sailors.rating%type;
s_age sailors.age%type;
begin
select sid,sname,rating,age into s_id,s_sname,s_rating,s_age from sailors
where sname='lubber';
dbms_output.put_line('sid is '||s_id||' sname is'||s_sname||' rating'||s_rating||' age i
s'||s_age);
end;
Output:
sid is 31 sname is lubber rating is 8 age is 55.5
3. Write a PL/SQL program to find largest and smallest of three numbers
Program:
47 | P a g e
declare
a number(2):=10;
b number(2):=5;
c number(2):=15;
large number(2):=0;
small number(2):=0;
begin
if b>a and b>c then
large:=b;
elsif c>b and c>a then
large:=c;
else
large:=a;
end if;
dbms_output.put_line('largest number is'||large);
if b<a and b<c then
small:=b;
elsif c<b and c<a then
small:=c;
else
small:=a;
end if;
dbms_output.put_line('smallest number is'||small);
end;
Output:
largest number is15
smallest number is5
4. Write a PL/SQL program to check whether a number is prime or not?
Program:
declare
a number:=&a;
c number:=0;
i number;
begin
for i in 1..a loop
if mod(a,i)=0 then
c:=c+1;
end if;
end loop;
if c=2 then
48 | P a g e
dbms_output.put_line('number is prime');
else
dbms_output.put_line('number is not prime');
end if;
end;
Output:
Enter value for a: 7
old 2: a number:=&a;
new 2: a number:=7;
number is prime
5. Write a PL/SQL program to check whether a number is palindrome or
not?
Program:
declare
a number:=&a;
c number:=a;
r number:=0;
s number:=0;
begin
while a>0 loop
r:=mod(a,10);
s:=s*10+r;
a:=floor(a/10);
end loop;
if s=c then
dbms_output.put_line('number is palindrome');
else
dbms_output.put_line('number is not palindrome');
end if;
end;
Output:
Enter value for a: 123
old 2: a number:=&a;
new 2: a number:=123;
number is not palindrome
6. Write a PL/SQL program to show handling of Pre-defined exception
Program:
declare
a number:=4;
c number;
49 | P a g e
begin
c:=a/0;
exception
when ZERO_DIVIDE then
dbms_output.put_line('divide by zero exception');
end;
Output:
divide by zero exception
7. Write a PL/SQL program to show handling of User-defined exception
Program:
declare
a number(2);
b number(2);
c number(2);
ex exception;
begin
a:=&a;
b:=&b;
if(b=0) then
raise ex;
else
c:=a/b;
dbms_output.put_line(c);
end if;
exception
when ex then
dbms_output.put_line('divide by zero');
end;
Output:
old 8: b:=&b;
new 8: b:=0;
divide by zero
8. Write a PL/SQL program to print the following values
0 if a=0
1 if a>0
-1 if a<0
Program:
declare
a number:=&a;
begin
50 | P a g e
if a=0 then
dbms_output.put_line('0');
elsif a>0 then
dbms_output.put_line('1');
else
dbms_output.put_line('-1');
end if;
end;
Output:
Enter value for a: 5
old 2: a number:=&a;
new 2: a number:=5;
1
9. Write a PL/SQL program to find even numbers and odd numbers in a
given range m to n
Program:
declare
m number:=&m;
n number:=&n;
i number;
begin
for i in m..n loop
if mod(i,2)=1 then
dbms_output.put_line(i||' is odd number');
else
dbms_output.put_line(i||' is even number');
end if;
end loop;
end;
Output: Enter value for a: 25
old 2: m number:=&m;
new 2: m number:=25;
Enter value for a: 30
old 3: n number:=&n;
new 3: n number:=30;
25 is odd number
26 is even number
27 is odd number
28 is even number
29 is odd number
51 | P a g e
30 is even number
10. Write a PL/SQL program to retrieve records from the sailors table using
cursor
Program:
declare
s_id number(2);
s_name varchar2(20);
s_rating number(2);
s_age number(3,1);
cursor c_sailors is select sid,sname,rating,age from sailors;
begin
open c_sailors;
loop
fetch c_sailors into s_id,s_name,s_rating,s_age;
dbms_output.put_line(s_id||' '||s_name||' '||s_rating||' '||s_age);
exit when c_sailors%notfound;
end loop;
close c_sailors;
end;
Output:
22 dustin 7 45
29 brutus 1 33
31 lubber 8 55.5
32 andy 8 25.5
58 rusty 10 35
64 horatio 7 35
71 zorba 10 16
74 horatio 9 35
85 art 3 25.5
95 bob 3 63.5
11. Write a PL/SQL procedure to find factorial of a given number
Procedure:
create or replace procedure fact(n in number, r out number) is
i number:=n; --Never modify in parameter value
f number:=1;
begin
while(i>1) loop
f:=f*i;
i:=i-1;
end loop;
52 | P a g e
r:=f; --Assign final value to out parameter
end fact;
Output:
Procedure created.
Program:
declare
n number;
r number;
begin
n:=&n;
fact(n,r);
dbms_output.put_line('Factorial of '||n||' is '||r);
end;
Output:
Enter value for n: 6
old 5: n:=&n;
new 5: n:=6;
Factorial of 6 is 720
12. Write a PL/SQL function to find sum of digits of a number
Function:
create or replace function sumofn(n in number) return number is
s number:=0;
i number:=n;
begin
while(i!=0) loop
s:=s+mod(i,10);
i:=floor(i/10); --Extract decimal part
end loop;
return s;
end sumofn;
Output:
Function created.
Program:
declare
n number;
r number;
begin
n:=&n;
r:=sumofn(n);
dbms_output.put_line('Sum of '||n||' digits is '||r);
53 | P a g e
end;
Output:
Enter value for n: 456
old 5: n:=&n;
new 5: n:=456;
Sum of 456 digits is 15
13. Write a PL/SQL recursive function to find factorial of a number
Procedure:
create or replace function rfact(n in number) return number is
f number:=1;
begin
if n=1 then
return 1;
else
f:=n*rfact(n-1);
return f;
end if;
end;
Output:
Function created
Query;
declare
n number;
r number;
begin
n:=&n;
r:=rfact(n);
dbms_output.put_line('Factorial of '||n||' is '||r);
end;
Output:
Enter value for n: 7
old 5: n:=&n;
new 5: n:=7;
Factorial of 7 is 5040

54 | P a g e
SREENIDHI INSTITUTE OF SCIENCE AND TECHNOLOGY
(An Autonomous Institution approved by UGC and affiliated to JNTUH)
(Accredited by NAAC with ‘A” Grade, Accredited by NBA of AICTE and
Recipient of World Bank under TEQIP-I and II )
Yamnampet, Ghatkesar Mandal, Hyderabad - 501 301.

LABORATORY MANUAL

FOR

Object Oriented
Programming through Java

B. TECH 2nd Year 2ND Semester


ECM

DEPARTMENT OF
ELECTRONICS AND COMPUTER ENGINEERING
55 | P a g e
FEB- 2022

56 | P a g e
1 2 3 4 5 6 7 8 9 10 11 12
H M L
H: High M: Medium L: Low
Syllabus for B.Tech. II year I Semester
Computer Science and Engineering
OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB
(Common to CSE, IT and ECM)

Code: 8EC62 L T P C
- - 4 2
Course objective :
Understand, design an execute the programs involving concepts of Java and Object oriented
programming principles.

COURSE OUTCOMES: After completing this course, the student will be able to
1 Write programs to generate Prime numbers, Roots of quadratic equation and
Fibonacci series.

2 Write small application such as banking system.


3 Write programs on operator, function overloading and dynamic method dispatch.
4 Write programs to implement interface and packages.
5 Explain and write programs to implement threads.
6 Write programs to implement applets and event handling.
7 Write an application to implement client and server scenario.

List of Programs:

1. A) Write a program to print prime numbers up to a given number.


B) Write a program to print roots of a quadratic equation ax2+bx+c=0.
C) Write a program to print Fibonacci sequence up to a given number.

2.A) Define a class to represent a bank account and include the following members Instance
variables:
(i)Name of depositor
(ii)Account No
(iii)Type of account
(iv)Balance amount in the account

Instance Methods:
To assign instance variables (Constructors-Zero argument and parameterized)
1. To deposit an amount
2. To withdraw amount after checking the balance
(iv) To display name and address
Define ExecuteAccount class in which define main method to test above class.

57 | P a g e
B) In the above account class, maintain the total no. of account holders present in the
bank and also define a method to display it. Change the main method appropriately.
C) In main method of ExecuteAccount class, define an array to handle five accounts.
D) In Account class constructor, demonstrate the use of “this” keyword.
E) Modify the constructor to read data from keyboard.
F) Overload the method deposit() method (one with argument and another without
argument)
G) In Account class, define set and get methods for each instance variable.
Example:
For account no variable, define the methods
getAccountNo() and setAccountNo(int accno)
In each and every method of Account class, reading data from and writing data to instance
variables should be done through these variables.

3.A) Define Resister class in which we define the following members:


Instance variables:
resistance
Instance Methods:
giveData():To assign data to the resistance variable
displayData(): To display data in the resistance variable
constructors
Define subclasses for the Resistor class called SeriesCircuit and ParallelCircuit in which
define methods : calculateSeriesResistance( ) and calculateParallelResistance()
respectively.Both the methods should take two Resistor objects as arguments and return
Resistor object as result.In main method , define another class called ResistorExecute to
test the above class.
B) Modify the above two methods which should accept array of Resistor objects as argument and
return Resistor object as result.
4 .A) Write a program to demonstrate method overriding.
B) Write a program to demonstrate the uses of “super” keyword (three uses)
C) Write a program to demonstrate dynamic method dispatch (i.e .Dynamic polymorphism).

5) A) Write a program to check whether the given string is palindrome or not.


B) Write a program for sorting a given list of names in ascending order.
C) Write a program to count the no. of words in a given text.

6. A) Define an interface “GeomtricShape” with methods area( ) and perimeter( ) (Both


method’s return type and parameter list should be void and empty respectively.
Define classes like Triangle, Rectangle and Circle implementing the “GeometricShape”
interface and also define “ExecuteMain” class in which include main method to test the
above class
B) Define a package with name “sortapp” in which declare an interface “SortInterface”
with method sort( ) whose return type and parameter list should be void and
empty.Define “subsortapp” as subpackage of “sortapp” package in which define class
“SortImpl” implementing “SortInterface” in which sort() method should print a message
linear sort is used.

58 | P a g e
Define a package “searchingapp” in which declare an interface “SearchInterface” with
search( ) method whose return type and parameter list should be void and empty
respectively.
Define “searchingimpl” package in which define a “SearchImpl” class implementing
“SearchInterface” defined in “searchingapp” package in which define a search( ) method
which should print a message linear search is used.
Define a class ExecutePackage with main method using the above packages(classes and
its methods).
Use ArrayList class of Collections Framework to and use algorithms to search and sort
the elemnt of an array.

7) Modify the withdraw() method of Account class such that this method should throw
“InsufficientFundException” if the account holder tries to withdraw an amount that leads
to condition where current balance becomes less than minimum balance otherwise allow
the account holder to withdraw and update the balance accordingly.
8. A) Define two threads such that one thread should print even numbers and another thread
should print odd numbers.
B) Modify the Account class to implement thread synchronization concept.
C) Define two threads such that one thread should read a line of text from text file and
another thread should write that line of text to another file. (Thread communication
example).
D) Write a program to implement thread priority.

9) Design the user screen as follows and handle the events appropriately.
Add Window
First Number
Second Number
Result
ADD SUBTRACT

10) Write a program to simulate a calculator


11) Write a Java program for handling mouse events and key events.
12) a) Write a program for handling window events.
b) Develop an applet that displays a simple message..
13) Develop a client that sends data to the server and also develop a server that sends data to the
client (two way communication)
14) Develop a client/server application in which client read a file name from keyboard and send
the file name to the server, and server will read the file name from client and send the file
contents to the client.
Programs Beyond the Syllabus

15) Write a program to illustrate the scope of default , private, protected and public access
modifiers for variables and methods in java .
16).Write a java program to illustrate the usage of multiple catch blocks in java.
17) Develop a program for passing parameters to an Applet.

59 | P a g e
INDEX

S.NO NAME OF THE PROGRAM Page .No.


1 (A)Write a program to print prime numbers up to a given number 64
(B)Write a program to print roots of a quadratic equation ax2+bx+c=0
(C)Write a program to print Fibonacci sequence up to a given number
2 ( A) Define a class to represent a bank account and include the 68
following members Instance variables:
(i)Name of depositor
(ii)Account No
(iii)Type of account
(iv)Balance amount in the account

Instance Methods:
To assign instance variables (Constructors-Zero argument and
parameterized)
3. To deposit an amount
4. To withdraw amount after checking the balance
(iv) To display name and address
Define ExecuteAccount class in which define main method to test
above class.
B) In the above account class, maintain the total number of account
holders present in the bank and also define a method to display it.
Change the main method appropriately.
C) In main method of Execute Account class, define an array to
handle five accounts
D) In Account class constructor, demonstrate the use of “this”
keyword
E) Modify the constructor to read data from keyboard
F) Overload the method deposit () method (one with argument and
another without argument)
G) In Account class, define set and get methods for each instance
variables. Example:
For account no variable, define the methods
getAccountNo() and setAccountNo(int accno)
In each and every method of Account class, reading data from and
writing data to instance variables should be done through these
variables.
3 A) Define Resister class in which we define the following 83
60 | P a g e
members:
Instance variables:
resistance
Instance Methods:
giveData():To assign data to the resistance variable
displayData(): To display data in the resistance variable
constructors
Define subclasses for the Resistor class called SeriesCircuit
and ParallelCircuit in which define methods :
calculateSeriesResistance( ) and calculateParallelResistance()
respectively.Both the methods should take two Resistor
objects as arguments and return Resistor object as result.In
main method , define another class called ResistorExecute to
test the above class.

B) Modify the above two methods which should accept array of


Resistor objects as argument and return Resistor object as result.
4 A). Write a program to demonstrate method overriding. 87
B). Write a program to demonstrate the uses of “super” keyword
(three uses)
C). Write a program to demonstrate dynamic method dispatch
(ie. Dynamic polymorphism)
5 A) Write a program to check whether the given string is palindrome or 93
not.
B) Write a program for sorting a given list of names in ascending
order
C) Write a program to count the number of words in a given text.
6 A) Define an interface “GeomtricShape” with methods area( ) and 97
perimeter( ) (Both method’s return type and parameter list
should be void and empty respectively.
Define classes like Triangle, Rectangle and Circle
implementing the “GeometricShape”
interface and also define “ExecuteMain” class in which
include main method to test the above class.

B) Define a package with name “sortapp” in which declare an


interface “SortInterface” with method sort( ) whose return
type and parameter list should be void and empty.Define
“subsortapp” as subpackage of “sortapp” package in which
define class “SortImpl” implementing “SortInterface” in which

61 | P a g e
sort() method should print a message linear sort is used.
Define a package “searchingapp” in which declare an interface
“SearchInterface” with search( ) method whose return type and
parameter list should be void and empty respectively.
Define “searchingimpl” package in which define a
“SearchImpl” class implementing “SearchInterface” defined in
“searchingapp” package in which define a search( ) method
which should print a message linear search is used.
Define a class ExecutePackage with main method using the
above packages(classes and its methods).
Use ArrayList class of Collections Framework to and use
algorithms to search and sort the elemnt of an array.

7 Modify the withdraw() method of Account class such that this method 102
should throw “Insufficient Fund Exception” if the account holder tries
to withdraw an amount that leads to condition where current balance
becomes less than minimum balance otherwise allow the account
holder to withdraw and update balance accordingly.
8 A) Define two threads such that one thread should print even numbers 104
and another thread should print even numbers.
B). Modify the Account class to implement synchronization concept.
C). Define two threads such that one thread should read a line of text
file and another thread should write that line of text to another file
(Thread communication example)
D). Write a program to implement thread priority.
9 Design the user screen as follows and handle the events appropriately. 112
Add Window
First Number
Second Number
Result
ADD SUBTRACT

10 Write a Java program to simulate a calculator. 114


11 Write a Java program for handling mouse events and key events. 120
12 a) Write a program for handling window events. 125

b) Develop an applet that displays a simple message.

62 | P a g e
13 Develop a client that sends data to the server and also develop a server 128
that sends data to the client (two way communication)
14 Develop a client server application in which client read a file name 131
from the key board and send the file name to the server, and server
will read the file name from client and send the file contents to the
client.
15. Write a program to illustrate the scope of default ,private,protected 133
and public access modifiers for variables and methods in java .
16 Write a java program to illustrate the usage of multiple catch blocks in 135
java.

17 Develop a program for passing parameters to an Applet. 136

63 | P a g e
OOP THROUGH JAVA LAB

1A) Write a program to print prime numbers up to a given number.

import java.util.Scanner;
class Test {
void check(int num) {
System.out.println ("Prime numbers up to "+num+" are:");
for (int i=1;i<=num;i++)
for (int j=2;j<i;j++) {
if(i%j==0)
break;
else if((i%j!=0)&&(j==i-1))
System.out.print(“ “+i);
}
}
} //end of class Test

class Prime {
public static void main(String args[ ]) {
Test obj1=new Test();
Scanner input=new Scanner(System.in);
System.out.println("Enter the value of n:");
int n=input.nextInt();
obj1.check(n);
}
}

64 | P a g e
B) Write a program to print roots of a quadratic equation ax2+bx+c=0.
import java.io.*;
import java.util.*;
class quad{
public static void main(String args[]){
Scanner s=new Scanner(System.in);
System.out.println("enter the values for a,b & c");
int a=s.nextInt();
int b=s.nextInt();
int c=s.nextInt();

double d,e;

d=((b*b)-(4*a*c));
if(d==0){
System.out.println("expression has real&equal roots");
e=(-b)/(2*a);
System.out.print("roots are:"+e+"\t"+e);
}
if(d>0){
System.out.println("expression has real&unreal roots");

e=(-b+Math.sqrt(d))/(2*a);

System.out.print("roots are:"+e+"\t");
e=(-b-Math.sqrt(d))/(2*a);
System.out.println(e);

65 | P a g e
}
if(d<0){
System.out.println("expression has imaginary rotts");
}
}
}

C) Write a program to print Fibonacci sequence up to a given number.

import java.util.Scanner;

class Fib {
public static void main(String args[ ]) {
Scanner input=new Scanner(System.in);
int i,a=0,b=1,c=0,t;
System.out.println("Enter value of t:");
t=input.nextInt();
System.out.print(a);
System.out.print(" "+b);
for(i=0;i<t-2;i++) {
c=a+b;
a=b;
b=c;
System.out.print(" "+c);
}

System.out.println();
System.out.print(t+"th value of the series is: "+c);
}
}

66 | P a g e
67 | P a g e
2A) Define a class to represent a bank account and include the following members
Instance Variables:
i) Name of depositor
ii) Account no
iii) Type of account
iv) Balance amount in the account
Instance Methods:
i) To assign instance variables (Customer-Zero argument and parameterized)
ii) To deposit an amount
iii) To withdraw amount after checking the balance
iv) To display name and address
Define ExecuteAccount class in which define main method to test above class.

2A) Define a class to represent a bank account and include the following members
Instance Variables:
i) Name of depositor
ii) Account no
iii) Type of account
iv) Balance amount in the account
Instance Methods:
i) To assign instance variables (Constructors-Zero argument and parameterized)
ii) To deposit an amount
iii) To withdraw amount after checking the balance
iv) To display name and address
Define ExecuteAccount class in which define main method to test above class.
import java.util.*;
class BankAccount
{
String name,type;
int acctno;
double balance;
double wbalance;
Scanner s = new Scanner(System.in);
public BankAccount()
{
name="abc";
type="saving";
acctno=1234567890;
balance=10000.00;
}
public BankAccount(String n,String t,int an,double bl)
{
name=n;
type=t;
acctno=an;
balance=bl;

68 | P a g e
}
void deposit()
{
double dat;
System.out.println("Enter the amount to deposit: ");
dat=s.nextDouble();
if(dat>0)
{
balance+=dat;
}
else
System.out.println("Enter the valid Amount");
}
void withdraw()
{
System.out.println("Enter the amount to withdraw : ");
wbalance=s.nextDouble();
if(wbalance>0)
{
balance-=wbalance;
}
else
System.out.println("Enter the valid Amount");
}
void display()
{
System.out.println("Account Holder Name: "+name);
System.out.println("Account Number: "+acctno);
System.out.println("Account Number: "+type);
System.out.println("Account Balance: "+balance);
System.out.println();
}
}
class ExecuteAccountA
{
public static void main(String args[])
{
BankAccount ba1=new BankAccount();
BankAccount ba2=new BankAccount("Sreenivas","Saving",1234567891,20000);
System.out.println("1st Account holder Details : \n");
ba1.display();
ba1.deposit();
ba1.withdraw();
ba1.display();
System.out.println("2nd Account holder Details : \n");
ba2.display();

69 | P a g e
ba2.deposit();
ba2.withdraw();
ba2.display();
}
}
Output:

B) In the above account class, maintain the total number of account holders present in the bank
and also define a method to display it. Change the main method appropriately.

import java.util.*;
class BankAccount
{
String name,type;
int acctno;
double balance;
double wbalance;
static int count=0;
Scanner s = new Scanner(System.in);

70 | P a g e
public BankAccount()
{
name="abc";
type="saving";
acctno=1234567890;
balance=10000.00;
count++;
}
public BankAccount(String n,String t,int an,double bl)
{
name=n;
type=t;
acctno=an;
balance=bl;
count++;
}
void deposit()
{
double dat;
System.out.println("Enter the amount to deposit: ");
dat=s.nextDouble();
if(dat>0)
{
balance+=dat;
}
else
System.out.println("Enter the valid Amount");
}
void withdraw()
{
System.out.println("Enter the amount to withdraw : ");
wbalance=s.nextDouble();
if(wbalance>0)
{
balance-=wbalance;
}
else
System.out.println("Enter the valid Amount");
}
void display()
{
System.out.println("Account Holder Name: "+name);
System.out.println("Account Number: "+acctno);
System.out.println("Account Number: "+type);
System.out.println("Account Balance: "+balance);
System.out.println();

71 | P a g e
}
static void totalAccounts()
{
System.out.println("Total No.of Accounts :"+count);
}
}
class ExecuteAccountB
{
public static void main(String args[])
{
BankAccount ba1=new BankAccount();
BankAccount ba2=new BankAccount("Sreenivas","Saving",1234567891,20000);
BankAccount ba3=new BankAccount("Sreenu","Saving",1234567892,30000);
BankAccount ba4=new BankAccount();
BankAccount ba5=new BankAccount("Srinu","Saving",1234567893,15000);
BankAccount.totalAccounts();
}
}
Output:

C) In main method of ExecuteAccount class, define an array to handle five accounts.

import java.util.*;
class BankAccount
{
String name,type;
int acctno;
double balance;
double wbalance;
static int count=0;
Scanner s = new Scanner(System.in);
public BankAccount()
{
name="abc";
type="saving";
acctno=1234567890;
balance=10000.00;
count++;
}
public BankAccount(String n,String t,int an,double bl)

72 | P a g e
{
name=n;
type=t;
acctno=an;
balance=bl;
count++;
}
void deposit()
{
double dat;
System.out.println("Enter the amount to deposit: ");
dat=s.nextDouble();
if(dat>0)
{
balance+=dat;
}
else
System.out.println("Enter the valid Amount");
}
void withdraw()
{
System.out.println("Enter the amount to withdraw : ");
wbalance=s.nextDouble();
if(wbalance>0)
{
balance-=wbalance;
}
else
System.out.println("Enter the valid Amount");
}
void display()
{
System.out.println("Account Holder Name: "+name);
System.out.println("Account Number: "+acctno);
System.out.println("Account Number: "+type);
System.out.println("Account Balance: "+balance);
System.out.println();
}
static void totalAccounts()
{
System.out.println("Total No.of Accounts :"+count);
}
}
class ExecuteAccountC
{
public static void main(String args[])

73 | P a g e
{
BankAccount[] ba=new BankAccount[5];
ba[0]=new BankAccount("Sreenivas","Saving",1234567891,20000);
ba[1]=new BankAccount("Sreenu","Saving",1234567892,30000);
ba[2]=new BankAccount();
ba[3]=new BankAccount("Srinu","Saving",1234567893,15000);
ba[4]=new BankAccount();
System.out.println("Five Accounts Details: ");
for(int i=0;i<ba.length;i++)
ba[i].display();
}
}
Output:

D) In Account class constructor, demonstrate the use of “this” keyword.


import java.util.*;
class BankAccount
{
String name,type;
int acctno;
double balance;
double wbalance;
static int count=0;
Scanner s = new Scanner(System.in);
public BankAccount()

74 | P a g e
{
name="abc";
type="saving";
acctno=1234567890;
balance=10000.00;
count++;
}
public BankAccount(String name,String type,int acctno,double balance)
{
this.name=name;
this.type=type;
this.acctno=acctno;
this.balance=balance;
count++;
}
void deposit()
{
double dat;
System.out.println("Enter the amount to deposit: ");
dat=s.nextDouble();
if(dat>0)
{
balance+=dat;
}
else
System.out.println("Enter the valid Amount");
}
void withdraw()
{
System.out.println("Enter the amount to withdraw : ");
wbalance=s.nextDouble();
if(wbalance>0)
{
balance-=wbalance;
}
else
System.out.println("Enter the valid Amount");
}
void display()
{
System.out.println("Account Holder Name: "+name);
System.out.println("Account Number: "+acctno);
System.out.println("Account Number: "+type);
System.out.println("Account Balance: "+balance);
System.out.println();
}

75 | P a g e
static void totalAccounts()
{
System.out.println("Total No.of Accounts :"+count);
}
}
class ExecuteAccountD
{
public static void main(String args[])
{
BankAccount ba1=new BankAccount();
BankAccount ba2=new BankAccount("Sreenivas","Saving",1234567891,20000);
ba1.display();
ba2.display();
}
}
Output:

E) Modify the constructor to read data from keyboard.


import java.util.*;
class BankAccount
{
String name,type;
int acctno;
double balance;
double wbalance;
static int count=0;
Scanner s = new Scanner(System.in);
public BankAccount()
{
System.out.println("Enter the Name: ");
name=s.nextLine();
System.out.println("Enter the type of Account: ");
type=s.nextLine();
System.out.println("Enter the Account Number: ");
acctno=s.nextInt();

76 | P a g e
System.out.println("Enter the Balance: ");
balance=s.nextDouble();
count++;
}
void deposit()
{
double dat;
System.out.println("Enter the amount to deposit: ");
dat=s.nextDouble();
if(dat>0)
{
balance+=dat;
}
else
System.out.println("Enter the valid Amount");
}
void withdraw()
{
System.out.println("Enter the amount to withdraw : ");
wbalance=s.nextDouble();
if(wbalance>0)
{
balance-=wbalance;
}
else
System.out.println("Enter the valid Amount");
}
void display()
{
System.out.println("Account Holder Name: "+name);
System.out.println("Account Number: "+acctno);
System.out.println("Account Number: "+type);
System.out.println("Account Balance: "+balance);
System.out.println();
}
static void totalAccounts()
{
System.out.println("Total No.of Accounts :"+count);
}
}
class ExecuteAccountE
{
public static void main(String args[])
{
BankAccount ba1=new BankAccount();
ba1.display();

77 | P a g e
}
}
Output:

F) Overload the method deposit () method (one with argument and another without argument)

import java.util.*;
class BankAccount
{
String name,type;
int acctno;
double balance;
double wbalance;
static int count=0;
Scanner s = new Scanner(System.in);
public BankAccount()
{
System.out.println("Enter the Name: ");
name=s.nextLine();
System.out.println("Enter the type of Account: ");
type=s.nextLine();
System.out.println("Enter the Account Number: ");
acctno=s.nextInt();
System.out.println("Enter the Balance: ");
balance=s.nextDouble();
count++;
}
void deposit()

78 | P a g e
{
double dat;
System.out.println("Enter the amount to deposit: ");
dat=s.nextDouble();
if(dat>0)
{
balance+=dat;
}
else
System.out.println("Enter the valid Amount");
}
void deposit(double d)
{
if(d>0)
{
balance+=d;
}
else
System.out.println("Enter the valid Amount");
}
void withdraw()
{
System.out.println("Enter the amount to withdraw : ");
wbalance=s.nextDouble();
if(wbalance>0)
{
balance-=wbalance;
}
else
System.out.println("Enter the valid Amount");
}
void display()
{
System.out.println("Account Holder Name: "+name);
System.out.println("Account Number: "+acctno);
System.out.println("Account Number: "+type);
System.out.println("Account Balance: "+balance);
System.out.println();
}
static void totalAccounts()
{
System.out.println("Total No.of Accounts :"+count);
}
}
class ExecuteAccountF
{

79 | P a g e
public static void main(String args[])
{
BankAccount ba1=new BankAccount();
System.out.println("Account Details :");
ba1.display();
ba1.deposit();
System.out.println("Account Details after deposit :");
ba1.display();
ba1.deposit(3500);
System.out.println("Account Details after deposit :");
ba1.display();
}
}
Output:

G) In Account class, define set and get methods for each instance variables.
Example:
For account number variable, define the methods.
getAccountNo() and setAccountNo(int accno)
In each and every method of Account class, reading data from and writing data to instance
variables should be done through these variables.

import java.util.Scanner;
class BankAccount{

80 | P a g e
String AcctName,Type;
long AcctNo;
double balance;
Scanner s=new Scanner(System.in);

void getAcctNo(){
System.out.println("Acct Number is :"+AcctNo);
}

void setAcctNo(int acctno){


AcctNo=acctno;
}

void getAcctBalance(){
System.out.println("Acct balance is :"+balance);
}

void setAcctBalance(double bal){


balance=bal;
}
void setName(String s){
AcctName=s;
}
void getName(){
System.out.println("AcctName is:"+AcctName);

}
void setType(String type){
Type=type;
}
void getType(){
System.out.println("Account type is: "+Type);
}
public BankAccount(String Name,String T,long AccNo,double bal){

AcctName=Name;
Type=T;
balance=bal;
AcctNo=AccNo;

void deposit(){
getAcctBalance();
}

81 | P a g e
void withdraw(){
double wbal;
System.out.print("Enter with draw amount:");
wbal=s.nextLong();
System.out.println("with draw amount is:"+wbal);
balance=balance-wbal;
System.out.println("balance after with drawing: "+balance);
}

void display(){
getAcctNo();
getType();
getName();

}
}
class ExecuteAccountG{
public static void main(String args[]){

BankAccount ba=new BankAccount("abc","saving",1234,20000.00);

ba.display();
ba.getAcctBalance();
ba.withdraw();
ba.deposit();

}
}

82 | P a g e
3. A) Define Resister class in which we define the following members:
Instance variables:
resistance
Instance Methods:
giveData():To assign data to the resistance variable
displayData(): To display data in the resistance variable
constructors
Define subclasses for the Resistor class called SeriesCircuit and ParallelCircuit in w h i c h
define methods : calculateSeriesResistance( ) and
calculateParallelResistance() respectively.Both the methods should take two Resistor objects as
arguments and return Resistor object as result.ln main method , define another class called
ResistorExecute to test the above class.

import java.util.Scanner;
class Resistor
{
float resistance;
void giveData()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter value of resistance");
resistance=sc.nextFloat();
}
void displayData()
{
System.out.println("resultant value of series is :"+resistance);
}
}
class SeriesCircuit extends Resistor
{
Resistor calculateSeriesResistance(Resistor r1,Resistor r2)
{
Resistor r3=new Resistor();
r3.resistance=r1.resistance+r2.resistance;
return r3;
}
}
class ParallelCircuit extends Resistor
{
Resistor calculateParallelResistance(Resistor r1,Resistor r2)
{
Resistor r4=new Resistor();
r4.resistance=(r1.resistance*r2.resistance)/(r1.resistance+r2.resistance);
return r4;
}
}

83 | P a g e
class ResistorExecute
{
public static void main(String args[])
{
Resistor r3,r4;
Resistor r1=new Resistor();
r1.giveData();
Resistor r2=new Resistor();
r2.giveData();
SeriesCircuit sc=new SeriesCircuit();
r3=sc.calculateSeriesResistance(r1,r2);
r3.displayData();
ParallelCircuit PA=new ParallelCircuit();
r4=PA.calculateParallelResistance(r1,r2);
r4.displayData();
}
}
Output:

84 | P a g e
B) Modify the above two methods which should accept array of Resistor objects as argument and return
Resistor object as result.

import java.util.Scanner;
class Resistor
{
float resistance;
void giveData()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter value of resistance");
resistance=sc.nextFloat();
}
void displayData()
{
System.out.println("resultant value of series is :"+resistance);
}
}
class SeriesCircuit extends Resistor
{
Resistor calculateSeriesResistance(Resistor[] r)
{
Resistor r3=new Resistor();
r3.resistance=r[0].resistance+r[1].resistance;
return r3;
}
}
class ParallelCircuit extends Resistor
{
Resistor calculateParallelResistance(Resistor[] r)
{
Resistor r4=new Resistor();
r4.resistance=(r[0].resistance*r[1].resistance)/(r[0].resistance+r[1].resistance);
return r4;
}
}
class ResistorExecuteA
{
public static void main(String args[])
{
Resistor r3,r4;
Resistor[] r=new Resistor[2];
r[0]=new Resistor();
r[1]=new Resistor();
for(int i=0;i<2;i++)

85 | P a g e
r[i].giveData();
SeriesCircuit sc=new SeriesCircuit();
r3=sc.calculateSeriesResistance(r);
r3.displayData();
ParallelCircuit PA=new ParallelCircuit();
r4=PA.calculateParallelResistance(r);
r4.displayData();
}
}
Output:

86 | P a g e
4. A) Write a program to demonstrate method overriding.

class Simple
{
void method()
{
System.out.println("method in Simple");
}
}
class SimpleA extends Simple
{
void method()
{
System.out.println("method in SimpleA");
}
}
class TestOverRiding
{
public static void main(String[] args)
{
Simple s1=new Simple();
s1.method();
SimpleA s2=new SimpleA();
s2.method();
Simple s3=new SimpleA();
s3.method();
}
}

Output:

87 | P a g e
B) Write a program to demonstrate the uses of "super" keyword (three uses)

//Call Base Class Constructor using super


class SuperClass
{
public SuperClass(String str)
{
System.out.println("Base Class Constructor " + str);
}
}
class SubClass extends SuperClass
{
public SubClass(String str)
{
super(str);
System.out.println("Sub Class Constructor " + str);
}
}
class MainClass1
{
public static void main(String args[])
{
SubClass obj = new SubClass("called");
}
}

Output:

//Call Base Class Method using super


class SuperClass
{
void display()
{
System.out.println("Base Class method called");

88 | P a g e
}
}
class SubClass extends SuperClass
{

void display()

{
super.display();
System.out.println("Sub Class method called");
}
}
class MainClass2
{
public static void main(String args[])
{
SubClass obj = new SubClass();
obj.display();
}
}

Output:

//Access Base Class Variables using super


class SuperClass
{
int a = 10;
}

class SubClass extends SuperClass


{
int a = 20;
void display()

89 | P a g e
{
System.out.println("The value is : " + super.a);
}
}

class MainClass3
{
public static void main(String args[])
{
SubClass obj = new SubClass();
obj.display();
}
}

Output:

90 | P a g e
C) Write a program to demonstrate dynamic method dispatch (i.e. Dynamic polymorphism).

//Dynamic Method Dispatch


class A
{
void callme()
{
System.out.println("Inside A's callme method");
}
}
class B extends A
{
void callme()
{
System.out.println("Inside B's callme method");
}
}
class C extends B
{
void callme()
{
System.out.println("Inside C's callme method");
}
}
class Dispatch
{
public static void main(String args[])
{
A a=new A();
B b=new B();
C c=new C();

A r;

r=a;
r.callme();

r=b;
r.callme();

r=c;
r.callme();
}
}

91 | P a g e
Output:

92 | P a g e
5) A) Write a program to check whether the given string is palindrome or not.

import java.util.Scanner;
class Palindrome
{
public static void main(String[] args)
{
String str;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String : ");
str=in.nextLine();
StringBuffer sb=new StringBuffer(str);
String rstr=sb.reverse().toString();
if(str.equals(rstr))
System.out.println("The given String is Palindrome");
else
System.out.println("The given String is not Palindrome");
}
}

Output:

93 | P a g e
B) Write a program for sorting a given list of names in ascending order.

import java.util.Scanner;
class StringSort
{
public static void main(String args[])
{
String names[]=new String[5];
Scanner in = new Scanner(System.in);
System.out.println("Enter the Names: ");
for (int i = 0; i < 5; i++)
{
names[i]=in.nextLine();
}
int size=names.length;
System.out.println(size);
System.out.println("Before Sorting : ");
for(int i=0;i<size;i++)
{
System.out.println(names[i]);
}
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(names[i].compareTo(names[j])>0)
{
String temp=names[i];
names[i]=names[j];
names[j]=temp;
}
}
}
System.out.println("After Sorting : ");
for(int i=0;i<size;i++)
{
System.out.println(names[i]);
}
}
}

94 | P a g e
Output:

95 | P a g e
C) Write a program to count the no. of words in a given text.

import java.io.*;
import java.util.*;
class Count
{
public static void main(String args[ ])throws IOException
{
long nl=0,nw=0,nc=0;
String line;
BufferedReader br=new BufferedReader(new FileReader(args[0]));
while ((line=br.readLine())!=null)
{
nl++;
nc=nc+line.length();
StringTokenizer st = new StringTokenizer(line);
nw += st.countTokens();
}
System.out.println("Number of Characters: "+nc);
System.out.println("Number of Words: "+nw);
System.out.println("Number of Lines: "+nl);
}
}

Output:

96 | P a g e
6. A) Define an interface "GeomtricShape" with methods area( ) and perimeter()
(Bothmethod's return type and parameter list should be void and empty respectively). D e f i n e
c l a s s e s l i k e T r i a n g l e , R e c t a n g l e a n d C i r c l e i m p l e m e n t i n g t h e "GeometricShape"
interface and also define "ExecuteMain" class in which include main method to test the above
classes.

import java.util.Scanner;
interface GeometricShape
{
void area();
void perimeter();
}
class Triangle implements GeometricShape
{
double a=1,b=2,c=1,h=4;
public void area()
{
System.out.println("");
double area1=0.5*b*h;
System.out.println("Area of a Triangle: "+area1);
}
public void perimeter()
{
double per=a+b+c;
System.out.println("Perimeter of a Triangle: "+per);
System.out.println("");
}
}
class Rectangle implements GeometricShape
{
int length=15,width=10,per,area1;
public void area()
{
area1=length*width;
System.out.println("Area of Rectangle: "+area1);
}
public void perimeter()
{
per=2*length+2*width;
System.out.println("Perimeter of Rectangle: "+per);
System.out.println("");
}
}
class Circle implements GeometricShape
{
int r=10;

97 | P a g e
double p=3.141,area1=0.0,per=0.0;
public void area()
{
area1=p*r*r;
System.out.println("Area of Circle: "+area1);
}
public void perimeter()
{
per=2*p*r;
System.out.println("Perimeter of Circle: "+per);
System.out.println("");
}
}
class ExecuteMain
{
public static void main(String args[])
{
Triangle t=new Triangle();
t.area();
t.perimeter();
Circle c=new Circle();
c.area();
c.perimeter();
Rectangle r=new Rectangle();
r.area();
r.perimeter();
}
}

Output:

98 | P a g e
B) Define a package with name “sortapp” in which declare an interface “SortInterface” with
method sort () whose return type and parameter type should be void and empty. Define
“subsortapp” as sub package of “sortapp” package in which define class “SortImpl”
implementing “SortInterface” in which sort() method should print a message Linear sort is used.
Define a package “searchingapp” in which declare an interface “SearchInterface” with search ()
method whose return type and parameter list should be void and empty respectively.
Define “serachingimpl” package in which define a “SearchImpl” class implementing
“SearchInterface” defined in “searchingapp” package in which define a search() method which
should print a message linear search is used.
Define a class ExecutePackage with main method using the above packages (classes and it’s
methods).

//program1
package sortapp;
public interface SortInterface
{
void sort();
}

//program2
package sortapp.subsortapp;
import sortapp.*;

public class SortImpl implements SortInterface


{
public void sort()
{
System.out.println("Sort Interface.......");
}
}

//program3
package searchingapp;
public interface SearchInterface
{
void search();
}

//program4

package searchingimpl;
import searchingapp.*;
public class SearchImpl implements SearchInterface

99 | P a g e
{
public void search()
{
System.out.println("Search Interface.......");
}
}

//program5

import sortapp.SortInterface;
import sortapp.subsortapp.SortImpl;
import searchingapp.SearchInterface;
import searchingimpl.SearchImpl;
class ExecutePackageB
{
public static void main(String args[])
{
SortImpl sort1=new SortImpl();
SearchImpl search1=new SearchImpl();
sort1.sort();
search1.search();
}
}

Output:

100 | P a g e
101 | P a g e
7). Modify the withdraw() method of Account class such that this method should throw
“InsufficientFundException” if the account holder tries to withdraw an amount that leads to
condition where current balance becomes less than minimum balance otherwise allow the
account holder to withdraw and update balance accordingly.

import java.util.Scanner;
class InsufficientException extends Exception{
double balance;
double wbalance;
public InsufficientException(String msg){
super(msg);
}
void withdraw(){
double balance=25000.00;
System.out.println("Current Balance: "+balance);
try{
System.out.print("Enter withdraw amount: ");
Scanner in=new Scanner(System.in);
double wamount=in.nextDouble();
if(wamount>balance){
throw new InsufficientException("Insufficient balance in account.....");
}
else
System.out.println("Transaction Successfully Completed...............");
double rembal=balance-wamount;
System.out.println("Withdrawal Amount :"+wamount);
System.out.println("After transaction current balance :"+rembal);
}
catch(InsufficientException e){
System.out.println("Caught:"+e.getMessage());
}
}
}
class ExecuteAccount6{
public static void main(String args[]) {
InsufficientException ie=new InsufficientException("Insufficient balance in account");
ie.withdraw();
}
}

102 | P a g e
103 | P a g e
8. A) Define two threads such that one thread should print even numbers and another thread
should print odd numbers.
public class EvenOddNumber
{
int i = 1;

public synchronized void printNumber(String threadNm) throws InterruptedException


{

if(threadNm.equals("t1"))
{
if(i%2 == 1)
{
System.out.println(Thread.currentThread().getName()+"--"+ i++);
notify();
}
else
{
wait();
}
} else if(threadNm.equals("t2"))
{
if(i%2 == 0)
{
System.out.println(Thread.currentThread().getName()+"--"+ i++);
notify();
}
else
{
wait();
}
}

public static void main(String[] args)


{
final EvenOddNumber obj = new EvenOddNumber();
Thread t1 = new Thread(new Runnable()
{

public void run() {


try {
while(obj.i <= 10){

104 | P a g e
obj.printNumber(Thread.currentThread().getName());
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("done t1");
}
});
Thread t2 = new Thread(new Runnable() {

public void run() {


try {
while(obj.i <=10){
obj.printNumber(Thread.currentThread().getName());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("done t2");
}
});

t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
Output:

105 | P a g e
B) Write a program to implement thread synchronization concept.
//example of java synchronized method
class Table{
synchronized void printTable(int n)
{//synchronized method
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}

}
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}

}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}

106 | P a g e
public class TestSynchronization2
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:

107 | P a g e
C) Define two threads such that one thread should read a line of text from text file and another
thread should write that line of text to another file. (Thread communication example).
import java.io.*;
import java.util.*;
public class ThreadReadDemo
{
public static void main(String[] args)
{
Thread t1=new Thread(new MultiThread(),"A");
Thread t2=new Thread(new MultiThread(),"B");
t1.start();
t2.start();
}
}
class MultiThread implements Runnable
{
private static BufferedReader br = null;
private List<String> list;
static
{
try
{
br = new BufferedReader(new FileReader("D:/ee.txt"),10);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}

public void run()


{
String line = null;
int count = 0;
while(true)
{
this.list = new ArrayList<String>();
synchronized(br)
{
try
{
while((line = br.readLine()) != null)
{
if(count<15)
{
list.add(line);

108 | P a g e
count++;
}
else
{
list.add(line);
count = 0;
break;
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
Thread.sleep(1);
display(this.list);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
if(line == null)
break;
}
}

public void display(List<String> list)


{
for(String str:list)
{
System.out.println(str);
}
}

}
Output:

109 | P a g e
D) Write a program to implement thread priority.

public class TestPriority extends Thread


{
public static void main(String args[])
{
TestPriority tp1 = new TestPriority();
TestPriority tp2 = new TestPriority();

tp1.setPriority(Thread.MAX_PRIORITY-1);
tp2.setPriority(Thread.MIN_PRIORITY+1);
tp1.setName("High");
tp2.setName("Less");
System.out.println("High Priority is " + tp1.getPriority());
System.out.println("Less Priority is " + tp2.getPriority());
tp2.start();
tp1.start();
}
public void run()
{
for(int i=0; i<10; i++)
{
System.out.println(this.getName() + ": " + i);
}
}
}

110 | P a g e
111 | P a g e
9) Design the user screen as follows and handle the events appropriately.
Add Window
First Number
Second Number
Result
ADD SUBTRACT

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

class AddSub extends Frame implements ActionListener


{
Label l1,l2,l3;
TextField t1,t2,t3;
JButton b1,b2;
AddSub()
{
super("Addition of two numbers");
setLayout(null);
setSize(500,400);
setVisible(true);
l1=new Label("Enter the first no:");
l2=new Label("Enter the second no:");
l3=new Label("Result:");
t1=new TextField();
t2=new TextField();
t3=new TextField();
b1=new JButton("ADD");
b2=new JButton("SUB");
l1.setBounds(100,50,120,20);
add(l1);
t1.setBounds(240,50,50,20);
add(t1);
l2.setBounds(100,80,130,20);
add(l2);
t2.setBounds(240,80,50,20);
add(t2);
t3.setBounds(240,110,50,20);
add(t3);
l3.setBounds(100,110,100,20);
add(l3);
b1.setBounds(200,150,70,50);
add(b1);
b2.setBounds(300,150,70,50);

112 | P a g e
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);

addWindowListener( new WindowAdapter() {


public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae)
{
float a,b,c;
if(ae.getSource()==b1)
{
a=Float.parseFloat(t1.getText().trim());
b=Float.parseFloat(t2.getText().trim());
c=a+b;
t3.setText(Float.toString(c));
}
if(ae.getSource()==b2)
{
a=Float.parseFloat(t1.getText().trim());
b=Float.parseFloat(t2.getText().trim());
c=a-b;
t3.setText(Float.toString(c));
}
}
public static void main(String s[])
{
AddSub ob=new AddSub();
}
}
Output:

113 | P a g e
10) Write a program to simulate a calculator.
import javax.swing.*;
import java.awt.event.*;
class Calc implements ActionListener
{
JFrame f;
JTextField t;
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b0,bdiv,bmul,bsub,badd,bdec,beq,bdel,bclr;

static double a=0,b=0,result=0;


static int operator=0;

Calc()
{
f=new JFrame("Calculator");
t=new JTextField();
b1=new JButton("1");
b2=new JButton("2");
b3=new JButton("3");
b4=new JButton("4");
b5=new JButton("5");
b6=new JButton("6");
b7=new JButton("7");
b8=new JButton("8");
b9=new JButton("9");
b0=new JButton("0");
bdiv=new JButton("/");
bmul=new JButton("*");
bsub=new JButton("-");
badd=new JButton("+");
bdec=new JButton(".");
beq=new JButton("=");
bdel=new JButton("Delete");
bclr=new JButton("Clear");

t.setBounds(30,40,280,30);
b7.setBounds(40,100,50,40);
b8.setBounds(110,100,50,40);
b9.setBounds(180,100,50,40);
bdiv.setBounds(250,100,50,40);

b4.setBounds(40,170,50,40);
b5.setBounds(110,170,50,40);
b6.setBounds(180,170,50,40);
bmul.setBounds(250,170,50,40);

114 | P a g e
b1.setBounds(40,240,50,40);
b2.setBounds(110,240,50,40);
b3.setBounds(180,240,50,40);
bsub.setBounds(250,240,50,40);

bdec.setBounds(40,310,50,40);
b0.setBounds(110,310,50,40);
beq.setBounds(180,310,50,40);
badd.setBounds(250,310,50,40);

bdel.setBounds(60,380,100,40);
bclr.setBounds(180,380,100,40);

f.add(t);
f.add(b7);
f.add(b8);
f.add(b9);
f.add(bdiv);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(bmul);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(bsub);
f.add(bdec);
f.add(b0);
f.add(beq);
f.add(badd);
f.add(bdel);
f.add(bclr);

f.setLayout(null);
f.setVisible(true);
f.setSize(350,500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);

115 | P a g e
b8.addActionListener(this);
b9.addActionListener(this);
b0.addActionListener(this);
badd.addActionListener(this);
bdiv.addActionListener(this);
bmul.addActionListener(this);
bsub.addActionListener(this);
bdec.addActionListener(this);
beq.addActionListener(this);
bdel.addActionListener(this);
bclr.addActionListener(this);
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource()==b1)
t.setText(t.getText().concat("1"));

if(e.getSource()==b2)
t.setText(t.getText().concat("2"));

if(e.getSource()==b3)
t.setText(t.getText().concat("3"));

if(e.getSource()==b4)
t.setText(t.getText().concat("4"));

if(e.getSource()==b5)
t.setText(t.getText().concat("5"));

if(e.getSource()==b6)
t.setText(t.getText().concat("6"));

if(e.getSource()==b7)
t.setText(t.getText().concat("7"));

if(e.getSource()==b8)
t.setText(t.getText().concat("8"));

if(e.getSource()==b9)
t.setText(t.getText().concat("9"));

if(e.getSource()==b0)
t.setText(t.getText().concat("0"));

if(e.getSource()==bdec)

116 | P a g e
t.setText(t.getText().concat("."));

if(e.getSource()==badd)
{
a=Double.parseDouble(t.getText());
operator=1;
t.setText("");
}

if(e.getSource()==bsub)
{
a=Double.parseDouble(t.getText());
operator=2;
t.setText("");
}

if(e.getSource()==bmul)
{
a=Double.parseDouble(t.getText());
operator=3;
t.setText("");
}

if(e.getSource()==bdiv)
{
a=Double.parseDouble(t.getText());
operator=4;
t.setText("");
}

if(e.getSource()==beq)
{
b=Double.parseDouble(t.getText());

switch(operator)
{
case 1: result=a+b;
break;

case 2: result=a-b;
break;

case 3: result=a*b;
break;

case 4: result=a/b;

117 | P a g e
break;

default: result=0;
}

t.setText(""+result);
}

if(e.getSource()==bclr)
t.setText("");

if(e.getSource()==bdel)
{
String s=t.getText();
t.setText("");
for(int i=0;i<s.length()-1;i++)
t.setText(t.getText()+s.charAt(i));
}
}

public static void main(String...s)


{
new Calc();
}
}

118 | P a g e
119 | P a g e
11) Write a Java program for handling mouse events and key events.

// demonstrate the mouse event handlers.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="MouseEvents" width=300 height=100></applet>*/

public class MouseEvents extends Applet implements MouseListener,


MouseMotionListener,MouseWheelListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse

public void init() {


addMouseListener(this);
addMouseMotionListener(this);
addMouseWheelListener(this);
}

// Handle mouse clicked.


public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}

// Handle mouse entered.


public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}

// Handle mouse exited.


public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}

120 | P a g e
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}

// Handle button released.


public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}

// Handle mouse dragged.


public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}

// Handle mouse moved.


public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}

// Handle mouse wheel moved.


public void mouseWheelMoved(MouseWheelEvent me) {
// show status
showStatus("Mouse Wheel Moving at " + me.getX() + ", " + me.getY());
}

// Display msg in applet window at current X,Y location.


public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}
Output:

121 | P a g e
// demonstrate some virtual key codes.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="KeyEvents" width=300 height=100></applet>*/
public class KeyEvents extends Applet implements KeyListener
{
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init()
{
addKeyListener(this);

public void keyPressed(KeyEvent ke)


{
showStatus("Key Down");
int key = ke.getKeyCode();
switch(key) {
case KeyEvent.VK_PAGE_DOWN:
msg += "<PgDn>";
break;
case KeyEvent.VK_PAGE_UP:
msg += "<PgUp>";
break;
case KeyEvent.VK_LEFT:
msg += "<Left Arrow>";
break;
122 | P a g e
case KeyEvent.VK_UP:
msg += "<Up Arrow>";
break;
case KeyEvent.VK_DOWN:
msg += "<Down Arrow>";
break;
case KeyEvent.VK_9:
msg += "<Digit 9>";
break;
case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>";
break;
}
repaint();
}

public void keyReleased(KeyEvent ke)


{
showStatus("Key Up");
}

public void keyTyped(KeyEvent ke)


{
msg += ke.getKeyChar();
repaint();
}

// Display keystrokes.
public void paint(Graphics g)
{
g.drawString(msg, X, Y);
}
}

Output:

123 | P a g e
124 | P a g e
12) a) Write a program for handling window events.
import java.awt.*;
import java.awt.event.*;
class Myclass implements WindowListener
{
public void windowActivated(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void windowDeactivated(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowOpened(WindowEvent e){}
}
class MyFrame extends Frame
{
public static void main(String[] args)
{
MyFrame f = new MyFrame();
f.setTitle("My AWT Frame");
f.setSize(400,400);
f.setVisible(true);
f.addWindowListener(new Myclass());
}
}
Output:

125 | P a g e
b) Develop an applet that displays a simple message.
import java.awt.*;
import java.applet.Applet;
/* <applet code="SimpleApplet" width=300 height=50> </applet> */
public class SimpleApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString ("A Simple Applet",100, 100);
}
}
Output:

126 | P a g e
127 | P a g e
13) Develop a client that sends data to the server and also develop a server that sends data to the
client (two way communication)

import java.io.*;
import java.net.*;
class Client2
{
public static void main(String args[])throws Exception
{
Socket s=new Socket("localhost",777);
DataOutputStream dos=new DataOutputStream(s.getOutputStream());

InputStream obj=s.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(obj));
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in));
String str,str1;
while(!(str=kb.readLine()).equals("exit"))
{
dos.writeBytes(str+"\n");
str1=br.readLine();
System.out.println(str1);
}
dos.close();
br.close();
kb.close();
s.close();
}
}

import java.io.*;
import java.net.*;

class Server2
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(777);
Socket s=ss.accept();
System.out.println("Connection Established\n");
OutputStream obj=s.getOutputStream();
PrintStream ps=new PrintStream(obj);
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String str,str1;

128 | P a g e
while((str=br.readLine())!=null)
{
System.out.println(str);
str1=kb.readLine();
ps.println(str1);
}

ps.close();
br.close();
kb.close();
ss.close();
s.close();
System.exit(0);

}
}

129 | P a g e
130 | P a g e
14) Develop a client server application in which client read a file name from the key board and
send the file name to the server, and server will read the file name from client and send the file
contents to the client.

import java.net.*;
import java.io.*;
public class ContentsClient
{
public static void main( String args[ ] ) throws Exception
{
Socket sock = new Socket( "127.0.0.1", 4000);

// reading the file name from keyboard. Uses input stream


System.out.print("Enter the file name");
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
String fname = keyRead.readLine();

// sending the file name to server. Uses PrintWriter


OutputStream ostream = sock.getOutputStream( );
PrintWriter pwrite = new PrintWriter(ostream, true);
pwrite.println(fname);
// receiving the contents from server. Uses input stream
InputStream istream = sock.getInputStream();
BufferedReader socketRead = new BufferedReader(new InputStreamReader(istream));

String str;
while((str = socketRead.readLine()) != null) // reading line-by-line
{
System.out.println(str);
}
pwrite.close(); socketRead.close(); keyRead.close();
}
}

import java.net.*;
import java.io.*;
public class ContentsServer
{
public static void main(String args[]) throws Exception
{ // establishing the connection with the server
ServerSocket sersock = new ServerSocket(4000);
System.out.println("Server ready for connection");
Socket sock = sersock.accept(); // binding with port: 4000
System.out.println("Connection is successful and wating for chatting");

// reading the file name from client

131 | P a g e
InputStream istream = sock.getInputStream( );
BufferedReader fileRead =new BufferedReader(new InputStreamReader(istream));
String fname = fileRead.readLine( );
// reading file contents
BufferedReader contentRead = new BufferedReader(new FileReader(fname) );

// keeping output stream ready to send the contents


OutputStream ostream = sock.getOutputStream( );
PrintWriter pwrite = new PrintWriter(ostream, true);

String str;
while((str = contentRead.readLine()) != null) // reading line-by-line from file
{
pwrite.println(str); // sending each line to client
}

sock.close(); sersock.close(); // closing network sockets


pwrite.close(); fileRead.close(); contentRead.close();
}
}

Programs Beyond the Syllabus

132 | P a g e
15.Write java programs to illustrate the scope of default ,private,protected and public access
modifiers for variables and methods in java..

Java program to illustrate private modifier


class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}}
Java program to illustrate default modifier

package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

Java program to illustrate protected modifier

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

133 | P a g e
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello

Java program to illustrate public modifier

//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

134 | P a g e
16) Write a java program to illustrate the usage of multiple catch blocks in java.
class MultipleCatchBlock {
public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Test it Now

Output:

Arithmetic Exception occurs


rest of the code

135 | P a g e
17) Develop a program for passing parameters to an Applet.

import java.applet.Applet;
import java.awt.*;
/* <APPLET CODE="HelloAppletMsg" width=500 height=400>
<PARAM NAME="Greetings" VALUE="Hello , How are you?">
</APPLET> */
public class HelloAppletMsg extends Applet {
String msg;
public void init()
{
msg = getParameter("Greetings");
if( msg == null)
msg = "Hello";
}
public void paint(Graphics g) {
g.drawString (msg,10, 100);
}
}

136 | P a g e
(

SREENIDHI INSTITUTE OF SCIENCE AND TECHNOLOGY


(Approved by AICTE & GOVT OF A.P and Affiliated to JNTU)
Yamnampet, Ghatkesar, Hyderabad – 501 301

LABORATORY MANUAL

FOR

ANALOG AND PULSE CIRCUITS (8D463)


(II/II B.TECH –ECM)

DEPARTMENT
OF

137 | P a g e
ELECTRONICS AND COMPUTER ENGINEERING (ECM)
February 2023

138 | P a g e
VISION OF THE DEPARTMENT
To emerge as a premier centre in Electronics and Computer engineering with focus on human
values and professional ethics

MISSION OF THE DEPARTMENT


1. To prepare Electronics and Computer Engineering graduates to be a life- long learner
with competence in basic sciences, engineering & professional core, interdisciplinary
subjects, so that they can have professional career or to pursue higher studies.
2. Developing liaison with Academia, R & D institutions, software and electronics Indus-
tries for exposure of students to the practical aspects in engineering and solution of the
industry oriented and societal problems, entrepreneurial pursuit and project management
3. Inculcating interpersonal skills, team work, professional ethics, IPR and regulatory is-
sues in students to improve their employability and promoting leadership in changing
global environment
4. To continuously engage in research and development activities and to promote scientific
temper in the graduates.

139 | P a g e
Program Outcomes (POs)

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in Independent and life-long learning in the broadest context of technological
change.

140 | P a g e
Program Specific Outcomes (PSO)

1. System Development and Research Activity:


Ability to identify, formulate and solve engineering problems using computation and ap-
propriate algorithms in one or more fields of electronics and computer engineering, such
as Internet Of Things, embedded systems, computer vision, machine learning, artificial
intelligence, and signal processing
2. Problem Analysis and Design
Ability to use contemporary engineering tools and techniques and adapt to the industry
needs for solving multi-disciplinary problems
3. Successful Career:
Ability to design a system or process to meet desired needs within realistic constraints
such as economic, environmental, social, political, ethical, safety, and sustainability.

Program Educational Objectives (PEOs)

PEO - I. Graduates will have strong foundation in fundamentals of basic sciences, mathematics,
Engineering sciences and technology with abilities to understand societal problems
PEO - II. Graduates will have successful professional career by demonstrating good scientific
and engineering breadth to comprehend the problems using modern tools , conduct
experiments, analyze the results and design novel products and solutions to the real life
problems.
PEO - III. Graduates will be motivated to achieve academic excellence and promote
entrepreneurship and skills in project and finance management, pursue research to
develop life – long learning in a world of constantly evolving technology
PEO- IV. Graduates will be trained in human values, Professional ethics and Intellectual
Property related issues in broader environmental and social context and sustainable
development, communication skills, team work skills, leadership and multidisciplinary
approach.

141 | P a g e
LAB MANUAL ANALOG AND PULSE CIRCUITS (8D463)
L T P/D C
0 0 2 1

Course Objectives: To prepare students to practice the design and analysis of any Analog electronics circuit.

Course Outcomes:
At the end of the laboratory course, the students will be able to
1. To understand the design and working of various linear and non-linear wave shaping circuits.
2. To demonstrate the working principle of various multivibrators.
3. To verify the functionalities of various logic gates.
4. To perform and verify the BJT/ FET and feedback amplifiers.
5. To perform and verify the working of oscillators and voltage regulators.
6. To perform laboratory experiment to verify the conversion efficiency of various power amplifiers.

Mapping of Course Outcomes with Program Outcomes


PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
CO1 3 3 3 2 2 2 3 2
CO2 3 3 3 2 2 2 3 2
CO3 2 3 3 2 2 2 3 2
CO4 3 3 3 2 2 2 3 2
CO5 2 3 3 2 2 2 3 2
C06 3 3 3 2 2 2 3 2
Overall 3 3 3 2 2 2 3 2
7.

Syllabus Content:
Part-A: Hardware based experiments
1. Linear wave shaping.
2. Non Linear wave shaping – Clippers. clampers.
3. UJT Relaxation Oscillator
4. Astable and monostable Multivibrator.
5. Bistable Multivibrator.
6. Study of Logic Gates with discrete components.

Part-B: Software Simulation based experiments (Multisim OR Pspice OR Tina Pro Or


Equivalent Simulation Software)
1. Common Emitter and Common Source amplifier
2. Voltage shunt and Feedback Amplifier
3. Cascade Amplifier (CE+CE, CE+CC)
4. RC Phase Shift Oscillator using Transistors
5. Class- A and Class-B Complementary Symmetry Power Amplifier
6. Series and Shunt Voltage Regulator.

142 | P a g e
Contents
S.No: Name of the Experiment Page No
CYCLE - I
1 Linear Wave Shaping 143
2 Non Linear Wave Shaping Clipper Circuits 151
3 Non Linear Wave Shaping Clamper 160
4 Study Of Logic Gates 165
5 Astable Multivibrator 170
6 Monostable Multivibrator 173
7 Bi Stable Multivibrator 176
8 UJT Relaxation Oscillator 178

CYCLE – II

1 Common Emitter Amplifier 181


2 Common Source Amplifier 185
3 Two Stage RC coupled Amplifier 187
4 Darlington Pair (CC +CC) 190
5 Voltage Shunt feedback Amplifier 192
6 RC Phase Shift Oscillator 195
7 Class A Power Amplifier 197
8 Class B complementary symmetry Power Amplifier 200
9 Sereis and Shunt voltage Regulator 204

143 | P a g e
1. LINEAR WAVE SHAPING

AIM: To understand linear wave shaping using RC high pass and Low pass circuits.

APPARATUS:
1. Bread Board
2. Resistor- 1KΩ-1No.
3. Regulated power supply
4. capacitors- 0.01μf – 1 No.
5. Connecting wires.
6. Function Generator.
7. CRO Probes
8. CRO

CIRCUIT DIAGRAM:
i) High pass circuit:

ii) Low pass circuit:

144 | P a g e
THEORY:
The linear wave shaping circuits alter the shape of a waveform by passing them though a
process of differentiation or integration. High pass circuits allow high frequency signals and
attenuate low frequency signals. High pass circuits acts as a good differentiator for RC<<T. Low
pass circuits allows low frequency signals and attenuates high frequency signals. Low pass
circuits acts as a good Integrator for RC>>T.

PROCEDURE:

i) High pass RC circuit:


1. Before connection calculate the time constant τ.
2. Connect high pass RC circuit as per the circuit shown in figure.
3. Connect a square wave generator to the input of the circuit.
4. Connect the CRO channel-I to the input and channel-II to the output of circuit.
5. Adjust the square wave amplitude to 5V peak to peak & note down the input waveform.
6. Adjust the frequency of square wave generator such that i) T<< τ ii) T= τ iii) T>> τ
7. Observe and note down the output waveforms in each case.
8. Now calculate % tilt from the output waveform for case T<< τ and check whether it is equal to
theoretical value or not.

i) Low pass RC circuit:

1. Before connection calculate the time constant τ.


2. Connect low pass RC circuit as per the circuit shown in figure.
3. Connect a square wave generator to the input of the circuit.
4. Connect the CRO channel-I to the input and channel-II to the output of circuit.
5. Adjust the square wave amplitude to 5V peak to peak & note down the input waveform.
6. Adjust the frequency of square wave generator such that i) T<< τ ii) T= τ iii) T>> τ
7. Observe and note down the output waveforms in each case.
8. Now calculate rise time tr from output waveforms for case T<< τ and verify whether it is equal
to theoretical value or not.

145 | P a g e
EXPECTED WAVEFORM:

146 | P a g e
Out put wave forms: High Pass RC Circuit

147 | P a g e
THEORITICAL CALCULATIONS:
High pass circuit:

% tilt = (T/2 RC) X100

Low pass circuit:

Rise time = tr = 2.2 RC

RESULT:
Linear wave shaping using RC high pass and Low pass circuits is studied.

VIVA-QUESTIONS:

1. What is a linear network? What is linear wave shaping?

Ans: A linear network is a network made up of linear elements only.The principle of superposi-
tion and the principle of homogeneity hold good for linear networks.

Linear wave shaping: it is the process whereby the form of non sinusoidal signal is altered by
transmission through a linear network.

2. Define Time constant. What is its formula?

Ans: The time constant of a circuit is defined as the time taken but the output to rise to 63.2% of
the amplitude of the input step T = RC.

3. Define %Tilt and Rise Time. Write the expressions for the same.

Ans: %Tilt: %Tilt is defined as decay in the amplitude of the outut voltage wave due to the inut
voltage maintaining constant level.

%Tilt = V1 –V11/(V/2) ×100

Rise Time: The rise time t is defined as the time taken by the output voltage waveform of a
low pass circuit excited by a step input to the rise from 10% to 90% of its final value.

The rise time of the output of a low pass circuit excited by a step input is given by

t = 2.2RC = 0.35/ f2 = 0.35 / BW

4. When High pass RC circuit is used as Differentiator? What is the formula for the output, when
operated as differentiator?

148 | P a g e
Ans: The high pass RC circuit acts as a differentiator provided the RC time constant of the cir-
cuit is very small in comparison with the time required for the input signals to make an apprecia-
ble change.

Vo (t) = RC dvi(t) / dt

5. When Low pass RC circuit is used as Integrator? What is the formula for the output, when the
circuit is operated as Integrator?

Ans: If the time constant of an RC low pass circuit is very large in comparison with the time re-
quired for the input signal to make an appreciable change, the circuit acts as an integrator.

Vo (t) = t2 / 2RC

6. What is the Difference between Low pass and High pass RC circuits.

Ans: Low Pass: A Low pass circuit is a circuit which transmits only low frequency signals and
attenuates or stops high frequency signals.

High Pass: A High pass circuit is a circuit which transmits only high frequency signals and at-
tenuates or stops low frequency signals.

7. A Capacitor blocks __ signal and passes __ signal. The voltage across the ___ will not change
suddenly.

Ans: A Capacitor blocks DC signal and passes AC signal. The voltage across the capacitor will
not change suddenly.

8. Explain 3 dB values for a LP and HP circuit.

Ans:

High Pass

Low Pass

9. A differentiator converts a square wave into what form? An integrator converts a square wave
into what form?

Ans: A differentiator converts a square wave into spikes waveform An integrator converts a
square wave into triangle waveform.

149 | P a g e
10. What are the formulae for charging a capacitor from an initial voltage of Vi to a final voltage
of Vo.

Ans: Vo = Vf + (Vi - Vf) e-T/RC

11. Instead of using RC components for a low pass or high pass, how the circuit changes , if we
want to use RL components? What are the values for the Time constant for RL circuits?

Ans: T = L/R

12. When a capacitor in a low pass circuit charges to 99.3 % ( treated as fully charged) for a step
input to a Low pass filter?

Ans: V0 = Vi

13. What is a peaking circuit?

Ans: The process of converting pulse into pips by means of a circuit of very short time constant
is called peaking.

14. What is a ringing circuit?

Ans: A ringing circuit is a circuit which can proved as nearly and un-damped oscillations as pos-
sible.

15. Why resistive attenuators are to be compensated?

Ans: A resistive alternator needs to be compensated in order to reduce or eliminate the rise time
of the output waveform.

Design Problems:

1. Design RC Differentiator circuit for frequency of 2kHz.


2. Design RC high circuit for a square wave input signal of frequency 2.5KHz for
i. RC = 10T
ii. RC = T
iii. RC = T/10
3. Design low pass circuit for a square wave signal of 3KHz for

i. RC = 5T
ii. RC = T
iii. RC = T/5
1. Verify the output of circuits given in Fig1.1 and Fig 1.2 for input square wave of fre-
quencies 10KHz and 500Hz.
2. Verify the RC high pass circuit output for sinusoidal input.

150 | P a g e
2. NON LINEAR WAVE SHAPING CLIPPER CIRCUITS

AIM: To study the diode clipper circuit using Diodes.

APPARATUS:
1. Bread Board
2. CRO Probes
3. CRO
4. Capacitor- 0.1μf
5. Regulated power supply
6. IN 4007 diode-1No.
7. Connecting wires.
8. Function Generator.

Circuit diagrams:
Input Signal

Negative clipper with zero reference (Series clipper):

Transfer characteristics:

151 | P a g e
Positive clipper with zero reference (Series clipper):

Transfer characteristics:

152 | P a g e
Negative clipper with zero reference (Shunt clipper):

Transfer characteristics:

Positive clipper with zero reference (Shunt clipper):

153 | P a g e
Transfer characteristics:

Positive clipper with positive reference (Series clipper):

154 | P a g e
Transfer characteristics:

Positive clipper with positive reference (Shunt clipper):

Transfer characteristics:

155 | P a g e
Negative clipper with positive reference (Series clipper):

Transfer characteristics:

Clipping at two independent levels :

156 | P a g e
Transfer characteristics:

157 | P a g e
THEORY:
Clipping circuits are commonly realized with diodes and resistor and do not contain any energy
storing components. The function performed by the clipping circuits essentially either limiting or
slicing. These circuits also employ devices such as diodes, Zener diodes, and transistors along
with resistors. Amplitude selectors and Amplitude limiters are the other names of the clipping
circuits

PROCEDURE:
1. Connect the circuits as per the circuit diagram
2. Connect the CRO Ch-I to input and Ch-2II to output of the circuit.
3. Adjust the input sine wave amplitude to 5V P-P.
4. Connect the D.C.battery wherever necessary.
5. Observe the wave form in the CRO channel II and not the waveform.

RESULT: Diode clipper circuit using ordinary and Zener Diode are studied and observed the
waveforms.

VIVA-QUESTIONS:

1. Define non linear wave shaping? What are the non-linear components?

Ans: The circuits for which the outputs are non-sinusoidal for sinusoidal inputs are called non-
linear wave shaping.

Example: clipping circuits and clamping circuits.

2. Define clipping circuit? What are the other names for clippers?

Ans: A clipping circuit is a circuit which removes the undesired part of the waveform and trans-
mits only the desired part of the signal which is above or below some particular reference level.
The other names for clippers are voltage (or current), limiters, amplitude, selectors or slicers.

3. Write the piecewise linear characteristics of a diode?

Ans: The piecewise linear approximation of a semi conductor diode the break down is at V
which is called offset or threshold voltage the diode behaves like an open circuit if v < V . The
characteristics show a constant incremental resistance r = dv / di if v > V .

4. What are the different types of clippers?

Ans: The different types of clippers are


1. Diode Clippers
2. Shunt Clippers

158 | P a g e
3. Series Clippers
4. Series And Shunt Noise Clippers
5. Transistor Clippers
6. Emitter Coupled Clippers

5. Which kind of a clipper is called a slicer circuit?

Ans: Two level clipper [It clips both positive and negative peaks]

6. What are the applications of Clipper Circuits?

Ans: Clipping circuits may be used to convert sine waves into square waves. They may also be
used to remove unwanted noise signals

7. What is the figure of merit for diodes used in clipping circuits?

Ans: The ratio of Rr / Rf is a figure of merit for diodes using in clipping circuit .

8. What is the influence of the practical diode compared to the ideal diode, in the above circuits?

Ans: In ideal diode current flows freely through the device , when forward bias having no
ressistance . a practical diode offers some in resistance to current flow when it is forward bias an

9. Instead of sinusoidal wave form as input, if we give other wave forms like triangular or
square, then how the clipping action is performed?

Ans: Clipping action is same for any give input.

10. What is Vγ for Ge diode and Vγ for Si diode?

Ans: V for Ge diode is 0.3V and V for Si diode is 0.7V.

159 | P a g e
3. NON LINEAR WAVE SHAPING CLAMPER

AIM: To study the Clamper circuits.

APPARATUS:
1. Bread Board
2. Patch cards
3. CRO Probes
4. CRO
5. Resistor- 1KΩ-1No.
6. Regulated power supply
7. IN 4007 diode-1No.
8. BZX6V2 diode- 2 No.
9. Connecting wires.
10. Function Generator.

CIRCUIT DIAGRAM:

Input Signal

Fig.3.1 Negative clamping with zero reference voltage

Fig.3.2 positive clamping with zero reference voltage

160 | P a g e
Fig.3.3 Negative clamping with Negative reference voltage

Fig.3.4 positive clamping positive reference voltage

Fig.3.5 Negative clamping with Positive reference voltage

Fig.3.6 Positive clamping with Negative reference voltage

THEORY:
161 | P a g e
Clamping circuits do not make any effort to change the wave shape of any signal. Their
main concern is to introduce a dc shift into a waveform by altering its dc component. In RC
coupling and capacitive coupling, the blocking capacitor does not allow the dc component of the
applied signal to pass through it. Since all the sinusoidal components pass through the blocking
capacitor, the wave shape of the signal remains the same after transmission while its dc level is
brought down to zero. Clamping circuits are essentially used to restore this lost dc component.

The process where sinusoidal signals are going to be altered by transmitting through a non-lin-
ear network is called non-linear wave shaping. Non-linear elements (like diodes) in combination
with resistors and capacitors can function as clamping circuit.

Clamping circuits add a DC level to an AC signal. A clamper is also referred to as DC restorer or


DC re-inserter. The Clampers clamp the given waveform either above or below the reference
level, which are known as positive or negative clampers respectively.

Clamping circuits are classified as two types.

i. Negative Clampers
ii. Positive Clampers

162 | P a g e
PROCEDURE:
1. Connect the circuits as per the circuit diagram
2. Connect the CRO Ch-I to input and Ch-2II to output of the circuit.
3. Adjust the input sine wave amplitude to 5V P-P.
4. For Zener diode clipper, increase the amplitude of the input Wave form to 15V P-P
5. Observe the wave form in the CRO, with and without connecting the D.C.battery (i.e. biasing)
and note the wave form from Ch-II of CRO.

RESULT: The clamping circuits are studied.

VIVA-QUESTIONS:
1. What are the applications of clamping circuits?

Ans: Clapping circuits are used to fix the positive or negative extremity of a periodic waveform
at some constant reference level.

3. Explain the Principle of operation of Clampers.

Ans: When a signal is transmitted to a capacitive coupling network (RC high pass circuit), it
losses its dc component, and a clamping circuit may be used to introduce a dc component by fix-
ing the positive or negative extremity of that waveform to some reference level.

4. What is clamping circuit theorem.

Ans: The clamping circuit theorem state that for any input waveform under steady state condi-
tions, the ratio of area Af under the output voltage curve in the forward direction to that in the re-
verse direction Ar is equal to the ratio Rf / R, i.e., Af / Ar = Rf / R

5. What is the function of capacitor in clamper circuit?

Ans: The function of capacitor in clamper circuit is that it will add dc signal to the ac signal.

6. What are the effects of diode characteristics on the output of the Clamper?

Ans: When temperature varies reverse saturation current increases and cut in voltage decreases
which effects clamping circuit.

7. If we interchange the diode and the capacitor in fig 1 above, how the circuit behaves?

Ans: If capacitor connected in series to allow AC ,for DC allowing circuits capacitors connected
in parallel.

163 | P a g e
8. Calculate the power dissipation in the Resistor for any one of the above circuits?

Ans: P = I2R P = 1 Watt

9. What is the difference between a clipper and a clamper?

Ans: Clipper clips OFF the unwanted portion of the input waveform, and the clamper simply
clams the maximum positive or negative peak to a desired level.

10. What are the other names for clampers?

Ans: The other names for clampers are: Dc restorer and Dc reinserter

164 | P a g e
4. LOGIC GATES

AIM: To study and verify the truth table of AND, NOR, OR, NOT, NAND Gate (Discrete
version)

APPARATUS:
1. Bread Board
2. IC trainer Kit Patch cards
3. Diodes IN4007
4. Resistors (1kΩ, 100Ω, 4.7kΩ, 330Ω, 10KΩ)
5. Capacitors (0.1μf)
4. Connecting wires.

CIRCUIT DIAGRAM:

165 | P a g e
166 | P a g e
167 | P a g e
168 | P a g e
169 | P a g e
THEORY:
In digital electronics, the binary digits 0 and 1 are represented by voltages LOW and HIGH.
This branch of electronics is mathematically supported by Boolean algebra. The basic logic
operations in this algebra are NOT, AND & OR. These logic operators are binary as they work
on two operands to specify the output.

PROCEDURE:
1. Connect the circuit as per the circuit diagram.
2. Give different combinations of inputs and observe the output.
3. Construct the truth tables for each circuit considering the input and output levels of the circuit.

RESULT: The truth tables of AND, OR, NOT, NOR, NAND gates are verified.

VIVA-QUESTIONS:
1) What is logic gate and by using which devices we can realize the logic gates?
2) What is combination circuit? What is truth table?
3) Realize the NAND gate using AND,OR and NOT gates?
4) Realize logic gates using transistors?
5) What is IC and give some IC’s name for logic gates?

170 | P a g e
5. ASTABLE MULTIVIBRATOR

AIM: To study an Astable Multivibrator to generate a square wave using Astable multivibrator.

APPARATUS:
1. D.C. Regulated power supply
2. Dual Trace CRO
3. Resistors
4. Capacitors/Decade capacitance box.
5. Bread Board.

CIRCUIT DIAGRAM:

THEORY:

Transistor multivibrators make use of all the three regions of operations: cut-off, saturation, as
well as the active region. The working principle of transistor multivibrators involves the cutoff
and saturation regions. Astable multivibrator can also be treated as a relaxation oscillator. The
astable multivibrator has two quasi-stable states. This circuit is commonly used for the
generation of a rectangular waveform.

171 | P a g e
PROCEDURE:
1. Connect the circuit diagram according to the given diagram.
2. Apply D.C.power supply to the circuit.
3. Observe the base and collector voltages of Q1 and Q2 on CRO.
4. Measure the time period of the output waveforms and compare with theoretical
Values.
5. Repast the above steps with different capacitance values from decade capacitance.

Expected Wave forms:

172 | P a g e
THEORITICAL CALCULATIONS:

T=0.69 (RB1C1+RB2C2)

If RB1C1=RB2 = R & C1 = C2=C


T =1.38RC

RESULT:
The working of Astable multivibrator is studied and Observed the practical values and
waveforms.

VIVA-QUESTIONS:

1) What is multivibrator? Give some names of the multivibrators?


2) What are the applications of astable multivibrator?
3) Which multivibrator is used as a voltage to frequency converter?
4) In which multivibrator we have to apply triggering pulses to change the states
of transistor?
5) How many stable states are there in astable multivibrator?

173 | P a g e
6. MONOSTABLE MULTIVIBRATOR

AIM: To study Monostable Multivibrator to generate a square wave

APPARATUS:
1. D.C. Regulated power supply
2. Dual Trace CRO
3. Resistors
4. Capacitors/Decade capacitance box.
5. Bread Board.

CIRCUIT DIAGRAM:

174 | P a g e
THEORY:

PROCEDURE:
1. Connect the circuit diagram according to the given diagram.
2. Apply D.C.power supply to the circuit.
3. Observe the base and collector voltages of Q1 and Q2 on CRO.
4. Measure the time period of the output waveforms and compare with theoretical
Values.
5. Repeat the above steps with different capacitance values from decade capacitance.

Expected Wave Forms:

175 | P a g e
THEORITICAL CALCULATIONS:

RESULT: The working of Mono stable multivibrator is studied and Observed the practical
values and waveforms.

176 | P a g e
7. BI STABLE MULTIVIBRATOR

AIM: To study Bistable Multivibrator to generate a square wave

APPARATUS:
1. D.C. Regulated power supply
2. Dual Trace CRO
3. Resistors
4. Capacitors/Decade capacitance box.
5. Bread Board.

CIRCUIT DIAGRAM:

THEORY:

The Bistable Multivibrator is another type of two state device similar to the monostable
multivibrator. Bistable Multivibrators have TWO stable states (hence the name: "Bi" meaning
two) and maintain a given output state indefinitely unless an external trigger is applied. The
bistable multivibrator can be switched over from one stable state to the other by the application
of an external trigger pulse thus, it requires two external trigger pulses before it returns back to
its original state. As bistable multivibrators have two stable states they are more commonly
known as Latches and Flip-flops for use in sequential type circuits.

177 | P a g e
PROCEDURE:

1. Connect the circuit diagram according to the given diagram.


2. Apply D.C.power supply to the circuit.
3.Verify the stable states by measuring the voltages at two collectors by using multimeter .
4. Observe the base and collector voltages of Q1 and Q2 on CRO.
5. Measure the time period of the output waveforms and compare with theoretical
Values.
6. Repeat the above steps with different capacitance values from decade capacitance

RESULT: The working of Bistable multivibrator is studied and Observed the practical values
and waveforms.

VIVA-QUESTIONS:

1) What is multivibrator? Give some names of the multivibrators?


2) What are the applications of bistable multivibrator?
3) Which multivibrator is used as a voltage to frequency converter?
4) Is triggering required for a bistable multivibrator?
5) How many stable states are there in bistable multivibrator?

178 | P a g e
8. UJT RELAXATION OSCILLATOR

AIM: To study the relaxation oscillator using uni junction transistor.

APPARATUS:

1. Bread Board
2. Patch cords
3. CRO
4. CRO Probes
5. Components, UJT

THEORY:

Uni junction transistor has only one junction. It is used to generate saw tooth wave forms i.e.
time base signals. UJT is used as a relaxation oscillator. A relaxation oscillator is one which
gives saw tooth waveforms without giving any input signal.

CIRCUIT DIAGRAM:

179 | P a g e
EXPECTED WAVEFORM:

PROCEDURE:
1. Connect the circuit as per the diagram
2. Switch on the supply and the capacitor is taken across the capacitor Ce.
3. Observe the output waveform and calculate the time period.

RESULT:
The UJT relaxation oscillator is studied.

VIVA-QUESTIONS:
1) What is an oscillator?
2) What is relaxation oscillator?
3) What are the different methods are used to generate time base waveforms?
4) What are the applications of relaxation oscillator?
5) What are differences between diode and UJT?

180 | P a g e
CYCLE -II

181 | P a g e
Experiment No. 1

COMMON EMITTER AMPLIFIER

AIM: To measure the gain, bandwidth, input resistance, output resistance of CE amplifier by
using TINA software

APPARATUS:

TINA software.

CIRCUIT DIAGRAM:

COMMOM EMITTER A MPLIFIER

V1 12V
R1 3 .3 k
R3 3 3k

C1 10uF VF1

R2 1k C1 10uF
T2 BC107A
R1 4 .7 k

C1 1 00 uF
+

R1 4 70

VG1

182 | P a g e
EXPECTED GRAPH :

183 | P a g e
184 | P a g e
PROCEDURE ( FREQUENCY RESPONSE ):

1. Connect the circuit as shown in fig.


2. Go to AC analysis and get the AC transfer characteristics as shown in Expected
graph.
3. By using scales we can calculate the bandwidth and gain.
4. By using the frequency response note down the readings.
5. Calculate the lower cut off frequency and upper cut off frequency theoretically.
.
CALCULATIONS:

1. Voltage gain at mid frequencies (Amid) = Maximum value of Av.


2. Voltage gain at lower & upper cut off frequencies = Avmid.-3
3. Lower cut off frequency = f1
4. Upper cut off frequency = f2
5. 3-dB band width of the amplifier = f2- f1

QUESTIONS:
1. Does phase reversal exist in CE amplifier?
2. Does phase reversal effect amplification?
3. What is signification of operating point?
4. Mention the influence of coupling capacitor CC on low frequency response.
5. Define & .
6. Calculate with the help of observed in this experiment?
7. In which transistor configuration current gain is less than unity.

Experiment No. 2

185 | P a g e
COMMON SOURCE AMPLIFIER

AIM: To measure the gain, bandwidth, input resistance, output resistance of CS amplifier by us-
ing TINA software.

APPARATUS:

TINA software.

CIRCUIT DIAGRAM:

COMMOM SOURCE AMPLIFIER

V1 12V

R1 4 .7 k
C1 10uF VF1

R2 1k C1 10uF

C1 1 00 uF
T1 BF245A
R1 2 .2 M
+

R1 4 70

VG1

EXPECTED GRAPH :

186 | P a g e
PROCEDURE( FREQUENCY RESPONSE ):

1. Connect the circuit as shown in fig.


2. Go to AC analysis and get the AC transfer characteristics as shown in Expected
graph.
3. By using scales we can calculate the bandwidth and gain.
4. By using the frequency response note down the readings.
.

CALCULATIONS:

1. Voltage gain at mid frequencies (Amid) = Maximum value of Av.


2. Voltage gain at lower & upper cut off frequencies = Avmid.-3
3. Lower cut off frequency = f1
4. Upper cut off frequency = f2
5. 3-dB band width of the amplifier = f2- f1

QUESTIONS:

1. Does phase reversal exist in CS amplifier?


2. Why the gain is increasing in low frequency, constant in mid frequencies and decreasing
in high frequencies?
3. Why cut off frequencies are also called as half power points?
4. Mention the influence of Bypass capacitor Ce on low frequency response.

187 | P a g e
Experiment No.3
TWO STAGE RC COUPLED AMPLIFIER

AIM: To meaure and plot gain and bandwidth (frequency response) for two stage RC coupled
amplifier by using SPICE software.

APPARATUS :

TINA PRO Software

CIRCUIT DIAGRAM:

Two Stage RC coupled Amplifier


V1 12
R1 3 3k

R1 3 .3 k

R1 3 3k

R1 3 .3 k
C110u VF1
VF2
R21k C110u
C110u
T1 BC107
T2 BC107
R1 4 .7 k

R1 4 .7 k
+

C1 1 00 u

VG1
R1 4 70

C1 1 00 u

R3 1 0k
R1 4 70

THEORY:
The output from single stage amplifier is usually insufficient to drive to drive an output
device. To achieve the extra gain the output of each amplifier stage is coupled in some way to
the input of next stage. A transistor circuit contains more than one stages known as multistage
amplifier.The coupling of one stage to another is done with help of some coupling device. If is
coupled with R and C then the amplifier(cascade) is called
R-C coupled amplifier. It can be Direct coupled or transformer coupled.

GAIN:- The gain G is the ratio of output to input. The gain of the multistage amplifier is equal to
the product of gains of individual stages.
i.e G=G1 x G2 x G3.

188 | P a g e
(EXPECTED GRAPH):-

PROCEDURE( FREQUENCY RESPONSE ):

1. Connect the circuit as shown in fig.


2. Go to AC analysis and get the AC transfer characteristics for both stages as shown in Ex-
pected graph .
3. By using scales we can calculate the bandwidth and gain at both stages.
4. By using the frequency response note down the readings.
5. Calculate Gain and Bandwidth at both the stages from frequency response.
6. calculate the LCF due to all external capacitors.
.

CALCULATIONS:

Single stage:

1. Voltage gain at mid frequencies (Amid)=Max. Value of Av.(dB)


2. Voltage gain at lower & upper cutoff frequencies = Avmid -3
3. Lower cutoff frequency = fL1...
4. Upper cutoff frequency = fH1.
5. 3-dB band width of the amplifier = fH1 - fL1..

189 | P a g e
Two Stage:

1. Voltage gain at mid frequencies (Amid)=Max. Value of Av.


2. Voltage gain at lower & upper cutoff frequencies = Avmid.-3
3. Lower cutoff frequency = fL2...
4. Upper cutoff frequency = fH2.
5. 3-dB band width of the amplifier = fH2 – fL2..

fL2>fL!; fH2<fH1; Bandwidth 2<Band width 1

QUESTIONS:

1. Is fH* for two stages greater or smaller than fH for a single stage? Explain
2. Given an approximate expression relating fH* and 3-dB frequencies of n
non-identical stages?
3. Three identical cascaded stages have an overall upper – 3dB frequency of 20 KHZ and a
lower 3-dB frequency of 20HZ. What are fL and fH of each stage? Assuming non-inter-
acting stages?
4. R-C coupled amplifier has a very ______ frequency response curve.
5. Direct coupling is used for amplifying _______________________.

190 | P a g e
Experiment No:4

DARLINGTON PAIR (CC+CC)

AIM: To calculate the input resistance of Darlington pair and comparing with the theoretical
values.

APPARATUS:

SPICE Software

CIRCUIT DIAGRAM:

Darlington Pair V1 12V


R2 1 00 M

R6 1 00 M

T1 BC107
R11k C110uF
VF2
R3 3 3M

C210uF
T2 BC107
C310uF
R7 3 3M

VF1
+

VG1
R4 5 00

R5 1 0k

PROCEDURE:

1. Connect the circuit diagram as shown in Fig.


2. Calculate the input resistance by the following for both stages
And compare with the theoretical values

191 | P a g e
Observation:

Sl.No Vs Vi Ii= Vs- Vi / Rs Ri=Vi / Ii Ris = Vs/Ii

Result:

192 | P a g e
Experiment No.5

VOLTAGE SHUNT FEED BACK AMPLIFIER

AIM: To measure the gain and bandwidth (frequency response) of voltage shunt feedback amplifier
with and without feedback by using TINA software.

APPARATUS:

TINA Software

CIRCUIT BIAGRAM;

EXPECTED GRAPH :

193 | P a g e
PROCEDURE:

1. Arrange the circuit as shown in the circuit diagram.


2. Apply ac signal to the input of the amplifier from the signal generator.
3. Keep the input signal voltage 1mV and frequency at 10kHz.
4. Go to AC analysis and get the AC transfer characteristics for both circuit diagram
as shown in Expected graph .
5. By using scales we can calculate the bandwidth and gain at both with and without
feedback.
6. By using the frequency response note down the readings.
7. Calculate Gain and Bandwidth at both the stages from frequency response.
8. Repeat the above steps by removing the feed back resistance and note down the
with out feedback readings.

CALCULATIONS:

With out feed back:

1. Voltage gain at mid frequencies (Amid)=Max. Value of Av.(dB)


2. Voltage gain at lower & upper cutoff frequencies = Avmid -3
3. Lower cutoff frequency = fL1...

194 | P a g e
4. Upper cutoff frequency = fH1.
5. 3-dB band width of the amplifier = fH1 - fL1..

With feed back:

1. Voltage gain at mid frequencies (Amid)=Max. Value of Av.


2. Voltage gain at lower & upper cutoff frequencies = Avmid.-3
3. Lower cutoff frequency = fL2...
4. Upper cutoff frequency = fH2.
5. 3-dB band width of the amplifier = fH2 – fL2..

fL2<fL!; fH2>fH1; Bandwidth 2>Band width 1

195 | P a g e
Experiment No.: 6

RC PHASE SHIFT OSCILLATOR

AIM: To study the performance of RC phase shift oscillator by using SPICE

APPARATUS:

TINA PRO software.

CIRCUIT DIAGRAM

EXPECTED GRAPH

196 | P a g e
PROCEDURE:

1.Connect the RC circuit as shown in the figure


2.Simulate the circuit and observe the waveform in the CRO.
3.Measure the frequency of the wave form generated and compare with the theoretical value.
. .
CALCULATIONS:

f0 = for : C = 0.01 F
R = 2.7 K

197 | P a g e
Experiment No: 7

CLASS –A POWER AMPLIFIER

AIM: To determine the efficiency of Class A power amplifier using TINA software.

APPARATUS:

TINA PRO software

INTRODUCTION:

An amplifier is a circuit meant to amplify a signal with a minimum of distortion, so as to make it


more useful. In an amplifier system, there are more than one stages. The initial and middle stages
work as voltage amplifiers and handle small signals. However the final stage (also called the
output stage) is required to drive a load (such as loud speaker) which handles sufficient power:
For obtaining sufficient power, it requires a large swing of voltage or current.

In almost all electronic systems, the last stage has to be a power amplifier. For example, in a
public-address system, it is the power amplifier that drives the loud speakers. A power amplifier
is meant to boost the power level of the input signal. This amplifier can feed a large amount of
power to the load. To obtain large power at the output of the power amplifier, its input- signal
voltage must be large. That is why, in an electronic system, a voltage amplifier invariably
proceeds the power amplifier. Therefore, the power amplifiers are called large-signal amplifiers.

Actually the power amplifier does not amplify the power. The power amplifier takes power from
the dc power supply connected to the output circuit and converts it into useful ac signal power.
This power is fed to the load (e.g. loud speaker).

The type of ac power developed at the output of the power amplifier is controlled by the input
signal. Thus, a power amplifier is also called as a dc- to-ac power converter, whose action is
controlled by the input signal.

Power amplifiers are divided into many types depending their conduction time over a cycle.
They are

1. Class-A Power Amplifier.


2. Class-B Power Amplifier.
3. Class-AB Power Amplifier.
4. Class-C Power Amplifier.

CIRCUIT DIAGRAM:

198 | P a g e
EXPECTED GRAPH:-

199 | P a g e
THEORY:

In Class-A operation, the transistor stays in the active region through- out the ac cycle. In this
operation, the transistor conducts for full 360° of the input cycle. For making conduction
possible through 360°, that is, through both positive and negative half-cycles, it is necessary that
the transistor should be biased for swing in the negative half-cycle also. Such biasing causes
continuous drain of current from the power-supply or battery, even if the input signal is absent. '

The output signal varies for a full (3600) cycle of the input. In this case, the Q-point is biased al -
most at the half of the DC load line. A Class-A amplifier, with DC bias at one half of the supply
voltage, uses a good amount of power to maintain bias, even with no signal applied. This results
in very poor efficiency. When very little AC power is delivered to the load a large amount of
power is dissipated in the collector resistance (Rc). This results in a maxi- mum efficiency of
only 25%. By replacing the collector resistance (Rc) by a large inductor (also called a choke), the
maximum efficiency can be increased to 50%.

PROCEDURE:

1. Switch ON Class- A Power amplifier.


2. Set V s (say 150 to 200mV), at 10KHz using signal generator.
3. Connect milli Ammeter to the ammeter terminals
4. Increase the input voltage till there is no distortion in the output voltage. The maximum
input voltage where there is no distortion in the output voltage at that point note down the
milli ammeter reading Idc and measure the output voltage Vo.
5. Calculate Pdc, Pac and efficiency using following formulae.
i. Pdc = Vcc X Idc. Pac = Vo2 /8 RL
6. Simulate the above class-A Power Amplifier using SPICE software and compare the
values.

200 | P a g e
Experiment No: 8

CLASS-B COMPLEMENTARY SYMMETRY AMPLIFIER

AIM:

To study Class-B (complementary Symmetry) power amplifier and to determine its efficiency
and simulate the same using spice / TINAPRO Software.

APPARATUS:

TINA PRO Software

INTRODUCTION:

An amplifier is a circuit meant to amplify a signal with a minimum of distortion, so as to make it


more useful. In an' amplifier system, there are more than one stages. The initial and middle
stages work as voltage amplifiers and handle small signals. However the final stage (also called
the output stage) is required to drive a load (such as loud speaker) which handles sufficient
power. For obtaining sufficient power, it requires a large swing of voltage or current.

In almost all electronic systems, the last stage has to be a power amplifier. For example, in a
public-address system, it is the power amplifier that drives the loud speakers. A power amplifier
is meant to boost the power level of the input signal. This amplifier can feed a large amount of
power to the load. To obtain large power at the output of the power amplifier, its input- signal
voltage must be large. That is why, in an electronic system, a voltage amplifier invariably
precedes the power amplifier. Therefore, the power amplifiers are called large-signal amplifiers.

Actually the power amplifier does not amplify the power. The power amplifier takes power from
the dc power supply connected to the output circuit and converts it into useful ac signal power.
This power is fed to the load (e.g. loud speaker).

The type of ac power developed at the output of the power amplifier is controlled by the input
signal. Thus, a power amplifier is also called as a dc- to-ac power converter, whose action is
controlled by the input signal.

Power amplifiers are divided into many types depending their conduction time over a cycle.
They are

1. Class-A Power Amplifier.


2. Class-B Power Amplifier.
3. Class-AB Power Amplifier.
4. Class-C Power Amplifier.

201 | P a g e
CIRCUIT DIAGRAM:

EXPECTED GRAPH :

202 | P a g e
THEORY:

The circuit of class-B push-pull amplifier uses two transformers, one at the input and cone at the
output. However, transformers are costly and add to the weight of the amplifier. We can elimi-
nate this drawback by using class- B complementary -symmetry power amplifier. This amplifier
does not have any transformer.

This circuit uses a pair of transistors having complementary symmetry,; that is, one transistor is
PNP and the other is NPN. The complementary- symmetry circuit requires two power supplies,
since each transistor must be biased suitably. The resistors act as voltage dividers across power
supplies to forward bias the emitter-base junction of both transistors. The transistors are operated
in Class-B. That is the bias is adjusted such that the operating point corresponds to the cut-off
points. Hence, with no signal input, both transistors are cut-off and no collector current flows.

The signal applied at the input goes to the base of both the transistors. Since the transistors are of
opposite type, they conduct in opposite half-cycles of the input. For example, during the positive
half-cycle of the input signal, the PNP transistor is reverse biased and does not conduct. The
NPN transistor, on the other hand is forward-biased and conducts. This results in a half-cycle of
output voltage across the load resistor. The other half-cycle of output across the load is provided
by the conduction of other transistor dur -ing the negative half-cycle of the input. Since the
collector current from each transistor flows through the load during alternative half-cycles of the
input signal, no centre tapped output transformer is required.
The two transistors-though of opposite type, must be matched. If there is an imbalance in the
characteristics of the two transistors, even harmonics will no longer be cancelled. This would
result in considerable distortion. In- creasing availability of complementary transistors is making
the use of class- B transformer-coupled stages obsolete. All modern power amplifier circuits are
transformer less aid use complementary transistors.

CIRCUIT DESCRIPTION:

The principle of complementary-symmetry is assembling of push-pull class-B amplifier without


requiring centre-tapped transformer at the input and output stages of transistor. The function of
input transformer present in push-pull amplifier is, providing two input signals 1800 out of
phase, which makes only one transistor to conduct at a time. However in this circuit, the same
signal voltage is applied simultaneously to the two transistors; one of them a PNP and another
NPN transistor. On the positive half cycle of V s' NPN transistor is forward biased and therefore
conducts, but another transistor, being PN~ is reverse biased and therefore does not conduct. The
opposite of this action is takes place when the signal V s is in the negative half cycle. The total
current flowing through RL is in both half -cycles.

ADVANTAGES:

1. This circuit does not require transformer. This saves on weight and cost.
2. The efficiency of Class-B(78.5%) is higher than class -A (50%).
3. Since the efficiency is higher, it is possible to obtain greater power out- put.

203 | P a g e
4. Since the power loss is negligible at no signal condition, it is well suited for battery or solar-
cell operation.

DISADVANTAGES:

1. It is difficult to get both transistors (NPN & PNP) consists of similar characteristics.
2. Both positive and negative supply voltages are required.
3. Cross-over distortion is present.
4. Harmonic distortion is high compared to Class-A.

PROCEDURE:

1. Connect the circuit as shown in fig.


2. Give the input from function generator to the input (Vs) terminals of the circuit (say 2V)
3. Observe the output in the CRO
4. Increase the input voltage amplitude till there is no distortion in the output. At the point
measure the output voltage Vo.
5. Calculate the efficiency by using following formula
 =  Vo/4 Vcc

6. Simulate the above circuit using TINA and compare the both Hardware and simulation
results.

204 | P a g e
Experiment No.9

SERIES AND SHUNT VOLAGE REGULATOR

AIM: To study the Load and Line regulation characteristics of series and shunt voltage
Regulatro

APPARATUS:

TINA software.

THEORY:

A voltage regulator is designed to automatically ‘regulate’ voltage level. It basically steps down
the input voltage to the desired level and keeps that in that same level during the supply. This
makes sure that even when a load is applied the voltage doesn’t drop.

Thus, a voltage regulator is used for two reasons:-

1. To regulate or vary the output voltage of the circuit.


2. To keep the output voltage constant at the desired value in-spite of variations in the sup-
ply voltage or in the load current
.
Voltage regulators find their applications in computers, alternators, power generator plants where
the circuit is used to control the output of the plant.
Types of Regulators
Regulators can be classified into different categories, depending upon their working and type of
connection.
Depending upon the type of regulation, the regulators are mainly divided into two types
namely, line and load regulators.
 Line Regulator − The regulator which regulates the output voltage to be constant, in
spite of input line variations, it is called as Line regulator.
 Load Regulator − The regulator which regulates the output voltage to be constant, in
spite of the variations in load at the output, it is called as Load regulator.
Depending upon the type of connection, there are two type of voltage regulators. They are

 Series voltage regulator


 Shunt voltage regulator

205 | P a g e
Shunt Voltage Regulator

Block diagram

Circuit diagram

206 | P a g e
The voltage drop across series resistance depends upon the current supplied to the load RL. The
output voltage is equal to the sum of zener voltage (VZ) and transistor base-emitter voltage
(VBE)
Vout = VZ + VBE
If the load resistance decreases, the current through base of transistor decreases. As a result, less
collector current is shunted. Therefore, the load current becomes larger, thereby maintaining the
regulated voltage across the load. Reverse happens should the load resistance increase.

Drawbacks:
 A large portion of the total current through RS flows through transistor rather than to the
load.
 There is considerable power loss in RS.
 There are problems of overvoltage protection in this circuit.
 For these reasons, a series voltage regulator is preferred over the shunt voltage regulator.

Expected Graphs:

207 | P a g e
Procedure:

Load Regulation:

 Connect the circuit as shown in fig.


 Keep the input voltage constant. Vin =20V
 Draw the DC characteristic by Vary the load Resistance from (1-100K )
 Calculate the percentage of Regulation.

 Where:
VNL = the no-load output voltage
VFL = the full-load output voltage

Line Reulation;

1. Connect the circuit as shown in fig.


2. Keep the Load Resistance =10Kohm
3. Draw the DC characteristic by Vary the inpu voltage 0-20V

Series Voltage Regulator

Block diagram

208 | P a g e
Circuit diagram

You can see in the figure that the load current is passing through the series transistor Q1 & that’s
the reason why we call the circuit a series voltage regulator. You can see that we feed the unreg -
ulated d.c. supply through the input terminals so that we can get the regulated across the load.
Here, the zener diode is providing the reference voltage.
Operation of Transistor Series Voltage Regulator

The base voltage of transistor Q1 is held to a relatively constant voltage across the Zener diode.
For example, if 8V zener (i.e., VZ = 8V) is used, the base voltage of Q1 will remain approxi-
mately 8V. Hence , Vout = VZ – VBE

209 | P a g e
Case 1 : Output Voltage Decreases

Under this circumstance , the increased base-emitter voltage will cause transistor Q1 to conduct
more, thus increasing the output voltage. Hence, the output voltage will be maintained at a con-
stant level.

Case 2 : Output Voltage Increases

Under this circumstance , the decreased base-emitter voltage will cause Q1 to conduct less, thus

reducing the output voltage. Hence, the output voltage will be maintained at a constant level .

EXPECTED GRAPHS:

Procedure:

210 | P a g e
Load Regulation:

 Connect the circuit as shown in fig.


 Keep the input voltage constant. Vin =20V
 Draw the DC characteristic by Vary the load Resistance from (1-100K )
 Calculate the percentage of Regulation.

 Where:VNL = the no-load output voltage; VFL = the full-load output voltage

Line Reulation;
 Connect the circuit as shown in fig.
 Keep the Load Resistance =10Kohm
 Draw the DC characteristic by Vary the inpu voltage 0-20V

211 | P a g e

You might also like