Sei sulla pagina 1di 85

LABORATORY MANUAL

for

CS8383 OBJECT ORIENTED PROGRAMMING


LABORATORY
of

B.Tech. (INFORMATION TECHNOLOGY)


(Anna University Regulation 2017)
For the Batch (2018 to 2022)
Semester: III
ACADEMIC YEAR: 2019-2020

DEPARTMENT OF INFORMATION TECHNOLOGY


KCG COLLEGE OF TECHNOLOGY,

1
CHENNAI – 600097

Date of Release: Approved


by
(HOD)

Copy No: 01 Copy Holder:

CERTIFICATE

This is to certify that ------------------------------------------------------, roll

number/ register number ( ) of Third year

(FifthSemester) B.E–Electrical and Electronics Engineering has successfully

completed all the lab exercises in CS8383 – Object Oriented Programming

Laboratory for the academic year 2019-2020 in the Odd Semester.

2
Faculty In-Charge HoD

VISION OF THE COLLEGE


KCG College of Technology aspires to become a globally recognized centre of
excellence for science, technology & engineering education, committed to quality
teaching, learning, and research while ensuring for every student a unique educational
experience which will promote leadership, job creation, social commitment and service to
nation building

MISSION OF THE COLLEGE

⦁ Disseminate knowledge in a rigorous and intellectually stimulating environment

3
⦁ Facilitate socially responsive research, innovation and entrepreneurship

⦁ Foster holistic development and professional competency

⦁ Nurture the virtue of service and an ethical value system in the young minds

VISION OF THE DEPARTMENT


The Department of Electrical and Electronics Engineering aims to be a centre

of excellence recognized for high quality teaching, learning and research,

producing competent professionals to serve the nation.

MISSION OF THE DEPARTMENT

⦁ Impart quality technical education in Electrical and Electronics Engineering


domain
⦁ Nurture industrial collaboration in research and development activities
⦁ Maintain state-of-the-art facilities to provide opportunities for knowledge up-
gradation
⦁ Invoke the desire and ability of life-long learning in the students for a
successful career

PROGRAMME EDUCATIONAL OBJECTIVES:

4
On completion of the program, the students will achieve the following: 
Provide efficient solutions for real world problems using contemporary
PEO1
tools

PROGRAMME OUTCOMES AND PROGRAMME SPECIFIC OUTCOMES


After successful completion of B.E (Computer Science and Engineering) programme, the 
students will be able to:

PO1 Apply the knowledge of mathematics, science, engineering fundamentals, and 
an engineering specialization to the solution of complex engineering problems.
Identify, formulate, research literature, and analyze complex engineering 
PO2 problems reaching substantiated conclusions using first principles of 
mathematics , natural sciences and engineering  sciences.
Design solutions for complex engineering problems and design  system  
PO3 components or processes  that meet the specified needs with appropriate 
consideration for the public health and safety, and the 
cultural, societal, and environmental considerations.
Use research based knowledge and methods including 
PO4 design of experiments, analysis and interpretation of data, and  synthesis of 
the information to provide valid conclusions.
Create, select, and apply appropriate techniques, resources, and modern 
PO5 engineering and IT  tools including prediction and modelling to complex 
engineering activities with an understanding of the limitations.
Apply reasoning informed by the contextual knowledge to assess societal, 
PO6 health, safety, legal and cultural issues and the consequent responsibilities 
relevant to the professional  engineering practice.
Understand the impact of the professional engineering 
PO7 solutions in societal and environmentalcontexts, and demonstrate the knowl
edge of, and need for sustainable development.
PO8 Apply ethical principles and commit  to  professional ethics  and responsibilit
ies  and  norms of the engineering practice.
PO9 Function effectively  as  an individual, and as a member or leader in 
diverse teams, and in multidisciplinary settings.

5
Communicate effectively on complex engineering  activities with the 
engineering community and with 
PO10 society at  large, such  as, being able  to  comprehend  an 
write effective  reports and design documentation,take effective presentatio
ns give and receive clear instructions.
Demonstrate knowledge and understanding of 
PO11 engineering and management principles 
and apply these to one’s own work, as a member leader  in  a team, to manage
projects and in multidisciplinary environments
Recognize the need for, and  have the preparation and ability  to engage 
PO12 in independent and life‐long learning in the broadst context of technological 
change.

PSO Description of PSO

PSO 1 To analyze, design and develop computing solutions by applying foundational 
concepts of Computer Science and Engineering.

PSO 2 To apply software engineering principles and practices for developing quality 
software for scientific and business applications.

PSO 3 To adapt to emerging Information and Communication Technologies (ICT) to 
innovate ideas and solutions to existing/novel problems.

COURSE OUTCOMES
Upon completion of this course, the student will be able to:

CO No Description of the Course Outcome Blooms level

Develop and implement Java programs for simple applications that


CO1 K3
make use of classes, packages and interfaces

6
CO2 Develop and implement Java programs with array list K3

Develop and implement Java programs with exception handling and


CO3 K3
multithreading
Design applications using file processing
CO4 K3

CO5 Design applications using generic programming K3

CO6 Design applications using event handling K3

CS8383: OBJECT ORIENTED PROGRAMMING LABORATORY


Amendment Sheet

Doc Ref. Effective date Approved


Page No Details of the Revisions
(or Expt No.) of the revision by

7
CS8383 : OBJECT ORIENTED PROGRAMMING LABORATORY
Index
Ex
Name of the Experiment Page No Date Signature
No.

8
01 Generation of Electricity bill.

Currency converter, distance converter and time


02
converter using packages.

03 Generation pay slips for the employees

