Revised CS8383 (Eee) Oop Lab Man
Revised CS8383 (Eee) Oop Lab Man
Revised CS8383 (Eee) Oop Lab Man
for
1
CHENNAI – 600097
CERTIFICATE
2
Faculty In-Charge HoD
3
⦁ Facilitate socially responsive research, innovation and entrepreneurship
⦁ Nurture the virtue of service and an ethical value system in the young minds
4
On completion of the program, the students will achieve the following:
Provide efficient solutions for real world problems using contemporary
PEO1
tools
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 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:
6
CO2 Develop and implement Java programs with array list K3
7
CS8383 : OBJECT ORIENTED PROGRAMMING LABORATORY
Index
Ex
Name of the Experiment Page No Date Signature
No.
8
01 Generation of Electricity bill.
09 Illustration of Multi-Threading
12 Mini Project
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:
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;
}
}
}
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;
}
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);
}
OUTPUT:
13
14
4. 0 Result:
Thus above program was executed and output is verified.
REVIEW QUESTIONS:
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.
2.0 Algorithm:
STEP 1: Start
STEP 2: Read the choice of conversion
16
STEP 3: Write a switch case for the required functions
3.0 Program:
a) Currency Converter
package currencyconverter;
import java.io.*;
import java.util.Scanner;
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);
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;
19
}
OUTPUT:
20
21
4.0 Result:
Thus above program executed and output is verified.
REVIEW QUESTIONS:
22
2. Can we import same package/class twice? Will the JVM load the package twice at
runtime?
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();
}
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);
}
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);
}
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?
⦁ 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?
Date:
1.0 Aim
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);
}
}
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:
37
⦁ Can we have an empty catch block?
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
38
method .
string is
Step 7: Print all string starts with given letter by using matches()
method.
3.0 Program:
import java.util.ArrayList;
import java.util.Scanner;
39
System.out.println(arrlist2);
arrlist.addAll(arrlist2);
OUTPUT:
40
41
4.0 Result:
Thus above program executed and output is verified.
REVIEW QUESTIONS:
42
⦁ What is special about string objects as compared to objects of other derived
types?
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:
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:
47
⦁ Difference between abstract class and interface in Java?
Abstract class Interface
48
⦁ Can you create instance of abstract class?
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;
{
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.
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.
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;
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
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 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?
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.*;
@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());
}
}
}
OUTPUT:
62
4.0 Result:
Thus above program executed and output is verified.
REVIEW QUESTIONS:
63
⦁ What is difference between user Thread and daemon Thread?
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;
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
}
}
}
OUTPUT:
66
4.0 Result:
Thus above program executed and output is verified.
REVIEW QUESTIONS:
67
⦁ What are advantages of using Generics?
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
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:
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);
Stack = 5
75
y
Stack = 33 5
Stack = 24 33 5
76
Stack = 87 24 33 5
Stack = 99 87 24 33 5
Stack = 1 99 87 24 33 5
77
Size = 6
Stack = 1 99 87 24 33 5
3
Peek Element = 1
Stack = 1 99 87 24 33 5
Stack = 99 87 24 33 5
78
2
Popped Element = 99
Stack = 87 24 33 5
Stack = 24 33 5
Stack = 24 33 5
79
2
Popped Element = 24
Stack = 33 5
Stack = 33 5
Stack = 5
80
2
Popped Element = 5
Stack = Empty
Stack = Empty
Stack = Empty
81
4
Empty status = true
Stack = Empty
4.0 Result:
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 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);
}
OUTPUT:
84
4.0 Result:
Thus the2-D shapes programhas been written and executed
successfully.
85