IT2305 – JAVA PROGRAMMING LABORATORY L A

Dr.N.N.C.E
IT / V Sem
JP Lab - LM
IT2305 – JAVA PROGRAMMING LABORATORY
LABORATORY MANUAL
FOR V SEMESTER B.TECH / IT
ACADEMIC YEAR: 2013 – 2014 (ODD)
(FOR PRIVATE CIRCULATION ONLY)
ANNA UNIVERSITY, CHENNAI.
DEPARTMENT OF INFORMATION TECHNOLOGY
DR.NAVALAR NEDUNCHEZHIAYN COLLEGE OF ENGINEERING,
THOLUDUR-606303, CUDDALORE DIST.
1
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
GENERAL INSTRUCTIONS FOR LABORATORY CLASSES
DO’S
o
Without Prior permission do not enter into the Laboratory.
o
While entering into the LAB students should wear their ID cards.
o
The Students should come with proper uniform.
o
Students should sign in the LOGIN REGISTER before entering into the laboratory.
o
Students should come with observation and record note book to the laboratory.
o
Students should maintain silence inside the laboratory.
o
After completing the laboratory exercise, make sure to shutdown the system properly.
DONT’S
o Students bringing the bags inside the laboratory..
o Students wearing slippers/shoes insides the laboratory.
o Students using the computers in an improper way.
o Students scribbling on the desk and mishandling the chairs.
o Students using mobile phones inside the laboratory.
o Students making noise inside the laboratory.
2
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
HARDWARE REQUIREMENTS:
Pentium IV with 2 GB RAM,
160 GB HARD Disk,
Monitor 1024* 768 color
60Hz
SOFTWARE REQUIREMENTS:
Windows / Linux operating system
JDK 1.6 (or above)
UNIVERSITY PRACTICAL EXAMINATION
Allotment of marks Internal assessment
Practical examination
Total
=
20 marks
=
80 marks
--------------------=
100 marks
---------------------
INTERNAL ASSESSMENT (20 marks)
Staff should maintain assessment register and the HOD should monitor it
Split up of Internal Marks
Observation
Record Note
Modal Exam
Attendance
=
3 marks
=
7 marks
=
5 marks
=
5 marks
--------------------=
20 marks
---------------------
Total
UNIVERSITY EXAMINATION
The exam will be conducted for 100 marks. Then the marks will be calculated to 80 marks
Split up of Practical Examination Marks
Aim and Procedure
=
30 marks
Program
=
30 marks
Execution
=
20 marks
Output & result
=
10 marks
Viva voce
=
10 marks
--------------------=
100 marks
---------------------
Total
3
Dr.N.N.C.E
IT / V Sem
IT2305 – JAVA PROGRAMMING LABORATORY
LIST OF EXPERIMENTS
1. Java package with simple stack and queue class
2. Complex number manipulation
3. Date class similar to java.util package
4. Implementing dynamic polymorphism in java
5. Java interface for ADT stack
6. DNA file creation
7. Developing a simple paint like program using applet
8. Developing a scientific calculator
9. Developing a template for linked list
10. Develop a multi threaded producer consumer Application
11. Generating prime numbers and Fibonacci series
12. Multithreaded GUI application
4
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
S.
No
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
NAME OF THE EXPERIMENTS
JAVA PACKAGE WITH SIMPLE
STACK AND QUEUE CLASS
COMPLEX NUMBER
MANIPULATION
DATE CLASS SIMILAR TO
JAVA.UTIL PACKAGE
IMPLEMENTING DYNAMIC
POLYMORPHISM IN JAVA
JAVA INTERFACE FOR ADT
STACK
DNA FILE CREATION
DEVELOPING A SIMPLE PAINT LIKE
PROGRAM USING APPLET
DEVELOPING A SCIENTIFIC
CALCULATOR
DEVELOPING A TEMPLATE FOR
LINKED LIST
DEVELOP A MULTI THREADED
PRODUCER CONSUMER
APLICATION
GENERATING PRIME NUMBERS
AND FIBONACCI SERIES
MULTITHREADED GUI
APPLICATION
OPERATORS AND EXPRESSIONS
DECISION MAKING STRUCTURES
5
Page No
CONTENTS
6
10
13
16
19
23
26
31
42
44
47
50
54
56
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
Exercise Number: 1
Title of the exercise
: JAVA PACKAGE WITH SIMPLE STACK AND QUEUE CLASS
Date of the exercise
:
OBJECTIVE (AIM) OF THE EXPERIMENT
• To write program to develop a java package for the stack and queue classes.
FACILITIES REQUIRED AND PROCEDURE
a)
Facilities Required:
S.No.
Facilities required
Quantity
1
System
1
2
O/S
3
S/W name
Windows / Linux OS
JDK 1.6
b) Procedure:
Step
Details of the step
no.
STACK CLASS
Start the program.
1
Create a class with the class name Stack to demonstrate the application of the stack.
2
Create a constructor to initialize the top value of the stack.
3
Define the method push ().
4
If the top value is equal to 9, print stack is full. Otherwise push the value in to the
5
stack.
Define the method pop ().
6
If the top value is less than zero, print stack underflow. Otherwise decrement the
7
value of the stack.
Create a main class with the class name teststack.
8
Create an object for the class Stack to call the methods define inside that class.
9
Call the methods push () & pop () using the objects.
10
Stop the program.
11
QUEUE CLASS
Start the program.
1
Create a class with the name queue implement to demonstrate about a application of
2
queue.
Declare a variable str as string and num as integer.
3
Create an object for a class queue implement.
4
Create a constructor to of the Linked List class. This class is used by importing the
5
java.util. package. This constructor is used for constructing an empty list.
Get the value from the command line by using a variable str.
6
Using try and catch block to handle exception using IOException.
7
Print the elements in the queue using the statement.
8
Stop the program.
9
6
Dr.N.N.C.E
IT / V Sem
c)
Program:
Stack class:
package SQ;
import java.io.*;
class Stack{
int stck[]=new int[10];
int tos;
Stack(){
tos=-1;}
void push(int item)
{
if(tos==9)
System.out.println("Stack is full");
else
stck[++tos]=item;
}
int pop(){
if(tos<0){
System.out.println("Stack underflow");
return 0;}
else
return stck[tos--];}
}
class TestStack{
public static void main(String args[])
{
Stack mystack1=new Stack();
Stack mystack2=new Stack();
for(int i=0;i<10;i++)
mystack1.push(i);
for(int i=10;i<20;i++)
mystack2.push(i);
System.out.println("Stack in mystack1:");
for(int i=0;i<10;i++)
System.out.println(mystack1.pop());
System.out.println("Stack im mystack2");
for(int i=0;i<10;i++)
System.out.println(mystack2.pop());}
}
Queue class:
package SQ;
import java.io.*;
import java.io.*;
import java.util.*;
public class QueueImplement{
LinkedList<Integer> list;
String str;
int num;
7
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
public static void main(String[] args){
QueueImplement q = new QueueImplement();}
public QueueImplement(){
try{
list = new LinkedList<Integer>();
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader bf = new BufferedReader(ir);
System.out.println("Enter number of elements : ");
str = bf.readLine();
if((num = Integer.parseInt(str)) == 0){
System.out.println("You have entered either zero/null.");
System.exit(0);}
else{
System.out.println("Enter elements : ");
for(int i = 0; i < num; i++){
str = bf.readLine();
int n = Integer.parseInt(str);
list.add(n);}}
System.out.println("First element :" + list.removeFirst());
System.out.println("Last element :" + list.removeLast());
System.out.println("Rest elements in the list :");
while(!list.isEmpty()){
System.out.print(list.remove() + "\t");}}
catch(IOException e){
System.out.println(e.getMessage() + " is not a legal entry.");
System.exit(0);}}}
OUTPUT:
Stack class:
E:\SQ>path=C:\Program Files\Java\jdk1.5.0\bin
E:\SQ>set path=.;E:\;
E:\SQ>javac TestStack.java
E:\SQ>java SQ.TestStack
Stack in mystack1:
9
8
7
6
5
4
3
2
1
0
Stack in mystack2
19
18
17
16
15
14
8
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
13
12
11
10
Queue class:
E:\SQ>javac QueueImplement.java
E:\SQ>java SQ.QueueImplement
Enter number of elements :
4
Enter elements :
2
4
6
8
First element :2
Last element :8
Rest elements in the list :
4
6
d)
Result:
Thus the Stack and queue program was compiled and executed successfuly.
VIVA – QUESTIONS AND ANSWERS:
1. What is difference between Stack and Queue in java ?
S.NO
Stack
Queue
1.
A Stack represents a Collection of objects that
A Queue is also a Collection of Objects
are in LIFO (Last In First Out Order).
similar to a Stack.
The Stack class provides operations that allow
Queues typically order the elements
testing for zero elements, inspection of it's top
contained within in FIFO order but this
most element, removal of it's top most element,
is not always the case.
2.
and the addition of elements.
2. What is Stack?
A Stack is a first-in, last-out data structure that pops elements in the opposite order than
they were pushed. By default, a Stack uses an Array for its internal storage, although this can
easily be changed.
3. What is queue?
A Queue is a first-in, first-out data structure that pops elements in the same order than
they were pushed. By default, a Queue uses an SList for its internal storage, although this can
easily be changed.
9
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
Exercise Number: 2
Title of the exercise : COMPLEX NUMBER MANIPULATION
Date of the exercise :
OBJECTIVE (AIM) OF THE EXPERIMENT
•
To write a program to perform addition, subtraction, multiplication in complex numbers
using constructors.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.
Facilities required
Quantity
1
System
1
2
O/S
3
S/W name
Windows / Linux OS
JDK 1.6
b) Procedure:
Step no.
Details of the step
1
Start the program
2
Create a class with a class name Complex Number.
3
Create a constructor with the arguments a and b with integer data type.
4
Define a method getcomplexvalue( ) to get the values of a and b.
5
7
Define static method named as addition, subtraction,multiplication to
perform particular function defined inside the method.
Create an object for the class Complex Number and pass the values in the
argument list.
Call the method by using object to get the values.
8
Print the result.
9
Stop the program.
6
c) Program:/
import java.io.*;
public class ComplexNumber
{
private int a;
private int b;
public ComplexNumber(){
10
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
}
public ComplexNumber(int a, int b){
this.a =a;
this.b=b;
}
public String getComplexValue(){
if(this.b < 0){
return a+""+b+"i";
}
else{
return a+"+"+b+"i";}
}
public static String addition(ComplexNumber num1, ComplexNumber num2){
int a1= num1.a+num2.a;
int b1= num1.b+num2.b;
if(b1<0){
return a1+""+b1+"i";
} else {
return a1+"+"+b1+"i";}
}
public static String substraction(ComplexNumber num1, ComplexNumber num2){
int a1= num1.a-num2.a;
int b1= num1.b-num2.b;
if(b1<0){
return a1+""+b1+"i";
} else {
return a1+"+"+b1+"i";}
}
public static String multiplication(ComplexNumber num1, ComplexNumber num2){
int a1= num1.a*num2.a;
int b1= num1.b*num2.b;
int vi1 = num1.a * num2.b;
int vi2 = num2.a * num1.b;
int vi;
vi=vi1+vi2;
if(vi<0){
return a1-b1+""+vi+"i";
} else {
return a1-b1+"+"+vi+"i";}
}
public static void main(String args[]){
ComplexNumber com1 = new ComplexNumber(-2,-3);
ComplexNumber com2 = new ComplexNumber(-4,-5);
System.out.println(com1.getComplexValue());
System.out.println(com2.getComplexValue());
System.out.println("Addition of both Complex Numbers are :"
+ComplexNumber.addition(com1,com2));
System.out.println("Substraction of both Complex Numbers are :"
+ComplexNumber.substraction(com1,com2));
11
Dr.N.N.C.E
IT / V Sem
System.out.println("Multiplication of both Complex Numbers are :"
+ComplexNumber.multiplication(com1,com2));
}}
JP Lab - LM
OUTPUT:
E:\Javaexecute>javac ComplexNumber.java
E:\Javaexecute>java ComplexNumber
-2-3i
-4-5i
Addition of both Complex Numbers are :-6-8i
Substraction of both Complex Numbers are :2+2i
Multiplication of both Complex Numbers are :-7+22i 16
d)
Result:
Thus the complex number program was executed and compiled successfuly.
/CDlgDlg.cpp
VIVA – QUESTIONS AND ANSWERS:
1.
What's the difference between J2SDK 1.5 and J2SDK 5.0?
There's no difference, Sun Microsystems just re-branded this version.
2.
Can an inner class declared inside of a method access local variables of this
method?
It's possible if these variables are final.
3. Define Encapsulation.
Java encapsulation is a programming concept that a language should support in
order toobject's state from its behavior. This is typically facilitated by means of hiding an
object's data representing its state from modification by external components.
4. What is the need for Java Language?
Java is a programming language and computing platform first released by Sun
Microsystems in 1995. There are lots of applications and websites that will not work unless
you have Java installed, and more are created every day. Java is fast, secure, and reliable.
5. What is the difference between C++ and Java?
•
•
•
Both C++ and Java use similar syntax and are Object Oriented,
Java does not support pointers. Pointers are inherently tricky to use and troublesome.
Java does not support multiple inheritances because it causes more problems than it solves.
Instead Java supports multiple interface inheritance, which allows an object to inherit many
method signatures from different interfaces with the condition that the inheriting object
must implement those inherited methods.
12
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
Exercise Number: 3
Title of the exercise
:
Date of the exercise
:
DATE CLASS SIMILAR TO JAVA.UTIL PACKAGE
OBJECTIVE (AIM) OF THE EXPERIMENT
•
To write a java program to display the dates of before and after days for a given date.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.
Facilities required
Quantity
1
System
1
2
O/S
3
S/W name
Windows / Linux OS
JDK 1.6
b) Procedure:
Step no.
Details of the step
1
Start the program.
2
Create a class with name Date
3
5
Declare the variables month, day, year as private and create constructor
with arguments.
Check the condition for exception. If the date is valid, It will proceed the
program otherwise display the exception “Invalid”.
Use Boolean type for method to return the values as either true or false.
6
Check the values for month and values for day using if loops.
7
Check the year using if loop whether it is leap year or not.
8
Define methods isAfter() and isBefore() in program.
9
Define method compareTo() to compare the date.
10
In main() create object today and give current date as value for
constructor fields
Call the all methods to display the dates.
4
11
c) Program:
import java.io.*;
public class Date {
private final int month;
private final int day;
13
Dr.N.N.C.E
IT / V Sem
private final int year;
public Date(int m, int d, int y) {
if (!isValid(m, d, y))
throw new RuntimeException("Invalid");
month = m;
day = d;
year = y;
}
private static boolean isValid(int m, int d, int y) {
int[] DAYS = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (m < 1 || m > 12)
return false;
if (d < 1 || d > DAYS[m])
return false;
if (m == 2 && d == 29 && !isLeapYear(y))
return false;
return true;
}
private static boolean isLeapYear(int y) {
if (y % 400 == 0)
return true;
if (y % 100 == 0)
return false;
return (y % 4 == 0);
}
public Date next() {
if (isValid(month, day + 1, year))
return new Date(month, day + 1, year);
else if (isValid(month + 1, 1, year))
return new Date(month + 1, 1, year);
else
return new Date(1, 1, year + 1);
}
public boolean isAfter(Date b) {
return compareTo(b) > 0;
}
public boolean isBefore(Date b) {
return compareTo(b) < 0;
}
public int compareTo(Date b) {
if (year != b.year)
return year - b.year;
if (month != b.month)
return month - b.month;
return day - b.day;
}
public String toString() {
return day + "-" + month + "-" + year;
}
public static void main(String[] args) {
14
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
Date today = new Date(7, 12, 2010);
System.out.println(today);
Date nextDate = today.next();
System.out.println(nextDate);
System.out.println(today.isAfter(nextDate));
System.out.println(today.next().isAfter(today));
System.out.println(today.isBefore(nextDate));
System.out.println(nextDate.compareTo(today));
}
}
OUTPUT:
20-7-2011
21-7-2011
false
true
true
d)
JP Lab - LM
Result:
Thus the Date class program was compiled and executed successfuly.
VIVA – QUESTIONS AND ANSWERS:
1. What's the difference between an interface and an abstract class?
An abstract class may contain code in method bodies, which is not allowed in an
interface. With abstract classes, you have to inherit your class from it and Java does not
allow multiple inheritance. On the other hand, you can implement multiple interfaces in
your class.
2. How can you force garbage collection?
We can't force Garbage Collection, but could request it by calling System.gc().
JVM does not guarantee that Garbage Collection will be started immediately.
3. Explain the usage of Java packages.
This is a way to organize files when a project consists of multiple modules. It also
helps resolve naming conflicts when different packages have classes with the same names.
Packages access level also allows you to protect data from being used by the non-authorized
classes.
15
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
Exercise Number: 4
Title of the exercise
: IMPLEMENTING DYNAMIC POLYMORPHISM IN JAVA
Date of the exercise
:
OBJECTIVE (AIM) OF THE EXPERIMENT
•
To write a java program for abstract class to find areas of different shapes.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.
Facilities required
Quantity
1
System
1
2
O/S
3
S/W name
Windows / Linux OS
JDK 1.6
b) Procedure:
Step
Details of the step
no.
1
Start the program.
2
Create an abstract class with class name Shape.
3
Create a constructor with arguments and declare variables dim1, dim2 and PI.
4
Declare an abstract method area() inside the class.
5
Create the classes Rectangle, Triangle, Circle, and Ellipse to find the area.
6
7
Define abstract method area() inside the subclasses and call the constructor of class
Shape using super keyword.
In main(), create the objects for all classes and pass values to fields of constructors.
8
Create a reference variable figuref for abstract class.
9
Using reference variable of class Shape, call the method area() of all subclasses
10
Print the areas for all shapes.
11
Stop the program.
c) Program:enuDoc.cpp
import java.io.*;
abstract class Shape
{
16
Dr.N.N.C.E
IT / V Sem
double dim1;
double dim2;
double PI=3.14;
Shape(double a, double b)
{
dim1 = a;
dim2 = b; }
abstract double area(); }
class Rectangle extends Shape {
Rectangle(double a, double b) {
super(a, b); }
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2; } }
class Triangle extends Shape{
Triangle(double a, double b){
super(a, b); }
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2; } }
class Circle extends Shape {
Circle(double a, double b){
super(a, b); }
double area(){
System.out.println("Inside Area for Circle.");
return PI * dim1 * dim1; }}
class Ellipse extends Shape {
Ellipse(double a, double b) {
super(a, b); }
double area() {
System.out.println("Inside Area for Ellipse.");
return PI * dim1 * dim2;}}
class Square extends Shape {
Square(double a, double b) {
super(a, b); }
double area() {
System.out.println("Inside Area for Square.");
return dim1 * dim1; }}
class AbstractAreas {
public static void main(String args[]) {
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Circle c=new Circle(5,5);
Ellipse e=new Ellipse(7,7);
Square s=new Square(6,6);
Shape figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
17
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
figref = c;
System.out.println("Area is " + figref.area());
figref = e;
System.out.println("Area is " + figref.area());
figref = s;
System.out.println("Area is " + figref.area());}
}
OUTPUT:
E:\SQ>java AbstractAreas
Inside Area for Rectangle.
Area is 45.0
Inside Area for Triangle.
Area is 40.0
Inside Area for Circle.
Area is 78.5
Inside Area for Ellipse.
Area is 153.86
Inside Area for Square.
Area is 36.0
d)
Result:
Thus the Dynamic polymorphism was compiled and executed successfuly.
VIVA – QUESTIONS AND ANSWERS:
1. What do you mean by polymorphism?
Polymorphism – means the ability of a single variable of a given type to be
used to reference objects of different types, and automatically call the method that is
specific to the type of object the variable references.
2. Give the benefit of polymorphism?
The benefit of polymorphism is that it is very easy to add new classes of
derived objects without breaking the calling code (i.e. getTotArea() in the sample code
shown below) that uses the polymorphic classes or interfaces.
3. What do you mean by Inheritance?
Inheritance – is the inclusion of behaviour (i.e. methods) and state (i.e.
variables) of a base class in a derived class so that they are accessible in that derived class.
4. What do you mean by Encapsulation?
Encapsulation – refers to keeping all the related members (variables and
methods) together in an object. Specifying members as private can hide the variables and
methods.
5. What are the benefits of the Java collection framework?
Collection framework provides flexibility, performance, and robustness.
1. Polymorphic algorithms – sorting, shuffling, reversing, binary search etc.
2. Set algebra - such as finding subsets, intersections, and unions between objects.
18
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
Exercise Number: 5
Title of the exercise
: JAVA INTERFACE FOR ADT STACK
Date of the exercise
:
OBJECTIVE (AIM) OF THE EXPERIMENT
•
To write the java program for ADT stack using interface.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.
Facilities required
Quantity
1
System
1
2
O/S
3
S/W name
Windows / Linux OS
JDK 1.6
b) Procedure:
Step no.
Details of the step
1
Start the program
2
Create an interface which consists of three methods namely PUSH, POP
and DISPLAY
Create a class which implements the above interface to implement the
concept of stack through Array
Define all the methods of the interface to push any element, to pop the to
element and to display the elements present in the stack.
Create another class which implements the same interface to implement
the concept of stack through linked list.
Repeat STEP 4 for the above said class also.
3
4
5
6
7
9
In the main class, get the choice from the user to choose whether array
implementation or linked list implementation of the stack.
Call the methods appropriately according to the choices madeby the user
in the previous step.
Repeat step 6 and step 7 until the user stops his/her execution
10
Stop the program
8
19
Dr.N.N.C.E
IT / V Sem
c) Program:
import java.lang.*;
import java.io.*;
import java.util.*;
interface Mystack
{
int n=10;
public void pop();
public void push();
public void peek();
public void display();}
class Stackimp implements Mystack{
int stack[]=new int[n];
int top=-1;
public void push(){
try{
DataInputStream dis=new DataInputStream(System.in);
if(top==(n-1)){
System.out.println("overflow");
return;}
else{
System.out.println("enter element");
int ele=Integer.parseInt(dis.readLine());
stack[++top]=ele;}}
catch(Exception e){
System.out.println("e");}}
public void pop(){
if(top<0){
System.out.println("underflow");
return;}
else{
int popper=stack[top];
top--;
System.out.println("popped element" +popper);}}
public void peek(){
if(top<0){
System.out.println("underflow");
return;}
else{
int popper=stack[top];
System.out.println("popped element" +popper);}}
public void display(){
if(top<0){
System.out.println("empty");
return;}
else{
String str=" ";
for(int i=0;i<=top;i++)
20
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
str=str+" "+stack[i];
System.out.println("elements are"+str);}}}
class Stackadt{
public static void main(String arg[])throws IOException{
DataInputStream dis=new DataInputStream(System.in);
Stackimp stk=new Stackimp();
int ch=0;
do{
System.out.println("enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit");
ch=Integer.parseInt(dis.readLine());
switch(ch){
case 1:stk.push();
break;
case 2:stk.pop();
break;
case 3:stk.peek();
break;
case 4:stk.display();
break;
case 5:System.exit(0);}
}while(ch<=5);}}
OUTPUT:
E:\SQ>java Stackadt
enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit
1
enter element
4
enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit
1
enter element
5
enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit
1
enter element
7
enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit
4
elements are 4 5 7
enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit
1
enter element
8
enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit
2
popped element8
enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit
4
elements are 4 5 7
enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit
21
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
3
popped element7
enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit
4
elements are 4 5 7
enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit
5
d)
Result:
Thus the Interface for ADT stack program was compiled and executed successfuly.
VIVA – QUESTIONS AND ANSWERS:
1. What is the purpose of Void class?
The Void class is an uninstantiable placeholder class to hold a reference to the Class
object representing the primitive Java type void.
2. Define an interface.
Interface in java is core part of Java programming language and one of the way to
achieve abstraction in Java along with abstract class
3. What is the need for an interface?
The main use is polymorphism, or the ability to perform the same operation on a
number of different objects. If different objects all implement the same interface and have
the same method, you can store all of those objects in a Vector, for example, and iterate
through the Vector calling that method on each one.
4. What is object cloning?
Cloning means creating a copy of the object. The precise meaning of "copy" may
depend on the class of the object. The general intent is that, for any object x, the expression:
x.clone() != x
5. How will you create an instance of Class.
There are two reflective methods for creating instances of classes:
•
•
java.lang.reflect.Constructor.newInstance()
Class.newInstance().
22
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
Exercise Number: 6
Title of the exercise
: DNA File Creation
Date of the exercise
:
OBJECTIVE (AIM) OF THE EXPERIMENT
•
To write a Java program to read a file that contains DNA sequences of arbitrary length one
per line, sort the sequences in descending order with respect to the number of 'TATA'
subsequences present and finally write the sequences in sorted order into another file.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.
Facilities required
Quantity
1
System
1
2
O/S
3
S/W name
Windows / Linux OS
JDK 1.6
b) Procedure:
Step no.
Details of the step
1
Start the program.
2
Create an input text file “DNA.txt” and add the sequence as needed.
3
Read each line from the file to a string array.
4
6
Count the number of TATA sequence in each line and store the count in
another array.
Arrange the data in the count array in descending order and also arrange
the data in the string array in parallel with the count array.
Write the sorted DNA sequence to the output file “File.txt”
7
View the output file.
8
Stop the program.
5
c) Program:/
import java.util.*;
import java.io.*;
import java.util.Arrays;
import java.util.Collections;
class FileDemo
{
public static void main(String args[])throws IOException
{
23
Dr.N.N.C.E
IT / V Sem
String fileLine[] = new String[6];
BufferedReader br = new BufferedReader(new FileReader("dna.txt"));
int i=0,z=0,k=0;;
int[] count =new int[6];
int[] order =new int[6];
int result=0;
String searchFor = "tata";
int len = searchFor.length();
System.out.println ("Reading data from DNA file............. ");
while ((fileLine[k]=br.readLine()) != null )
{
result=0;
if (len > 0)
{
int start = fileLine[k].indexOf(searchFor);
while (start != -1)
{
result++;
start = fileLine[k].indexOf(searchFor, start+len);
count[k]=result;
z++;
}
}
if(k<5)
k++;
else
break;
}
int temp,j;
String temps;
System.out.println ("Swapping data from DNA file............. ");
for(i=0;i<(count.length-1);i++)
{
for(j=i;j<=(count.length-1);j++)
{
if(count[i]<count[j])
{
temp=count[i];
count[i]=count[j];
count[j]=temp;
temps=fileLine[i];
fileLine[i]=fileLine[j];
fileLine[j]=temps;
}
}
}
System.out.println ("Writing Sorted DNA sequence to Output file................. ");
try {
BufferedWriter writer=new BufferedWriter(new FileWriter("file1.txt"));
for(i=0;i<6;i++)
24
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
{
writer.write(fileLine[i]);
writer.newLine();
}
writer.close();
System.out.println ("Writing of Sorted DNA sequence to Output file has been
completed................. ");
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
Input:
/*dna.txt*/
attaaattaaaaaaaattata
aaaaaaacatcgtaaa
tcaatatatataat
Output:
C:\Program Files\Java\jdk1.6.0\bin>javac FileDemo.java
C:\Program Files\Java\jdk1.6.0\bin>java FileDemo
Reading data from DNA file.............
Swapping data from DNA file.............
Writing Sorted DNA sequence to Output file.................
Writing of Sorted DNA sequence to Output file has been completed................
/*File.txt*/
tcaatatatataat
attaaattaaaaaaaattata
aaaaaaacatcgtaaa
d)
Result:
Thus the DNA sequences were read sorted and output was given to an output file.
VIVA – QUESTIONS AND ANSWERS:
1. What is the difference between instanceof and isInstance?
instanceof is used to check to see if an object can be cast into a specified type
without throwing a cast class exception. isInstance() determines if the specified object is
assignment compatible with the object represented by this Class.
2. Can applets communicate with each other?
Applets may communicate with other applets running in the same virtual machine. If
the applets are of the same class, they can communicate via shared static variables.
3. What are wrapper classes? Why do we need wrapper classes?
Java provides specialized classes corresponding to each of the primitive data types.
These are called wrapper classes. They are e.g. Integer, Character, Double etc.
4. What are the usages of Java packages?
It helps resolve naming conflicts when different packages have classes with the
same names. This also helps you organize files within your project. For example: java.io
package do something related to I/O and java.net package do something to do with network
and so on.
25
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
Exercise Number: 7
Title of the exercise
Date of the exercise
: DEVELOPING A SIMPLE PAINT LIKE PROGRAM USING APPLET
:
OBJECTIVE (AIM) OF THE EXPERIMENT
•
To develop a simple paint like program using applet in java.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.
Facilities required
Quantity
1
System
1
2
O/S
3
S/W name
Windows / Linux OS
JDK 1.6
b) Procedure:
Step
no.
1
Details of the step
Import the required class and packages.
2
Create a class Drawtest for creating an applet.
3
Initialize panles and controls in the init() method.
4
Define the destroy() method to destroy the same.
5
6
Create an instance for draw test class and call the init(0 and start() methods in the
main method.
Add a new frame to the applet window and resize it to 300x300.
7
Declare a method get applet infor to display the applet information.
8
Declare two constants LINES,POINTS which are going to be the modes.
9
Define the paint method and perfoem the required operations.
10
Display the result according to the mode selected.
c) Program:/SDIserializeDoc.cpp
import java.awt.event.*;
import java.awt.*;
import java.applet.*;
import java.util.Vector;
public class DrawTest extends Applet{
DrawPanel panel;
DrawControls controls;
public void init() {
setLayout(new BorderLayout());
26
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
panel = new DrawPanel();
controls = new DrawControls(panel);
add("Center", panel);
add("South",controls); }
public void destroy() {
remove(panel);
remove(controls); }
public static void main(String args[]) {
Frame f = new Frame("DrawTest");
DrawTest drawTest = new DrawTest();
drawTest.init();
drawTest.start();
f.add("Center", drawTest);
f.setSize(300, 300);
f.show(); }
public String getAppletInfo() {
return "A simple drawing program.";}}
class DrawPanel extends Panel implements MouseListener, MouseMotionListener {
public static final int LINES = 0;
public static final int POINTS = 1;
int mode = LINES;
Vector lines = new Vector();
Vector colors = new Vector();
int x1,y1;
int x2,y2;
public DrawPanel() {
setBackground(Color.white);
addMouseMotionListener(this);
addMouseListener(this);}
public void setDrawMode(int mode) {
switch (mode) {
case LINES:
case POINTS:
this.mode = mode;
break;
default:
throw new IllegalArgumentException();}}
public void mouseDragged(MouseEvent e) {
e.consume();
switch (mode) {
case LINES:
x2 = e.getX();
y2 = e.getY();
break;
case POINTS:
default:
colors.addElement(getForeground());
lines.addElement(new Rectangle(x1, y1, e.getX(), e.getY()));
x1 = e.getX();
y1 = e.getY();
27
Dr.N.N.C.E
IT / V Sem
break; }
repaint();}
public void mouseMoved(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
e.consume();
switch (mode) {
case LINES:
x1 = e.getX();
y1 = e.getY();
x2 = -1;
break;
case POINTS:
default:
colors.addElement(getForeground());
lines.addElement(new Rectangle(e.getX(), e.getY(), -1, -1));
x1 = e.getX();
y1 = e.getY();
repaint();
break;} }
public void mouseReleased(MouseEvent e) {
e.consume();
switch (mode) {
case LINES:
colors.addElement(getForeground());
lines.addElement(new Rectangle(x1, y1, e.getX(), e.getY()));
x2 = -1;
break;
case POINTS:
default:
break; }
repaint(); }
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void paint(Graphics g) {
int np = lines.size();
g.setColor(getForeground());
for (int i=0; i < np; i++) {
Rectangle p = (Rectangle)lines.elementAt(i);
g.setColor((Color)colors.elementAt(i));
if (p.width != -1) {
g.drawLine(p.x, p.y, p.width, p.height);
} else {
g.drawLine(p.x, p.y, p.x, p.y); }}
if (mode == LINES) {
g.setColor(getForeground());
28
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
if (x2 != -1) {
g.drawLine(x1, y1, x2, y2);}} }}
class DrawControls extends Panel implements ItemListener {
DrawPanel target;
public DrawControls(DrawPanel target) {
this.target = target;
setLayout(new FlowLayout());
setBackground(Color.lightGray);
target.setForeground(Color.red);
CheckboxGroup group = new CheckboxGroup();
Checkbox b;
add(b = new Checkbox(null, group, false));
b.addItemListener(this);
b.setForeground(Color.red);
add(b = new Checkbox(null, group, false));
b.addItemListener(this);
b.setForeground(Color.green);
add(b = new Checkbox(null, group, false));
b.addItemListener(this);
b.setForeground(Color.blue);
add(b = new Checkbox(null, group, false));
b.addItemListener(this);
b.setForeground(Color.pink);
add(b = new Checkbox(null, group, false));
b.addItemListener(this);
b.setForeground(Color.orange);
add(b = new Checkbox(null, group, true));
b.addItemListener(this);
b.setForeground(Color.black);
target.setForeground(b.getForeground());
Choice shapes = new Choice();
shapes.addItemListener(this);
shapes.addItem("Lines");
shapes.addItem("Points");
shapes.setBackground(Color.lightGray);
add(shapes); }
public void paint(Graphics g) {
Rectangle r = getBounds();
g.setColor(Color.lightGray);
g.draw3DRect(0, 0, r.width, r.height, false);
int n = getComponentCount();
for(int i=0; i<n; i++) {
Component comp = getComponent(i);
if (comp instanceof Checkbox) {
Point loc = comp.getLocation();
Dimension d = comp.getSize();
g.setColor(comp.getForeground());
g.drawRect(loc.x-1, loc.y-1, d.width+1, d.height+1);} } }
public void itemStateChanged(ItemEvent e) {
if (e.getSource() instanceof Checkbox) {
29
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
target.setForeground(((Component)e.getSource()).getForeground());
} else if (e.getSource() instanceof Choice) {
String choice = (String) e.getItem();
if (choice.equals("Lines")) {
target.setDrawMode(DrawPanel.LINES);
} else if (choice.equals("Points")) {
target.setDrawMode(DrawPanel.POINTS);
}
}
}
}
OUTPUT:
JP Lab - LM
d)
Result:
Thus the Applet-Paint program was compiled and executed successfuly.
VIVA – QUESTIONS:
1. When will a class be declared as final?
A compile-time error occurs if a class is declared both final and abstract, because the
implementation of such a class could never be completed.Because a final class never has
any subclasses, the methods of a final class are never overridden.
2. When will a method be declared final?
We declare a method final in java when we don’t want any subclasses of the class to
be able to override the method.
3. What are the methods under "object" class / java.lang.Object.
[Ljava.lang.Object; is the name for Object[].class, the java.lang.Class representing
the class of array of Object.
4. What is reflection?
Reflection is a process that is used to examine the runtime behaviour of a running
application in the JVM. Reflection API allows the creation of an instance of a class whose
name is not known until runtime.
30
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
Exercise Number: 8
Title of the exercise : DEVELOPING A SCIENTIFIC CALCULATOR
Date of the exercise :
OBJECTIVE (AIM) OF THE EXPERIMENT
• To develop a scientific calculator in java.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.
Facilities required
Quantity
1
System
1
2
O/S
3
S/W name
Windows / Linux OS
JDK 1.6
b) Procedure:
Step no.
Details of the step
1
Import the necessary packages.
2
Create a class calculator JFrame class and ActionListener interface.
3
Create a new font using String name,int style,int size).
4
6
Set up the JMenu bar and add Mnemenics to them by using
setMnemonic() method.
Set the frame layout for the applet and set the background color to gray
using setBackground() method .
Create a container using JPanel().
7
Create numeric JButtons for operators and numbers using JButtons().
8
9
Set all the Numbered JButtons to blue .the rest to red usig
setForeGround() method.
Declare the method getNumberInDisplay() to get by the calculator.
10
Use display result to display the method.
11
Declare the main function and create the instance for calculator and set
the attributes setTitle(),setSize(),setResizable().
Stop the program.
5
12
c) Program:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener{
31
Dr.N.N.C.E
IT / V Sem
final int MAX_INPUT_LENGTH = 20;
final int INPUT_MODE = 0;
final int RESULT_MODE = 1;
final int ERROR_MODE = 2;
int displayMode;
boolean clearOnNextDigit, percent;
double lastNumber;
String lastOperator;
private JMenu jmenuFile, jmenuHelp;
private JMenuItem jmenuitemExit, jmenuitemAbout;
private JLabel jlbOutput;
private JButton jbnButtons[];
private JPanel jplMaster, jplBackSpace, jplControl;
Font f12 = new Font("Times New Roman", 0, 12);
Font f121 = new Font("Times New Roman", 1, 12);
public Calculator()
{
jmenuFile = new JMenu("File");
jmenuFile.setFont(f121);
jmenuFile.setMnemonic(KeyEvent.VK_F);
jmenuitemExit = new JMenuItem("Exit");
jmenuitemExit.setFont(f12);
jmenuitemExit.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_X,
ActionEvent.CTRL_MASK));
jmenuFile.add(jmenuitemExit);
jmenuHelp = new JMenu("Help");
jmenuHelp.setFont(f121);
jmenuHelp.setMnemonic(KeyEvent.VK_H);
jmenuitemAbout = new JMenuItem("About Calculator");
jmenuitemAbout.setFont(f12);
jmenuHelp.add(jmenuitemAbout);
JMenuBar mb = new JMenuBar();
mb.add(jmenuFile);
mb.add(jmenuHelp);
setJMenuBar(mb);
setBackground(Color.gray);
jplMaster = new JPanel();
jlbOutput = new JLabel("0");
jlbOutput.setHorizontalTextPosition(JLabel.RIGHT);
jlbOutput.setBackground(Color.WHITE);
jlbOutput.setOpaque(true);
getContentPane().add(jlbOutput, BorderLayout.NORTH);
jbnButtons = new JButton[23];
JPanel jplButtons = new JPanel(); // container for Jbuttons
for (int i=0; i<=9; i++)
{
jbnButtons[i] = new JButton(String.valueOf(i));
}
jbnButtons[10] = new JButton("+/-");
jbnButtons[11] = new JButton(".");
32
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
jbnButtons[12] = new JButton("=");
jbnButtons[13] = new JButton("/");
jbnButtons[14] = new JButton("*");
jbnButtons[15] = new JButton("-");
jbnButtons[16] = new JButton("+");
jbnButtons[17] = new JButton("sqrt");
jbnButtons[18] = new JButton("1/x");
jbnButtons[19] = new JButton("%");
jplBackSpace = new JPanel();
jplBackSpace.setLayout(new GridLayout(1, 1, 2, 2));
jbnButtons[20] = new JButton("Backspace");
jplBackSpace.add(jbnButtons[20]);
jplControl = new JPanel();
jplControl.setLayout(new GridLayout(1, 2, 2 ,2));
jbnButtons[21] = new JButton(" CE ");
jbnButtons[22] = new JButton("C");
jplControl.add(jbnButtons[21]);
jplControl.add(jbnButtons[22]);
for (int i=0; i<jbnButtons.length; i++) {
jbnButtons[i].setFont(f12);
if (i<10)
jbnButtons[i].setForeground(Color.blue);
else
jbnButtons[i].setForeground(Color.red);
}
jplButtons.setLayout(new GridLayout(4, 5, 2, 2));
for(int i=7; i<=9; i++) {
jplButtons.add(jbnButtons[i]);
}
jplButtons.add(jbnButtons[13]);
jplButtons.add(jbnButtons[17]);
for(int i=4; i<=6; i++)
{
jplButtons.add(jbnButtons[i]);
}
jplButtons.add(jbnButtons[14]);
jplButtons.add(jbnButtons[18]);
for( int i=1; i<=3; i++)
{
jplButtons.add(jbnButtons[i]);
}
jplButtons.add(jbnButtons[15]);
jplButtons.add(jbnButtons[19]);
jplButtons.add(jbnButtons[0]);
jplButtons.add(jbnButtons[10]);
jplButtons.add(jbnButtons[11]);
jplButtons.add(jbnButtons[16]);
jplButtons.add(jbnButtons[12]);
jplMaster.setLayout(new BorderLayout());
jplMaster.add(jplBackSpace, BorderLayout.WEST);
33
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
jplMaster.add(jplControl, BorderLayout.EAST);
jplMaster.add(jplButtons, BorderLayout.SOUTH);
getContentPane().add(jplMaster, BorderLayout.SOUTH);
requestFocus();
for (int i=0; i<jbnButtons.length; i++){
jbnButtons[i].addActionListener(this);
}
jmenuitemAbout.addActionListener(this);
jmenuitemExit.addActionListener(this);
clearAll();
addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e)
{
System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent e){
double result = 0;
if(e.getSource() == jmenuitemAbout){
JDialog dlgAbout = new CustomABOUTDialog(this,
"About Java Swing Calculator",
true);
dlgAbout.setVisible(true);
}else if(e.getSource() == jmenuitemExit){
System.exit(0);
}
for (int i=0; i<jbnButtons.length; i++)
{
if(e.getSource() == jbnButtons[i])
{
switch(i)
{
case 0:
addDigitToDisplay(i);
break;
case 1:
addDigitToDisplay(i);
break;
case 2:
addDigitToDisplay(i);
break;
case 3:
addDigitToDisplay(i);
break;
case 4:
addDigitToDisplay(i);
break;
case 5:
34
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
addDigitToDisplay(i);
break;
case 6:
addDigitToDisplay(i);
break;
case 7:
addDigitToDisplay(i);
break;
case 8:
addDigitToDisplay(i);
break;
case 9:
addDigitToDisplay(i);
break;
case 10: // +/processSignChange();
break;
case 11: // decimal point
addDecimalPoint();
break;
case 12: // =
processEquals();
break;
case 13: // divide
processOperator("/");
break;
case 14: // *
processOperator("*");
break;
case 15: // processOperator("-");
break;
case 16: // +
processOperator("+");
break;
case 17: // sqrt
if (displayMode != ERROR_MODE)
{
try
{
if (getDisplayString().indexOf("-") == 0)
displayError("Invalid input for function!");
result = Math.sqrt(getNumberInDisplay());
displayResult(result);
}
catch(Exception ex)
{
displayError("Invalid input for function!");
displayMode = ERROR_MODE;
}
35
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
}
break;
case 18: // 1/x
if (displayMode != ERROR_MODE){
try
{
if (getNumberInDisplay() == 0)
displayError("Cannot divide by zero!");
result = 1 / getNumberInDisplay();
displayResult(result);
}
catch(Exception ex) {
displayError("Cannot divide by zero!");
displayMode = ERROR_MODE;
}
}
break;
case 19: // %
if (displayMode != ERROR_MODE){
try {
result = getNumberInDisplay() / 100;
displayResult(result);
}
catch(Exception ex) {
displayError("Invalid input for function!");
displayMode = ERROR_MODE;
}
}
break;
case 20: // backspace
if (displayMode != ERROR_MODE){
setDisplayString(getDisplayString().substring(0,getDisplayString().length() 1));
if (getDisplayString().length() < 1)
setDisplayString("0");
}
break;
case 21: // CE
clearExisting();
break;
case 22: // C
clearAll();
break;
}
}
}
}
void setDisplayString(String s){
jlbOutput.setText(s);
}
36
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
String getDisplayString (){
return jlbOutput.getText();
}
void addDigitToDisplay(int digit){
if (clearOnNextDigit)
setDisplayString("");
String inputString = getDisplayString();
if (inputString.indexOf("0") == 0){
inputString = inputString.substring(1);
}
if ((!inputString.equals("0") || digit > 0) && inputString.length() < MAX_INPUT_LENGTH)
{
setDisplayString(inputString + digit);
}
displayMode = INPUT_MODE;
clearOnNextDigit = false;
}
void addDecimalPoint(){
displayMode = INPUT_MODE;
if (clearOnNextDigit)
setDisplayString("");
String inputString = getDisplayString();
if (inputString.indexOf(".") < 0)
setDisplayString(new String(inputString + "."));
}
void processSignChange(){
if (displayMode == INPUT_MODE)
{
String input = getDisplayString();
if (input.length() > 0 && !input.equals("0"))
{
if (input.indexOf("-") == 0)
setDisplayString(input.substring(1));
else
setDisplayString("-" + input);
}
}
else if (displayMode == RESULT_MODE)
{
double numberInDisplay = getNumberInDisplay();
if (numberInDisplay != 0)
displayResult(-numberInDisplay);
}
}
void clearAll() {
setDisplayString("0");
lastOperator = "0";
lastNumber = 0;
displayMode = INPUT_MODE;
clearOnNextDigit = true;
37
Dr.N.N.C.E
IT / V Sem
}
void clearExisting(){
setDisplayString("0");
clearOnNextDigit = true;
displayMode = INPUT_MODE;
}
double getNumberInDisplay() {
String input = jlbOutput.getText();
return Double.parseDouble(input);
}
void processOperator(String op) {
if (displayMode != ERROR_MODE)
{
double numberInDisplay = getNumberInDisplay();
if (!lastOperator.equals("0"))
{
try
{
double result = processLastOperator();
displayResult(result);
lastNumber = result;
}
catch (DivideByZeroException e)
{
}
}
else
{
lastNumber = numberInDisplay;
}
clearOnNextDigit = true;
lastOperator = op;
}
}
void processEquals(){
double result = 0;
if (displayMode != ERROR_MODE){
try
{
result = processLastOperator();
displayResult(result);
}
catch (DivideByZeroException e) {
displayError("Cannot divide by zero!");
}
lastOperator = "0";
}
}
double processLastOperator() throws DivideByZeroException {
double result = 0;
38
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
double numberInDisplay = getNumberInDisplay();
if (lastOperator.equals("/"))
{
if (numberInDisplay == 0)
throw (new DivideByZeroException());
result = lastNumber / numberInDisplay;
}
if (lastOperator.equals("*"))
result = lastNumber * numberInDisplay;
if (lastOperator.equals("-"))
result = lastNumber - numberInDisplay;
if (lastOperator.equals("+"))
result = lastNumber + numberInDisplay;
return result;
}
void displayResult(double result){
setDisplayString(Double.toString(result));
lastNumber = result;
displayMode = RESULT_MODE;
clearOnNextDigit = true;
}
void displayError(String errorMessage){
setDisplayString(errorMessage);
lastNumber = 0;
displayMode = ERROR_MODE;
clearOnNextDigit = true;
}
public static void main(String args[]) {
Calculator calci = new Calculator();
Container contentPane = calci.getContentPane();
calci.setTitle("Java Swing Calculator");
calci.setSize(241, 217);
calci.pack();
calci.setLocation(400, 250);
calci.setVisible(true);
calci.setResizable(false);
}
} class DivideByZeroException extends Exception{
public DivideByZeroException()
{
super();
}
public DivideByZeroException(String s)
{
super(s);
}
}
class CustomABOUTDialog extends JDialog implements ActionListener {
JButton jbnOk;
CustomABOUTDialog(JFrame parent, String title, boolean modal){
39
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
super(parent, title, modal);
setBackground(Color.black);
JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
StringBuffer text = new StringBuffer();
text.append("Calculator Information\n\n");
text.append("Developer: Hemanth\n");
text.append("Version: 1.0");
JTextArea jtAreaAbout = new JTextArea(5, 21);
jtAreaAbout.setText(text.toString());
jtAreaAbout.setFont(new Font("Times New Roman", 1, 13));
jtAreaAbout.setEditable(false);
76 www.eeeexclusive.blogspot.com
p1.add(jtAreaAbout);
p1.setBackground(Color.red);
getContentPane().add(p1, BorderLayout.CENTER);
JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
jbnOk = new JButton(" OK ");
jbnOk.addActionListener(this);
p2.add(jbnOk);
getContentPane().add(p2, BorderLayout.SOUTH);
setLocation(408, 270);
setResizable(false);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
Window aboutDialog = e.getWindow();
aboutDialog.dispose();
}
}
);
pack();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == jbnOk) {
this.dispose();
}
}
}
40
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
OUTPUT:
d)
Result:
Thus the Scientific calculator program was compiled and executed successfuly.
VIVA – QUESTIONS AND ANSWERS:
1. How dynamic initialization of variables is achieved in java.
Java allows variables to be initialized dynamically, using any expression valid at
the time the variable is declared. double a= 3.0,b=4.0 double c=Math.sqrt( a * a + b * b);
here "c" is initialized dynamically to the length of hypotenuse.
2. What is the use of super keyword?
The super keyword can be used by classes that are extended from virtual or
abstract classes. By using super, you can override constructors and methods from the parent
class.
3. What are the advantages of Java Language?
¾ Java is simple.
¾ Java is object-oriented.
¾ Java is platform-independent.
¾ Java is distributed .
¾ Java is interpreted.
4. What is an applet program?
Applet is an application designed to be transmitted over the Internet and executed java
compatible web browser.
41
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
Exercise Number: 9
Title of the exercise : DEVELOPING A TEMPLATE FOR LINKED LIST
Date of the exercise :
OBJECTIVE (AIM) OF THE EXPERIMENT
•
To develop a template for linked list in java.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.
Facilities required
Quantity
1
System
1
2
O/S
3
S/W name
Windows / Linux OS
JDK 1.6
b) Procedure:
Step no.
Details of the step
1
Import the necessary packages.
2
Declare the main function within the class Linked list demo.
3
4
Insert items in to the list using add() method use addLast() to isert at the
end.
Display the contents of the lists.
5
Use remove() method to declare a specific element.
6
Use remove() first(0,removeLast() to delete the element at the first and at
the last.
Display the lsit and hadle the exceptions .
7
c) Program:
import java.util.*;
class LinkedListDemo
{
public static void main(String args[])
{
LinkedList<String> l1=new LinkedList<String>();
l1.add("F");
l1.add("B");
l1.add("D");
l1.add("E");
l1.add("C");
l1.addLast("Z");
42
Dr.N.N.C.E
IT / V Sem
l1.addLast("A");
l1.add(1,"A2");
System.out.println("Original contents of l1:" + l1);
l1.remove("F");
l1.remove(2);
System.out.println("Contents of l1 after deflection: " + l1);
l1.removeFirst();
l1.removeLast();
System.out.println("l1 after deleting first and last: " + l1);
String val=l1.get(2);
l1.set(2, val + "Changed");
System.out.println("l1 after change: " + l1); } }
JP Lab - LM
OUTPUT:
E:\SQ>java LinkedListDemo
Original contents of l1:[F, A2, B, D, E, C, Z, A]
Contents of l1 after deflection: [A2, B, E, C, Z, A]
l1 after deleting first and last: [B, E, C, Z]
l1 after change: [B, E, CChanged, Z]
d)
Result:
Thus the Linked list program was compiled and executed successfuly.
VIVA – QUESTIONS AND ANSWERS:
1. Why does Java not support destructors and how does the finalize method help in
garbage collection
The garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects. Right before
an asset is freed, the java run time calls the finalize() method on the object.
2. What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to
perform any cleanup processing before the object is garbage collected.
3. Mention some of the separator in java programming?
( ) Contain a list of parameters in method definition & invocation.
{ } Contain the value of automatically initialized arrays.
[ ] Declare array types.
; Terminate statements.
. Separate package name f rom sub packages.
43
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
Exercise Number: 10
Title of the exercise
: DEVELOP A MULTI THREADED PRODUCER CONSUMER
APPLICATION
Date of the exercise
:
OBJECTIVE (AIM) OF THE EXPERIMENT
•
To develop a multithreaded producer and consumer application in java.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.
Facilities required
Quantity
1
System
1
2
O/S
3
S/W name
Windows / Linux OS
JDK 1.6
b) Procedure:
Step no.
Details of the step
1
Import the necessary packages.
2
Create two threads producer and consumer.
3
Declare a constant MAXQUEUE in producer thread.
4
Create an instance for vector named messages to implement a queue.
5
7
In the run() method of producer thread put the messages on the queue
using putmessages() and suspend the thread for one sec using sleep(1000).
Declare the getmessage() method and ceck whether there is any message
if no wait for one.
After receiving the message remove the message and return it.
8
Create a constructor to assign values to them.
9
10
In the run method of consumer class call the getmessage() method of
producer thread and print the message.
Suspend the thread for 2 sec using sleep(2000).
11
Create two instances with different name for consumer thread.
12
Display the message.
6
44
Dr.N.N.C.E
IT / V Sem
c) Program:
import java.util.Vector;
class Producer extends Thread {
static final int MAXQUEUE = 5;
private Vector messages = new Vector();
public void run() {
try {
while ( true ) {
putMessage();
sleep( 1000 );
}
}
catch( InterruptedException e ) { }
}
private synchronized void putMessage()
throws InterruptedException {
while ( messages.size() == MAXQUEUE )
wait();
messages.addElement( new java.util.Date().toString() );
notify();
}
// Called by Consumer
public synchronized String getMessage()
throws InterruptedException {
notify();
while ( messages.size() == 0 )
wait();
String message = (String)messages.firstElement();
messages.removeElement( message );
return message;
}
}
class Consumer extends Thread {
Producer producer;
String name;
Consumer(String name, Producer producer) {
this.producer = producer;
this.name = name;
}
public void run() {
try {
while ( true ) {
String message = producer.getMessage();
System.out.println(name + " got message: " + message);
sleep( 2000 );
}
45
JP Lab - LM
Dr.N.N.C.E
}
catch( InterruptedException e ) { }
}
IT / V Sem
JP Lab - LM
public static void main(String args[]) {
Producer producer = new Producer();
producer.start();
// Start two this time
new Consumer( "One", producer ).start();
new Consumer( "Two", producer ).start();
}
}
OUTPUT:
E:\SQ>java Consumer
Two got message: Wed Sep 01 11:57:54 GMT+05:30 2010
One got message: Wed Sep 01 11:57:55 GMT+05:30 2010
Two got message: Wed Sep 01 11:57:56 GMT+05:30 2010
One got message: Wed Sep 01 11:57:57 GMT+05:30 2010
Two got message: Wed Sep 01 11:57:58 GMT+05:30 2010
One got message: Wed Sep 01 11:57:59 GMT+05:30 2010
Two got message: Wed Sep 01 11:58:00 GMT+05:30 2010
One got message: Wed Sep 01 11:58:01 GMT+05:30 2010
Two got message: Wed Sep 01 11:58:02 GMT+05:30 2010
One got message: Wed Sep 01 11:58:03 GMT+05:30 2010
One got message: Wed Sep 01 11:58:04 GMT+05:30 2010
Two got message: Wed Sep 01 11:58:18 GMT+05:30 2010
One got message: Wed Sep 01 11:58:19 GMT+05:30 2010
Two got message: Wed Sep 01 11:58:20 GMT+05:30 2010
One got message: Wed Sep 01 11:58:21 GMT+05:30 2010
Two got message: Wed Sep 01 11:58:22 GMT+05:30 2010
d)
Result:
Thus the Multithreaded program was compiled and executed successfuly.
VIVA – QUESTIONS AND ANSWERS:
1. What is Inheritance Hierarchy?
Hierarchical inheritance in simple sentence "creating one or more child classes from
the parent class".
2. What is nested class or inner class? Mention its types.
An inner class or nested class is a class declared entirely within the body of another
class or interface. It is distinguished from a subclass. StaticNon-Static / Inner Classes
3. What kind of thread is the Garbage collector thread?
It is a daemon thread.
4. What is a daemon thread?
These are the threads which can run without user intervention. The JVM can exit when
there are daemon thread by killing them abruptly.
46
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
Exercise Number: 11
Title of the exercise
Date of the exercise
: GENERATING PRIME NUMBERS AND FIBONACCI SERIES
:
OBJECTIVE (AIM) OF THE EXPERIMENT
•
To generate prime numbers and Fibonacci series using java.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.
Facilities required
Quantity
1
System
1
2
O/S
3
S/W name
Windows / Linux OS
JDK 1.6
b) Procedure:
Step no.
Details of the step
1
2
Import the necessary packages.
Create tow threads MyThread1 and MyThread2.
3
In MyThread1 create instances for piped reader and piped writer.
4
Create a constructor and assign values to them.
5
In mythread2 create instances for pipedreader and piped writer.
6
Create a constructor and assign values to them.
7
Declare a class Multithreaded programming and create two list using
ArrayList.
Create instances for pipedreader and pipedwriter prl and pwl respectively.
8
9
Get the Fibonacci series from the stream pr2 and store them in lsit2 by
using retainAll() method and print them.
c) Program:
import java.io.*;
import java.util.*;
class MyThread1 extends Thread {
private PipedReader pr;
private PipedWriter pw;
MyThread1(PipedReader pr, PipedWriter pw) {
this.pr = pr;
this.pw = pw;
}
47
Dr.N.N.C.E
IT / V Sem
public void run() {
try {
int i;
for (i=1;i<10;i++){
int j;
for (j=2; j<i; j++){
int n = i%j;
if (n==0){
break;}}
if(i == j){
pw.write(i+"\n");}
}pw.close();}
catch (IOException e) {
}}}
class MyThread2 extends Thread {
private PipedReader pr;
private PipedWriter pw;
MyThread2(PipedReader pr, PipedWriter pw) {
this.pr = pr;
this.pw = pw;}
public void run() {
try {
int f1, f2 = 1, f3 = 1;
for (int i = 1; i <10; i++) {
pw.write(f3+"\n");
f1 = f2;
f2 = f3;
f3 = f1 + f2;}
pw.close();
} catch (IOException e) {
}}}
class MultithreadedProgram {
public static void main(String[] args) throws Exception {
ArrayList list1=new ArrayList();
ArrayList list2=new ArrayList();
PipedWriter pw1 = new PipedWriter();
PipedReader pr1 = new PipedReader(pw1);
MyThread1 mt1 = new MyThread1(pr1, pw1);
System.out.println("Prime Numbers: ");
mt1.start();
int item1;
while ((item1 = pr1.read()) != -1){
char ch1=((char) item1);
System.out.print(Character.toString(ch1));
list1.add(Character.toString(ch1));
}
pr1.close();
PipedWriter pw2 = new PipedWriter();
PipedReader pr2 = new PipedReader(pw2);
MyThread2 mt2 = new MyThread2(pr2, pw2);
48
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
System.out.println("Fibonacci Numbers: ");
mt2.start();
int item2;
while ((item2 = pr2.read()) != -1){
char ch2=((char) item2);
System.out.print(Character.toString(ch2));
list2.add(Character.toString(ch2));
}
pr2.close();
System.out.println("Elements common to both lists are:");
list1.retainAll(list2);
for(int i=0;i<list1.size();i++){
System.out.print(list1.get(i));
}}}
OUTPUT:
E:\SQ>java MultithreadedProgram
Prime Numbers:
2
3
5
7
Fibonacci Numbers:
1
2
3
5
8
13
21
34
55
Elements common to both lists are:
2
3
5
d)
Result:
Thus the program was compiled and executed successfuly.
JP Lab - LM
VIVA – QUESTIONS AND ANSWERS:
1. What is the basic difference between string and stringbuffer object?
String is an immutable object. StringBuffer is a mutable object.
2. What is the need for abstract classes?
Abstract keyword will be used in method declaration to declare that method without
providing the implementation in that java program.
3. Define proxies.
A proxy server is an intermediary computer that is between the user's computer and
the Internet. It can be used to log Internet usage and also to block access to a web site. The
firewall at the proxy server blocks some web sites or web pages for various reasons.
49
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
Exercise Number: 12
Title of the exercise
: MULTITHREADED GUI APPLICATION
Date of the exercise :
OBJECTIVE (AIM) OF THE EXPERIMENT
•
To develop a multithreaded GUI application in java.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.
Facilities required
Quantity
1
System
1
2
O/S
3
S/W name
Windows / Linux OS
JDK 1.6
b) Procedure:
Step no.
1
Details of the step
3
Create the class ball which implements a ball which moves and bounces
of the edges of a rectangle.
Using the move() method move the ball to the nect postion by reversing
the direction if it bits one of the edges
Get the shapes of the ball at its current position.
4
Invoke the runnable() method to show the animated bouncing balls.
5
7
Using the sleep() method assign the time for ball to bounce in a given
interval of time.
Construct the frame with the component for showing bouncing ball and
start and close buttons.
Add the thread to the frame and button to the container.
8
Create a constructor to assign values to them.
9
Add a bouncing ball to the canvas and starts a thread to make it bounce.
10
Display the output.
2
6
c) Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.geom.*;
50
Dr.N.N.C.E
IT / V Sem
class Ball{
public void move(Rectangle2D bounds)
{
x += dx;
y += dy;
if (x < bounds.getMinX())
{
x = bounds.getMinX();
dx = -dx; }
if (x + XSIZE >= bounds.getMaxX())
{
x = bounds.getMaxX() - XSIZE;
dx = -dx; }
if (y < bounds.getMinY())
{
y = bounds.getMinY();
dy = -dy; }
if (y + YSIZE >= bounds.getMaxY())
{
y = bounds.getMaxY() - YSIZE;
dy = -dy; } }
public Ellipse2D getShape()
{
return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
}
private static final int XSIZE = 15;
private static final int YSIZE = 15;
private double x = 0;
private double y = 0;
private double dx = 1;
private double dy = 1;
}
class BallComponent extends JComponent
{
public void add(Ball b)
{
balls.add(b);}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
for (Ball b : balls)
{
g2.fill(b.getShape()); } }
private ArrayList<Ball> balls = new ArrayList<Ball>();
}
public class BounceThread
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
51
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
{
public void run() {
JFrame frame = new BounceFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);}
}); }}
class BallRunnable implements Runnable
{
public BallRunnable(Ball aBall, Component aComponent)
{
ball = aBall;
component = aComponent;
}
public void run(){
try {
for (int i = 1; i <= STEPS; i++)
{
ball.move(component.getBounds());
component.repaint();
Thread.sleep(DELAY); } }
catch (InterruptedException e)
{
}}
private Ball ball;
private Component component;
public static final int STEPS = 1000;
public static final int DELAY = 5;
}
class BounceFrame extends JFrame
{
public BounceFrame() {
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
setTitle("BounceThread");
comp = new BallComponent();
add(comp, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
addButton(buttonPanel, "Start", new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
addBall();}
});
addButton(buttonPanel, "Close", new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);}
});
add(buttonPanel, BorderLayout.SOUTH);
}
52
JP Lab - LM
Dr.N.N.C.E
IT / V Sem
public void addButton(Container c, String title, ActionListener listener)
{
JButton button = new JButton(title);
c.add(button);
button.addActionListener(listener);
}
public void addBall()
{
Ball b = new Ball();
comp.add(b);
Runnable r = new BallRunnable(b, comp);
Thread t = new Thread(r);
t.start();
}
private BallComponent comp;
public static final int DEFAULT_WIDTH = 450;
public static final int DEFAULT_HEIGHT = 350;
public static final int STEPS = 1000;
public static final int DELAY = 3;
}
OUTPUT:
d)
JP Lab - LM
Result:
Thus the Multithreaded GUI application was compiled and executed successfuly.
VIVA – QUESTIONS AND ANSWERS:
1. What are the approaches that we will follow for making a program very efficient?
By avoiding too much of static methods avoiding the excessive and unnecessary use of
synchronized methods Selection of related classes based on the application (meaning
synchronized classes for multiuser and non-synchronized classes for single user) Usage of
appropriate design patterns Using cache methodologies for remote invocations Avoiding
creation of variables within a loop and lot more.
53
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
Exercise Number: 13
Title of the exercise
: OPERATORS AND EXPRESSIONS
Date of the exercise :
OBJECTIVE (AIM) OF THE EXPERIMENT
•
To write a java program to find the area of rectangle.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.
Facilities required
Quantity
1
System
1
2
O/S
3
S/W name
Windows / Linux OS
JDK 1.6
b) Procedure:
Step no.
Details of the step
1
Start the program.
2
3
Create a class with the class name arearect to demonstrate the application
of the operators and expression.
Create a constructor for initialization.
4
Initialize the parseInt value to convert the string object into integer value.
5
Print the output value.
6
Stop the program.
c) Program:
class AreaRect
{
public static void main(String args[])
{
int len,bre,area;
len= Integer.parseInt(args[0]);
bre=Integer.parseInt(args[1]);
area=len*bre;
system.out.println(“length of rectangle=”+len);
54
Dr.N.N.C.E
IT / V Sem
system.out.println(“breadth of rectangle=”+bre);
JP Lab - LM
system.out.println(“area of rectangle=”+area);
}
}
OUTPUT:
D:\java>javac AreaRect.java
D:\java>java AreaRect
12 6
length of rectangle = 12
breadth of rectangle = 6
area of rectangle= 72
d) Result:
Thus the java program to find the area of rectangle was successfully executed and
verified.
VIVA – QUESTIONS AND ANSWERS:
1. What is a ternary operator?
The operator that takes three arguments is called as ternary operator. The
conditional operators is the only ternary operator available in java.
2. What is the use of Integer.parseInt() method?
It is used to convert the string object into integer value.
55
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
Exercise Number: 14
Title of the exercise
: DECISION MAKING STRUCTURE
Date of the exercise :
OBJECTIVE (AIM) OF THE EXPERIMENT
•
To write a java program to read an integer and find whether the number is odd or even.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities Required:
S.No.
Facilities required
Quantity
1
System
1
2
O/S
3
S/W name
Windows / Linux OS
JDK 1.6
b) Procedure:
Step no.
Details of the step
1
Start the program.
2
3
Create a class with the class name oddt to demonstrate the application of
the decision making structure.
Create a constructor for initialization.
4
Initialize the parseInt value to convert the string object into integer value.
5
Print the output value.
6
Stop the program.
c) Program:
import java.io.*;
class odd
{
public static void main(String args[])throws IOException
{
BufferedReader din = new BufferedReader(new InputStreamReader(System.in));
int n;
system.out.println(“enter a number:”);
56
Dr.N.N.C.E
n= Integer.parseInt(din.readLine());
IT / V Sem
JP Lab - LM
if(n%2==0)
system.out.println(n+”is an even no”);
else
system.out.println(n+”is an odd no:”);
}
}
OUTPUT:
D:\java>javac odd.java
D:\java>java odd
Enter a no: 67
67 is an odd no
d) Result:
Thus the java program to read an integer and find whether the number is odd or even
was successfully executed and verified.
VIVA – QUESTIONS AND ANSWERS:
1. What are decision making statements?
The statements that are used to execute only a block of code and leaving others based
on the condition.
2. What are the various decision making statements available in java?
Simple if, if-else, nested if..else, if else ladder and switch statement.
57
Dr.N.N.C.E
IT / V Sem
JP Lab - LM
IT2305 – JAVA PROGRAMMING LABORATORY
MODEL QUESTION SET
1. Create Java package with simple stack and queue class
2. Write a Java program to perform Complex number manipulation
3. Write a Java program for Date class similar to java.util package
4. Write a Java program for Implementing dynamic polymorphism in java
5. Write a Java program for ADT stack using Java interface
6. Write a Java program for DNA file creation
7. Develop a simple paint like program using applet
8. Develop a scientific calculator using java
9. Developing a template for linked list
10. Develop a multi threaded producer consumer Application
11. Write a Java program for generating prime numbers and Fibonacci series
12. Write a Java program for Multithreaded GUI application
58