04 ADT Stack using array.

05 Illustration of string operations using Array List.

06 Illustration of Abstract Class

07 Implementation of user defined exception.

08 Illustration of File Handling

09 Illustration of Multi-Threading

10 Illustration of Generic Programming

11 Illustration of Event programming

12 Mini Project

Content Beyond Syllabus


Write a java program to implementation of stack
13 using list. Handle all exceptions.

14 Write a Java program to implement 2-D shapes

9
Ex. No. 1 PROGRAM TO GENERATE ELECTRICITY
BILL

Date :

1.0 Aim
To develop a Java application to generate Electricity bill.

Develop a Java application to generate Electricity bill. Create a class with the following
members: Consumer no., consumer name, previous month reading, current month
reading, type of EB connection(i.e domestic or commercial). Compute the bill amount
using the following tariff.
If the type of the EB connection is domestic, calculate the amount to be paid as follows:
First 100 units - Rs. 1 per unit
101-200 units - Rs. 2.50 per unit
201 -500 units - Rs. 4 per unit
> 501 units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be paid as
follows:
First 100 units - Rs. 2 per unit
101-200 units - Rs. 4.50 per unit
201 -500 units - Rs. 6 per unit
> 501 units - Rs. 7 per unit

2.0 Algorithm:

STEP 1: Import the Scanner.

10
STEP 2:Declare the class as public
STEP 3:Create a class with the members: Consumer no., consumer name, previous month
reading, current month reading, type of EB connection
STEP4: Add the void main function
STEP 5: Add system.out.println() function with the message to enter units consumed.
STEP 6:Declare input as Scanner.
STEP 7:Take the inputs and save it in variables.
STEP 8:Calculate bill and save it in variable.
STEP 9:Addsystem.out.println() function to print the bill.

3.0 Program:
import java.io.*;
import java.util.*;
public class EBbillCalculation
{
int cno;
String cname;
int pm_reading,cm_reading,units;
double billpay;
void getdetails()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the Consumer No:");
cno=in.nextInt();
System.out.println("Enter the Consumer Name:");
cname=in.next();
System.out.println("Enter the Previous Month Reading:");
pm_reading=in.nextInt();
System.out.println("Enter the Current Month Reading:");
cm_reading=in.nextInt();
units= cm_reading-pm_reading;
System.out.println("Choose the type of EB Connection
1.Domestic connection 2. Commercial connection");
int ch=in.nextInt();
switch(ch)
{
case 1:

11
Domestic_Calculation(units);
break;
case 2: Commercial_Calculation(units);
break;
}
}

void Domestic_Calculation(int units)


{
billpay = 0;
if(units<=100)
{
billpay=units*1.00;
}
else if(units>100 && units<=200)
{
billpay=100*1.00+(units-100)*2.50;
}
else if(units>200 && units<=500)
{
billpay=100*1.00+200*2.50+(units-200)*4.00;
}
else if(units>500)
{
billpay =100*1.00+200*2.50+500*4.00+(units-500)*6.00;

}
show();
System.out.println("Amount to be Paid : " + billpay);
}
void Commercial_Calculation(int units)
{
billpay = 0;
if(units<=100)
{
billpay=units*2.00;
}
else if(units>100 && units<=200)
{
billpay=100*2.00+(units-100)*4.50;
}

else if(units>200 && units<=500)


{

12
billpay=100*2.00+200*4.50+(units-200)*6.00;
}
else if(units>500)
{
billpay =100*2.00+200*4.50+500*6.00+(units-500)*7.00;
}
show();
System.out.println("Amount to be Paid : " + billpay);
}

public void show()


{
System.out.println("Customer Number : " + cno);
System.out.println("Customer Number : " + cname);
System.out.println("Units Consumed : " + units);
}

public static void main(String[] args)


{
EBbillCalculation eb=new EBbillCalculation();
eb.getdetails();
}
}

OUTPUT:

13
14
4. 0 Result:
Thus above program was executed and output is verified.

REVIEW QUESTIONS:

⦁ Explain public static void main(String args[]).

⦁ Why Java is platform independent?

⦁ What are constructors in Java?

⦁ What are the access specifies in OOPS

15
Ex. No. 2 Program To Implement Currency Converter,
Distance Converter and Time Converter Using
Packages

Date:

1.0 Aim
To develop a java application to implement currency converter,distance converter and
time converter using the concept of packages.

Develop a java application to implement currency converter (Dollar to INR, EURO to


INR, Yen to INR and vice versa), distance converter (meter to KM, miles to KM and vice
versa), time converter (hours to minutes, seconds and vice versa) using packages.

2.0 Algorithm:
STEP 1: Start
STEP 2: Read the choice of conversion

16
STEP 3: Write a switch case for the required functions

STEP 4: Define the packages for conversion


STEP 5: Convert using appropriate packages

3.0 Program:
a) Currency Converter
package currencyconverter;

import java.io.*;
import java.util.Scanner;

public class Currencyconverter {

public static void main(String[] args) {

double Rs;
Scanner in = new Scanner(System.in);
System.out.println("Choose the type of currency conversition");
System.out.println("1.USDollar to INDRupees,2.Euro to INDRupees,3.
JapaneseYen to INDRupees");
int ch=in.nextInt();
switch(ch)

{
case 1: System.out.println("Dollar to Rupees conversion");
System.out.println("Enter the number of Dollars");
double dollar=in.nextInt();
Rs=dollar*67.02;
System.out.println("USD="+dollar+" is INR="+Rs);
break;
case 2: System.out.println("EURO to Rupees conversion");

17
System.out.println("Enter the number of EURO");
double Euro=in.nextInt();
Rs=Euro*78.29;
System.out.println("Euro="+Euro+" is INR="+Rs);
break;
case 3: System.out.println("Japanese Yen to Rupees conversion");
System.out.println("Enter the number of Yen");
double Yen=in.nextInt();
Rs=Yen*0.61;
System.out.println("Yen="+Yen+" is INR="+Rs);
break;
}

}
}

b) Distance Converter
package currencyconverter;
import java.io.*;
import java.util.Scanner;
public class distanceconvertor {
public static void main(String args[])
{
double meters,kilometers,miles;
Scanner in = new Scanner(System.in);

System.out.println("Choose the type of Distance conversion");


System.out.println("1.Meters to KiloMeters ,2. Miles to KiloMeters :");
int ch=in.nextInt();
switch(ch)
{
case 1: System.out.println("Meters into KiloMeters");

System.out.println("Enter the number of Meters");


meters=in.nextDouble();

18
kilometers = meters * 0.001;
System.out.println( meters+ " Meters is " +kilometers+ " in Kilometers");
break;
case 2: System.out.println("Miles to Kilometers conversion");
System.out.println("Enter the number of Miles");
miles=in.nextDouble();
kilometers =miles * 1.60934;
System.out.println( miles+ " Miles is " +kilometers + " in Kilometers");
break;
}
}
}
c) Time Converter
package currencyconverter;

import java.util.Scanner;

public class Timeconverter


{
public static void main(String[] args) {
int n,hr,min,sec;
Scanner in = new Scanner(System.in);
System.out.print("Enter the Input in seconds:");
n= in.nextInt();
if(n>3600){
min = n/60;
sec = n%60;
hr = min/60;
min = min%60;
System.out.println("Converted format:"+hr+ "hour " + min +"mins" +
sec+"secs");
}
else{
min = n/60;
sec = n%60;
System.out.println("Converted format :"+min+" mins " +sec +"secs");
}
}

19
}

OUTPUT:

20
21
4.0 Result:
Thus above program executed and output is verified.

REVIEW QUESTIONS:

1. Define packages in Java

22
2. Can we import same package/class twice? Will the JVM load the package twice at
runtime?

3. How will you define classes in Java?

4. Differentiate abstraction and encapsulation.

5. What is a static variable?

Ex.No. 3 PROGRAM TO GENERATE PAYSLIP


USING INHERITANCE

23
Date:

1.0 Aim
To develop a java application to generate pay slip for different category of employees
using the concept of inheritance.

Develop a java application with Employee class with Emp_name, Emp_id, Address,
Mail_id, Mobile_no as members. Inherit the classes, Programmer, Assistant Professor,
Associate Professor and Professor from employee class. Add Basic Pay (BP) as the
member of all the inherited classes with 97% of BP as DA, 10 % of BP as HRA, 12% of
BP as PF, 0.1% of BP for staff club fund. Generate pay slips for the employees with their
gross and net salary

2.0 Procedure:
STEP 1: Create the specified classes
STEP 2: Add members of the inherited class
STEP 3: Calculate gross salary and net salary with the given equation
STEP 4: Display the pay slip with net salary and gross salary

3.0 Program:

package employee;
import java.io.IOException;
import java.util.Scanner;

class Emp
{
String ename,Address,email;
int eid;
int mobile;

void getEmployeedetails()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the Emp_id. :");
eid=in.nextInt();

24
System.out.println("Enter the Employee Name:");
ename=in.next();
System.out.println("Enter the Employee Address:");
Address=in.next();
System.out.println("Enter the Employee Email id :");
email=in.next();

System.out.println("Enter the Mobile No:");


mobile=in.nextInt();
}
void pay_calulation(double BasicPay)
{
double DA,HRA,PF,Sfund,Gross_Salary,Netsalary;
DA=BasicPay*0.97;
HRA=BasicPay*0.10;
PF=BasicPay*0.12;
Sfund=BasicPay*0.1;
Gross_Salary=BasicPay+DA+HRA;
Netsalary=Gross_Salary-(PF+Sfund);
System.out.println("Gross salary of the Employee"+Gross_Salary);
System.out.println("Net salary of the Employee: "+Netsalary);

}
void display()
{
System.out.println("Emp_id:"+eid);
System.out.println("Employee Name:"+ename);
System.out.println("Employee Address:"+Address);
System.out.println("Employee Email id :"+email);
System.out.println("Employee Mobile No:"+mobile);
}
}
class Programmer extends Emp
{
double BasicPay;
void Programmerdetails()
{
getEmployeedetails();

25
Scanner in = new Scanner(System.in);
System.out.println("Enter the Basic Pay of the Programmer:");
BasicPay=in.nextInt();
display();
pay_calulation(BasicPay);
}
}
class AssistantProfessor extends Emp
{

void APDetails()
{
double BasicPay;
getEmployeedetails();
Scanner in = new Scanner(System.in);

System.out.println("Enter the Basic Pay of the AssistantProfessor:");


BasicPay=in.nextInt();
display();
pay_calulation(BasicPay);
}

}
class AssociateProfessor extends Emp
{
double BasicPay;

void ASPDetails()
{
getEmployeedetails();
Scanner in = new Scanner(System.in);
System.out.println("Enter the Basic Pay of the AssociateProfessor:");
BasicPay=in.nextInt();
display();
pay_calulation(BasicPay);
}

26
class Professor extends Emp
{
double BasicPay;
void profDetails()
{
getEmployeedetails();
Scanner in = new Scanner(System.in);
System.out.println("Enter the Basic Pay of the Professor:");
BasicPay=in.nextInt();
display();
pay_calulation(BasicPay);
}

public class Employee


{

public static void main(String[] args)


{

Scanner in = new Scanner(System.in);


System.out.println("Choose the type Employee");

System.out.println("1.Programmer ,2.Assistant Professor,3.Associate


Professor ,4.Professor: ");
int ch=in.nextInt();
switch(ch)
{
case 1: System.out.println("PROGRAMMER DETAILS");
Programmer p=new Programmer();
p.Programmerdetails();
break;
case 2: System.out.println("Assistant Professor DETAILS");
AssistantProfessor ap=new AssistantProfessor();
ap.APDetails();
break;

27
case 3: System.out.println("Associate Professor DETAILS");
AssociateProfessor asp=new AssociateProfessor();
asp.ASPDetails();
break;
case 4: System.out.println("Professor DETAILS");
Professor pf=new Professor();
pf.profDetails();
break;

}
}}

28
OUTPUT:

4.0 Result:

29
Thus above program executed and output is verified.

REVIEW QUESTIONS:
⦁ Can a top-level class be private or protected?

⦁ Will java support multiple inheritance?

⦁ What is Method Overriding? What restrictions are placed on method overriding?

⦁ If a class is declared without any access modifiers, where may the class be
accessed?

30
⦁ Does a class inherit the constructors of its superclass?

Ex. No. 4 PROGRAM FOR STACK ADT USING


INTERFACE

Date:

1.0 Aim

To design a java application to implement array implementation of stack using the


concept of interface and exception handling.

Design a Java interface for ADT Stack. Implement this interface using array. Provide
necessary exception handling in both the implementations
2.0 Algorithm:
STEP 1: Define a java interface with methods push and pop
STEP 2: Define the push and pop operations with array
STEP 3: Provide the appropriate exception handling techniques

31
3.0 Program:

package stackadt;
import java.io.*;
interface Mystack
{
public void pop();
public void push();
public void display();
}
class Stack_array implements Mystack
{
final static int n=5;
int stack[]=new int[n];
int top=-1;
public void push()
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
if(top==(n-1))
{
System.out.println(" Stack Overflow");
return;
}
else
{
System.out.println("Enter the element");
int ele=Integer.parseInt(br.readLine());
stack[++top]=ele;
}
}
catch(IOException e)
{

32
System.out.println("e");
}
}
public void pop()
{
if(top<0)
{
System.out.println("Stack underflow");
return;
}
else
{
int popper=stack[top];
top--;
System.out.println("Popped element:" +popper);
}
}

public void display()


{
if(top<0)
{
System.out.println("Stack is empty");
return;
}
else
{
String str=" ";
for(int i=0; i<=top; i++)
str=str+" "+stack[i]+" <--";
System.out.println("Elements are:"+str);
}
}
}
class StackADT
{
public static void main(String arg[])throws IOException
{

33
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Implementation of Stack using Array");
Stack_array stk=new Stack_array();
int ch=0;
do
{
System.out.println("1.Push 2.Pop 3.Display 4.Exit");
System.out.println("Enter your choice:");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
stk.push();
break;
case 2:
stk.pop();
break;
case 3:
stk.display();
break;
case 4:
System.exit(0);
}
}
while(ch<5);
}
}

34
OUTPUT:

35
4.0 Result:

36
Thus above program executed and output is verified.

REVIEW QUESTIONS:

⦁ Describe stack operations.

⦁ Can you change the size of array once created?

⦁ Difference between a[] and []a in Java?

⦁ What is out of Memory Error in Java?

37
⦁ Can we have an empty catch block?

Ex. No. 5 PROGRAM TO PERFORM STRING


OPERATIONS USING ARRAYLIST
Date:

1.0 Aim
To write a java program to perform string operations using ArrayList for the following
functions
a. Append - add at end
b. Insert – add at particular index
c. Search
Step 1: Start the netbeansIDE8.2

Step 2: Goto FILE new projectjavajava applicationclick next

Step 3: Give the name for the applicationClick Finish.

Step 4: Create an Array list named arrlist, arrlist2 and

add the strings using add()method.

Step 5: Append the arrlist2 to the end of arrlist Using addAll()

38
method .

Step 6: Search the string in Arraylist by using contain() method. if the

string is

found , print search is successful otherwise try again.

Step 7: Print all string starts with given letter by using matches()

method.

Step 8: Stop the program.

3.0 Program:

import java.util.ArrayList;
import java.util.Scanner;

public class ArrayListDemo


{
public static void main(String args[])
{
ArrayList<String> arrlist = new ArrayList<>();
arrlist.add("book");
arrlist.add("cook");
arrlist.add("HTML");
System.out.println("Printing list1:");
System.out.println(arrlist);
arrlist.add(1,"PHP");
System.out.println("(After Insertion)Printing list1:");
System.out.println(arrlist);
ArrayList<String> arrlist2 = new ArrayList<>();
arrlist2.add("cat");
arrlist2.add("bat");
arrlist2.add("hat");
arrlist2.add("Jump");
System.out.println("Printing list2:");

39
System.out.println(arrlist2);
arrlist.addAll(arrlist2);

System.out.println("( After Appended)Printing all the elements");


System.out.println(arrlist);
System.out.println("SEARCH STRING IN ARRAY LIST");
System.out.println("###########################");
Scanner in = new Scanner(System.in);
System.out.println("ENTER THE STRING TO BE SEARCH:");
String searchString=in.next();
boolean Found = arrlist.contains(searchString);
if(Found)
System.out.println("SUCCESS!!! String is available in the Arraylist");
else
System.out.println("Failure!!! Try Again");
System.out.println("LIST THE STRING IN ARRAY LIST");
System.out.println("-----------------------------------------------");
ArrayList <String> listClone = new ArrayList<>();
for (String string : arrlist)
{
if(string.matches("(?i)(b).*"))
{
listClone.add(string);
}
}
System.out.println(listClone);
}
}

OUTPUT:

40
41
4.0 Result:
Thus above program executed and output is verified.

REVIEW QUESTIONS:

⦁ Is String a keyword in java?

⦁ In how many ways you can create string objects in java?

⦁ How do you create mutable string objects?

⦁ What is the difference between String, StringBuffer and StringBuilder?

42
⦁ What is special about string objects as compared to objects of other derived
types?

Ex. No. 6 PROGRAM TO CALCULATE AREA


USING

ABSTRACT CLASS
Date:

1.0 Aim
To write a java program to calculate the area of rectangle,circle and triangle using the
concept of abstract class.
Write a Java Program to create an abstract class named Shape that contains two
integers and an empty method named print Area(). Provide three classes named
Rectangle, Triangle and Circle such that each one of the classes extends the class Shape.
Each one of the classes contains only the method print Area () that prints the area of the
given shape.

43
2.0 Algorithm:
STEP 1: Create an abstract class with the name shape
STEP 1.1: Let sides of shape be Side1 and Side2, create variables Side1, Side2
STEP 1.2: Define an empty method PrintArea()
STEP 2: Create three classes with names Rectangle, Triangle and Circle
STEP 2.1: Extend the Shape class in each of these classes
STEP 2.2: Develop the implementation of Area in each class appropriately
STEP 2.3: For Eg: PrintArea() of Circle would be 3.14*Side1*Side1 ; here Side1
is considered as circle’s radius
STEP 3: Write a class with main method
STEP 4: Create instance of all three classes
STEP 5: Calculate the Area for each shape
STEP 6: Display the area

3.0 Program:

package javaapplication3;
abstract class shape
{
int a=3,b=4;
abstract public void print_area();
}
class rectangle extends shape
{
public int area_rect;
@Override
public void print_area()
{

44
area_rect=a*b;
System.out.println("The area ofrectangle is:"+area_rect);
}
}
class triangle extends shape
{
int area_tri;
@Override
public void print_area()
{
area_tri=(int) (0.5*a*b);
System.out.println("The area oftriangle is:"+area_tri);
}
}
class circle extends shape
{
int area_circle;
@Override
public void print_area()
{
area_circle=(int) (3.14*a*a);
System.out.println("The area ofcircle is:"+area_circle);
}
}
public class JavaApplication3 {
public static void main(String[] args) {

45
rectangle r=new rectangle();
r.print_area();
triangle t=new triangle();
t.print_area();
circle r1=new circle();
r1.print_area();
}
}

OUTPUT:

46
4.0 Result:

Thus above program executed and output is verified.

Points to remember:
⦁ Abstract classes are not Interfaces. They are different, we will study this when we
will study Interfaces.
⦁ An abstract class may or may not have an abstract method. But if any class has even a
single abstract method, then it must be declared abstract.
⦁ Abstract classes can have Constructors, Member variables and Normal methods.
⦁ Abstract classes are never instantiated.
⦁ When you extend Abstract class with abstract method, you must define the abstract
method in the child class, or make the child class abstract.

REVIEW QUESTIONS:

⦁ Can abstract class have constructors in Java?

⦁ Can abstract class be final in Java?

47
⦁ Difference between abstract class and interface in Java?
Abstract class Interface

⦁ Can abstract class have static methods in Java?

48
⦁ Can you create instance of abstract class?

⦁ Are all the methods in an abstract class are abstract?

Ex. No. 7 PROGRAM TO IMPLEMENT USER


DEFINED EXCEPTION HANDLING
Date :

49
1.0 Aim
To write a java program to implement user defined exception handling

2.0 Algorithm:
STEP 1: Create a class that extends Exception class
STEP 1.1: Let the name be MyException
STEP 1.2: Define a constructor that calls super()
STEP 2: Create a class with main method
STEP 2.1: Use the MyException in the try catch clause

3.0 Program:

package example1;

class MyException extends Exception{


String str1;
MyException(String str2) {
str1=str2;
}
public String toString(){
return ("MyException Occurred: "+str1) ;
}
}
public class Example1 {

public static void main(String[] args)

{
try{
System.out.println("Starting of try block");
// I'm throwing the custom exception using throw
throw new MyException("This is My error Message");
}
catch(MyException exp){

50
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}

OUTPUT:

51
⦁ Result:
Thus above program executed and output is verified.

Points to remember:
⦁ Extend the Exception class to create your own exception class.
⦁ You don't have to implement anything inside it, no methods are required.
⦁ You can have a Constructor if you want.
⦁ You can override the toString() function, to display customized message.

REVIEW QUESTIONS:
⦁ What is difference between Checked and Unchecked Exception in Java?
BASIS FOR
CHECKED EXCEPTION UNCHECKED EXCEPTION
COMPARISON
The compiler checks the The compiler does not check
Basic
checked exception. the Unchecked exception.
Except "RuntimeException"
class all the child classes of the "RuntimeException" class and
Class of
class "Exception", and the its child classes,are"Unchecked
Exception
"Error" class and its child Exceptions".
classes are Checked Exception.
If we do not handle the checked Even if we do not handle the
Handling exception, then the compiler unchecked exception, the
objects. compiler doesn't object.
The program compiles
The program doesn't compile if
successfully even if there is an
Compilation there is an unhandled checked
unhandled unchecked
exception in the program code.
exception in the program code.

52
⦁ What is difference between throw and throws keyword in Java?
BASIS OF
THROW THROWS
COMPARISON
The throw keyword
The throws keyword is used to delegate
handover our created
Basic the responsibility of exception handling
exception object to
to the caller of the method.
JVM manually.
return_typemethod_name(parameter-list)
throws ExceptionClass_list
throw Throwable-
Syntax {
instance;
// body of method
}
The throw keyword is The throws keyword is followed by the
Followed by followed by exception list of the exception classes that can
object. occur in the method.
Number of The throw keyword The throws keyword can declare
Exception can throw a single multiple exception classes separated by a
thrown exception instance. comma.

⦁ Can we have an empty catch block?

⦁ What happens when exception is thrown by main method?

53
⦁ What is the difference between error and exception in java?

BASIS FOR
ERROR EXCEPTION
COMPARISON
An error is caused due to lack An exception is caused because
Basic
of system resources. of the code.
Recovery An error is irrecoverable. An exception is recoverable.
Exceptions are handled using
There is no means to handle
Keywords three keywords "try", "catch",
an error by the program code.
and "throw".
As an exception is detected, it is
As the error is detected the
thrown and caught by the
Consequences program will terminated
"throw" and "catch" keywords
abnormally.
correspondingly.
Errors are classified as Exceptions are classified as
Types
unchecked type. checked or unchecked type.
In Java, errors are defined In Java, an exceptions are
Package
"java.lang.Error" package. defined in"java.lang.Exception".
Checked
Exceptions :NoSuchMethod,
OutOfMemory, ClassNotFound.
Example
StackOverFlow. Unchecked
Exceptions :NullPointer,
IndexOutOfBounds.

Ex. No. 8 PROGRAM FOR DISPLAYING FILE


INFORMATION

Date :
1.0 Aim
To write a java program that reads a file name from the user, displays information about

54
whether the file exists, whether the file is readable, or writable, the type of file and the
length of the file in bytes.
Write a Java program that reads a file name from the user, displays information
about whether the file exists, whether the file is readable, or writable, the type of file and
the length of the file in bytes.

2.0 Algorithm:
STEP 1: Create a text file with some contents
STEP 1.1: Let the name of file be ‘Example.txt’
STEP 1.2: Enter some content and save in the same folder as java program
STEP 2: Create a class with main method
STEP 2.1: Create a file object
STEP 2.2: Print all the attributes of the file objects

3.0 Program:
import java.util.Scanner;
import java.io.File;

public class Filedemo {

public static void main(String[] args) {

Scanner input=new Scanner(System.in);


String s=input.nextLine();
File f1=new File(s);
System.out.println("File Name:"+f1.getName());
System.out.println("Path:"+f1.getPath());
System.out.println("Abs Path:"+f1.getAbsolutePath());
System.out.println("Parent:"+f1.getParent());
System.out.println("This file
is:"+(f1.exists()?"Exists":"Does not exists"));
System.out.println("Is file:"+f1.isFile());
System.out.println("Is Directory:"+f1.isDirectory());
System.out.println("Is Readable:"+f1.canRead());
System.out.println("IS Writable:"+f1.canWrite());

55
System.out.println("Is Absolute:"+f1.isAbsolute());
System.out.println("File Last
Modified:"+f1.lastModified());
System.out.println("File Size:"+f1.length()+"bytes");
System.out.println("Is Hidden:"+f1.isHidden());

Fib.java

public class Fib {

public static void main(String[] args) {


int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);

for(i=2;i<count;++i)
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}

56
OUTPUT:

57
4.0 Result:
Thus above program executed and output is verified.

REVIEW QUESTIONS:

⦁ What are flush() and close() used for ?

⦁ What is the difference between the Reader/Writer class hierarchy and the
Input Stream/Output Stream class hierarchy?

58
⦁ Which class is used to read streams of characters from a file? Which class is
used to read streams of raw bytes from a file?

⦁ What is the difference between System.out , System.err and System.in?

⦁ Which exceptions should be handled with the following code?

File Output Streamfile Output Stream = new FileOutputStream(new


File("newFile.txt"));

Ex. No. 9 PROGRAM TO IMPLEMENT


MULTITHREADED APPLICATION
Date :

1.0 Aim
To write a java program that implements a multi-threaded application .

59
Write a java program that implements a multi-threaded application that has three
threads. First thread generates a random integer every 1 second and if the value is even,
second thread computes the square of the number and prints. If the value is odd, the third
thread will print the value of cube of the number.

2.0 Algorithm:
STEP 1: Create three classes ,IntThread, SqThread, CubeThread
STEP 1.1: Let the classes extend the Thread Class
STEP 1.2: Let the run method of IntTheadhave random no generator
STEP 1.3: Let the run method of SqThread have square generator
STEP 1.4: Let the run method of CubeThread have cube generator
STEP 2: Create a class with main method
STEP 2.1: Create instances of IntThread, SqThread, CubeThread
STEP 2.2: Synchronize all the threads and print no, then square and then cube

3.0 Program:

package mtherad;
import java.util.*;

class even implements Runnable{


public int x;
public even(int x){
this.x=x;
}

@Override
public void run()
{
System.out.println("Thread Name:Even Thread and square is: " +
x * x);

60
class odd implements Runnable{
public int x;
public odd(int x){
this.x=x;
}
@Override
public void run()
{
System.out.println("Thread Name:Odd Thread and cube is :"+ x
* x * x);

}
class A extends Thread{
public String tname;
public Random r;
public Thread t1,t2;
public A(String s){
tname=s;
}
@Override
public void run()
{
int num=0;
r=new Random();
try {
for(int i=0;i<50;i++){
num=r.nextInt(100);
System.out.println("main thread and generated number is"+num);
if(num%2==0)
{
t1=new Thread(new even(num));
t1.start();
}else{
t2=new Thread(new odd(num));
t2.start();

61
}
Thread.sleep(1000);
System.out.println("------------------------------------");
}
}

catch(InterruptedException ex)
{
System.out.println(ex.getMessage());
}
}
}

public class Mtherad {

public static void main(String[] args) {


A a=new A("one");
a.start();
}

OUTPUT:

62
4.0 Result:
Thus above program executed and output is verified.

REVIEW QUESTIONS:

⦁ What is the difference between Process and Thread?

63
⦁ What is difference between user Thread and daemon Thread?

⦁ Why wait(), notify() and notifyAll() methods have to be called from


synchronized method or block?

⦁ Which is more preferred – Synchronized method or Synchronized block?

⦁ Why Thread sleep() and yield() methods are static?

64
Ex. No. 10 FINDTHE MAXIMUM VALUE FROM THE
GIVENTYPE OF ELEMENTS
Date :

1.0 Aim
To write a java program to find the maximum value from the given type of elements
using a generic function.
Write a java program to find the maximum value from the given type of elements
using a generic function.

2.0 Algorithm:
STEP 1: Write a function to find the maximum no in an array
STEP 1.1: Convert the function to generic by giving Type parameter
STEP 2: Create a class with main method
STEP 2.1: Invoke the generic function with array of integers
STEP 2.2: Invoke the generic function with array of float
STEP 2.3: Invoke the generic function with array of chars
STEP 2.4: Invoke the generic function with array of string

3.0 Program:

package genericmethodtest;

public class GenericMethodTest {

public static <T extends Comparable<T>> T maximum(T x, T y, T z)


{

T max = x; // assume x is initially the largest

65
if(y.compareTo(max) > 0) {
max = y; // y is the largest so far
}

if(z.compareTo(max) > 0) {
max = z; // z is the largest now
}
return max; // returns the largest object
}

public static void main(String args[])


{
System.out.printf("Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ));

System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",


6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));

}
}

OUTPUT:

66
4.0 Result:
Thus above program executed and output is verified.

REVIEW QUESTIONS:

67
⦁ What are advantages of using Generics?

⦁ How Can We Restrict Generics To A Super Class Of Particular Class?

⦁ How Can We Restrict Generics To A Subclass Of Particular Class?

⦁ How To Write Parameterized Class In Java Using Generics ?

⦁ Can you give an example of a Generic Method?

68
EX NO: 11 DESIGN A CALCULATOR USING
EVENTDRIVENPROGRAMMING
PARADIGM

Date:

1.0 Aim
To design a calculator using event driven programming paradigm of Java with the
following options

⦁ Decimal Manipulations
⦁ Scientific Manipulations

69
2.0 Procedure

1. import the swing packages and awt packages.


2. Create the class scientificcalculator that implements action listener.
3. Create the container and add controls for digits , scientific calculations and decimal
Manipulations.
4. The different layouts can be used to lay the controls.
5.When the user presses the control , the event is generated and handled .
6. The corresponding decimal , numeric and scientific calculations are performed.

3.0 Program:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class ScientificCalculator extends JFrame implements
ActionListener
{
JTextField tfield;

double temp,temp1,result,a,ml;
static double m1,m2;
int k=1,x=0,y=0,z=0;
char ch;
JButton
b1,b2,b3,b4,b5,b6,b7,b8,b9,zero,clr,pow2,pow3,exp,fac,plus,min,di
v,log, rec,mul,eq,addsub,dot,mr,mc,mp,mm,sqrt,sin,cos,tan;
Container cont;
JPanel textpanel,buttonpanel;
ScientificCalculator()
{
cont=getContentPane();
cont.setLayout(new BorderLayout());
JPanel textpanel=new JPanel();
tfield=new JTextField(25);
tfield.setHorizontalAlignment(SwingConstants.RIGHT);
tfield.addKeyListener(new KeyAdapter()
{
public void keyTyped(KeyEvent 70 keyevent)
{
char c=keyevent.getKeyChar();
if(c>='0'&&c<='9')
{
Ex No. 13 IMPLEMENTATION OF STACK USING LIST

Date:

1.0 Aim:
Write a java program to implementation of stack using list. Handle all exceptions.

2.0 Algorithm:

STEP 1: Define a java interface with methods push and pop


STEP 2: Define the push and pop operations with array
STEP 3: End the program

3.0 Program:

import java.util.*;

/* Class Node */
class Node
{
protected int data;
protected Node link;

/* Constructor */
public Node()
{
link = null;
data = 0;
}
/* Constructor */
public Node(int d,Node n)
{
data = d;
link = n;
}

71
/* Function to set link to next Node */
public void setLink(Node n)
{
link = n;
}
/* Function to set data to current Node */
public void setData(int d)
{
data = d;
}
/* Function to get link to next node */
public Node getLink()
{
return link;
}
/* Function to get data from current Node */
public int getData()
{
return data;
}
}

/* Class linkedStack */
class linkedStack
{
protected Node top ;
protected int size ;

/* Constructor */
public linkedStack()
{
top = null;
size = 0;
}
/* Function to check if stack is empty */
public boolean isEmpty()
{
return top == null;
}
/* Function to get the size of the stack */
public int getSize()
{
return size;
}
/* Function to push an element to the stack */

72
public void push(int data)
{
Node nptr = new Node (data, null);
if (top == null)
top = nptr;
else
{
nptr.setLink(top);
top = nptr;
}
size++ ;
}
/* Function to pop an element from the stack */
public int pop()
{
if (isEmpty() )
throw new NoSuchElementException("Underflow Exception") ;
Node ptr = top;
top = ptr.getLink();
size-- ;
return ptr.getData();
}
/* Function to check the top element of the stack */
public int peek()
{
if (isEmpty() )
throw new NoSuchElementException("Underflow Exception") ;
return top.getData();
}
/* Function to display the status of the stack */
public void display()
{
System.out.print("\nStack = ");
if (size == 0)
{
System.out.print("Empty\n");
return ;
}
Node ptr = top;
while (ptr != null)
{
System.out.print(ptr.getData()+" ");
ptr = ptr.getLink();
}
System.out.println();

73
}
}

/* Class LinkedStackImplement */
public class LinkedStackImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of class linkedStack */
linkedStack ls = new linkedStack();
/* Perform Stack Operations */
System.out.println("Linked Stack Test\n");
char ch;
do
{
System.out.println("\nLinked Stack Operations");
System.out.println("1. push");
System.out.println("2. pop");
System.out.println("3. peek");
System.out.println("4. check empty");
System.out.println("5. size");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println("Enter integer element to push");
ls.push( scan.nextInt() );
break;
case 2 :
try
{
System.out.println("Popped Element = "+ ls.pop());
}
catch (Exception e)
{
System.out.println("Error : " + e.getMessage());
}
break;
case 3 :
try
{
System.out.println("Peek Element = "+ ls.peek());
}
catch (Exception e)

74
{
System.out.println("Error : " + e.getMessage());
}
break;
case 4 :
System.out.println("Empty status = "+ ls.isEmpty());
break;
case 5 :
System.out.println("Size = "+ ls.getSize());
break;
case 6 :
System.out.println("Stack = ");
ls.display();
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
/* display stack */
ls.display();
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);

} while (ch == 'Y'|| ch == 'y');


}
}
OUTPUT
Linked Stack Test

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size
1

Enter integer element to push


5

Stack = 5

Do you want to continue (Type y or n)

75
y

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size
1
Enter integer element to push
33

Stack = 33 5

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size
1
Enter integer element to push
24

Stack = 24 33 5

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size
1
Enter integer element to push
87

76
Stack = 87 24 33 5

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size
1
Enter integer element to push
99

Stack = 99 87 24 33 5

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size
1
Enter integer element to push
1

Stack = 1 99 87 24 33 5

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size
5

77
Size = 6

Stack = 1 99 87 24 33 5

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size

3
Peek Element = 1

Stack = 1 99 87 24 33 5

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size
2
Popped Element = 1

Stack = 99 87 24 33 5

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size

78
2
Popped Element = 99

Stack = 87 24 33 5

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size
2
Popped Element = 87

Stack = 24 33 5

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size
5
Size = 3

Stack = 24 33 5

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size

79
2
Popped Element = 24

Stack = 33 5

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size
3
Peek Element = 33

Stack = 33 5

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size
2
Popped Element = 33

Stack = 5

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size

80
2
Popped Element = 5

Stack = Empty

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size
2
Error : Underflow Exception

Stack = Empty

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size
3
Error : Underflow Exception

Stack = Empty

Do you want to continue (Type y or n)

Linked Stack Operations


1. push
2. pop
3. peek
4. check empty
5. size

81
4
Empty status = true

Stack = Empty

Do you want to continue (Type y or n)

4.0 Result:

Thus the java program executed successfully.

82
Ex. No: 14 IMPLEMENT 2 - D SHAPES
Date:

1.0 Aim:
Write a Java program to implement 2-D shapes

2.0 Algorithm:
Step 1: Start the program
Step 2: Open the notepad and type the program and save the program as
Draw2DObjects.java
Step 3: Import graphics and geometric packages.
Step 4: Create the class Draw2DObjects. Define and declare its variables.
Step 5: Click on the Cmd Prompt cd C:\Java\jdk1.8\bin
Step 6: Now compile the Filedemo.java using
javac Draw2DObjects.java
Step 7: Execute the program using
java Draw2DObjects

3.0 Program:

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Graphics2D;

83
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;

import javax.swing.JFrame;

public class Draw2DObjects extends JFrame {


Shape shapes[] = new Shape[5];
public static void main(String args[]) {
Draw2DObjects app = new Draw2DObjects();
}

public Draw2DObjects() {
add("Center", new MyCanvas());
shapes[0] = new Line2D.Double(0.0, 0.0, 100.0, 100.0);
shapes[1] = new Rectangle2D.Double(10.0, 100.0, 200.0, 200.0);
shapes[2] = new Ellipse2D.Double(20.0, 200.0, 100.0, 100.0);
GeneralPath path = new GeneralPath(new Line2D.Double(300.0, 100.0, 400.0,
150.0));
path.append(new Line2D.Double(25.0, 175.0, 300.0, 100.0), true);
shapes[3] = path;
shapes[4] = new RoundRectangle2D.Double(350.0, 250, 200.0, 100.0, 50.0,
25.0);
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

class MyCanvas extends Canvas {


public void paint(Graphics graphics) {
Graphics2D g = (Graphics2D) graphics;
for (int i = 0; i < shapes.length; ++i) {
if (shapes[i] != null)
g.draw(shapes[i]);
}
}
}
}

OUTPUT:

84
4.0 Result:
Thus the2-D shapes programhas been written and executed
successfully.

85

Potrebbero piacerti anche