IT 2305- JAVA PROGRAMMING LAB LAB MANUAL SRINVASAN ENGINEERING COLLEGE

SRINVASAN ENGINEERING COLLEGE
PERAMBALUR - 621212
DEPARTMENT OF INFORMATION TECHNOLOGY
IT 2305- JAVA PROGRAMMING LAB
LAB MANUAL
Academic year (2013-2014) V SEMESTER
PREPARED BY
T.Rajalakshmi
Assistant Professor (IT),
Srinivasan Engineering College, Perambalur-621212
PREFACE
Java Programming Lab manual is intended to provide a
basic knowledge of java programming for students and readers.
To develop software development skills in java programming and
Students will have the proficiency to develop projects in java
programming
Acknowledgement
I give all glory and thanks to our god almighty for showering upon, the
necessary wisdom and grace for accomplishing the lab manual.
I am highly indebted to our respectable chairman and founder of Dhanalakshmi
Srinivasan Group of institutions, SHRI.A.SRINIVASAN for providing with
sufficient facilities that contributed to the success in this endeavor.
I
am
very
thankful
to
our
reputable,
beloved
principal,
DR.B.KARTHIKEYAN M.E.,Ph.D.,, for his continuous encouragement and for
motivating me to complete this lab manual.
I would like to express my sincere thanks and deep sense of gratitude to our
Head of the Department, Mrs. P. MANJULA M.E for her valuable guidance,
suggestions and constant encouragement paved way for the completion of the manual.
Contents
EX.NO
NAME OF THE EXPERIMENT
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
INTRODUCTION OF THE LANGUAGE
Java is a general-purpose, concurrent, class-based, object-oriented computer programming language
that is specifically designed to have as few implementation dependencies as possible. Java
applications are typically compiled to bytecode (class file) that can run on any Java virtual machine
(JVM) regardless of computer architecture. JVM is an interpreter, accepts Bytecode as input and
execute it.
To compile and run Java program code you need to download JDK (Java
Development Kit).
To compile type: javac file_name.java where file_name is name of file containing
java
source
code.
Javac is the Java compiler which converts java code into bytecode.
To run type: java main_method_class where main_method_class is the name of class
which defines main method
MAIN FEATURES JAVA PROGRAMMING LANGUAGE
Simple :
Java is Easy to write and more readable and eye catching.
Java has a concise, cohesive set of features that makes it easy to learn and use.
Most of the concepts are drew from C++ thus making Java learning simpler.
Secure :
Java program cannot harm other system thus making it secure.
Java provides a secure means of creating Internet applications.
Java provides secure way to access web applications.
Portable :
Java programs can execute in any environment for which there is a Java run-time
system.(JVM)
Java programs can be run on any platform (Linux,Window,Mac)
Java programs can be transferred over world wide web (e.g applets)
Object-oriented :
Java programming is object-oriented programming language.
Like C++ java provides most of the object oriented features.
Java is pure OOP. Language. (while C++ is semi object oriented)
Robust :
Java encourages error-free programming by being strictly typed and performing
run-time checks.
Multithreaded :
Java provides integrated support for multithreaded programming.
Architecture-neutral :
Java is not tied to a specific machine or operating system architecture.
Machine Independent i.e Java is independent of hardware .
Interpreted :
Java supports cross-platform code through the use of Java bytecode.
Bytecode can be interpreted on any platform by JVM.
High performance :
Bytecodes are highly optimized.
JVM can executed them much faster .
Distributed :
Java was designed with the distributed environment.
Java can be transmit,run over internet.
Dynamic :
Java programs carry with them substantial amounts of run-time type information
that is used to verify and resolve accesses to objects at run time.
APPLICATIONS
Computer applications
Writing embedded software/firmware for various electronics
Industries
Communications products which use micro-controllers
Developing verification software, test code, simulators etc.
Hardware products.
Research
System designing
Networking
Database connectivity
Mobile Applications
LIST OF EXPERIMENTS
1. Develop a Java package with simple Stack and Queue classes. Use JavaDoc
comments for documentation.
2. Design a class for Complex numbers in Java. In addition to methods for basic
operations on complex numbers, provide a method to return the number of active
objects created.
3. Design a Date class similar to the one provided in the java.util package.
4. Develop with suitable hierarchy, classes for Point, Shape, Rectangle, Square, Circle,
Ellipse, Triangle, Polygon, etc. Design a simple test application to demonstrate
dynamic polymorphism.
5. Design a Java interface for ADT Stack. Develop two different classes that implement
this interface, one using array and the other using linked-list. Provide necessary
exception handling in both the implementations.
6. Write a Java program to read a file that contains DNA sequences of arbitrary length
one per line (note that each DNA sequence is just a String). Your program should sort
the sequences in descending order with respect to the number of 'TATA'
subsequences present. Finally write the sequences in sorted order into another file.
7. Develop a simple paint-like program that can draw basic graphical primitives in
different dimensions and colors. Use appropriate menu and buttons.
8. Develop a scientific calculator using even-driven programming paradigm of Java.
9. Develop a template for linked-list class along with its methods in Java.
10. Design a thread-safe implementation of Queue class. Write a multi-threaded
producer-consumer application that uses this Queue class.
11. Write a multi-threaded Java program to print all numbers below 100,000comthat are
both prime and fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a
thread that generates prime numbers below 100,000 and writes them into a pipe.
Design another thread that generates fibonacci numbers and writes them to another
pipe. The main thread should read both the pipes to identify numbers common to
both.
12. Develop a multi-threaded GUI application of your choice.
IT 2305- JAVA PROGRAMMING LAB
Objective
To Effectively use the Java SDK environment to create, debug and run
simple Java programs
To understand fundamentals of object-oriented programming in Java,
including defining classes, invoking methods, using class libraries, etc.
Ex.No:1
JAVA PACKAGE WITH SIMPLE STACK AND QUEUE CLASS
AIM:
To write program to develop a java package for the stack and queue classes.
EXPLANATION
Java Package
A Java package is a mechanism for organizing Java classes into namespaces similar to the
modules of Modula.In a Java source file, the package that this file's class or classes belong to is
specified with the package keyword.Classes within a package can access classes and members
declared with default access and class members declared with the protected access modifier.
Stack
A stack is a particular kind of abstract data type or collection which follows the Last-In-FirstOut (LIFO) data structure principle. The PUSH operation is for inserting an element into the
stack. POP operation is for deleting an element from the stack.
Queue
A queue is a particular kind of abstract data type or collection which follows the First-InFirst-Out (FIFO) data structure principle.The operations on the collection are the addition of
entities to the rear terminal position, known as enqueue, and removals of entities from the front
terminal position, known as dequeue.
ALGORITHM:
Stack class:
1. Start the program.
2. Create a class with the class name Stack to demonstrate the application of the stack.
3. Create a constructor to initialize the top value of the stack.
4. Define the method push ().
5. If the top value is equal to 9, print stack is full. Otherwise push the value in to the stack.
6. Define the method pop ().
7. If the top value is less than zero, print stack underflow. Otherwise decrement the value of
the stack.
8. Create a main class with the class name teststack.
9. Create an object for the class Stack to call the methods define inside that class.
10. Call the methods push () & pop () using the objects.
Queue class:
1. Start the program.
2. Create a class with the name queue implement to demonstrate about a application of
queue.
3. Declare a variable str as string and num as integer.
4. Create an object for a class queue implement.
5. Create a constructor to of the Linked List class. This class is used by importing
the java.util. package. This constructor is used for constructing an empty list.
6. Get the value from the command line by using a variable str.
7. Using try and catch block to handle exception using IOException.
8. Print the elements in the queue using the statement.
Stack class:
package SQ;
import java.io.*;
/**
* This class demonstrates about the application of Statck
* @author Herbert Schildt
* @version 1.6
*/
class Stack
{
int stck[]=new int[10];
int tos;
/**
* Stack constructor initializes the top of the stack.
* @param tos The value to be initialized to -1.
*/
Stack()
{
tos=-1;
}
/**
* This method push an item on to the stack.
* @param tos If the value is nine the stack is full otherwise array will incremented.
*/
void push(int item)
{
if(tos==9)
System.out.println("Stack is full");
else
stck[++tos]=item;
}
/**
* This method pop an item on to the stack.
* @param tos If the value is negative the stack is undeflow otherwise array will decremented.
* @return stck[tos--] the stack array will return
*/
int pop()
{
if(tos<0)
{
System.out.println("Stack underflow");
return 0;
}
else
return stck[tos--];
}
}
class TestStack
{
public static void main(String args[])
{
/**
* Two objects will be created to push and pop the items.
* @param mystack1 The object of the class stack.
* @param mystack2 The object of the class stack.
*/
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.*;
/**
* This class demonstrates about the application of Queue
* @author Herbert Schildt
* @version 1.6
*/
import java.io.*;
import java.util.*;
public class QueueImplement{
LinkedList<Integer> list;
String str;
int num;
public static void main(String[] args){
QueueImplement q = new QueueImplement();
}
/**
* This constructor demonstrates the queue application
* @param str the value get from commandline is stored.
* @exception IOException on input error.
* @see IOException
*/
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
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
Result:
Thus the Stack and queue program was compiled and executed successfully.
VIVA
Define Stack
A stack is a particular kind of abstract data type or collection which follows the Last-In-First-Out
(LIFO) data structure principle.
What are the operations in Stack?
The PUSH operation is for inserting an element into the stack. POP operation is for deleting an
element from the stack.
Define Java Package
A Java package is a mechanism for organizing Java classes into namespaces similar to the
modules of Modula.
Define Queue
A queue is a particular kind of abstract data type or collection which follows the First-In-First-Out
(FIFO) data structure principle.
What are the operations in Queue?
The operations on the collection are the addition of entities to the rear terminal position, known as
enqueue, and removals of entities from the front terminal position, known as dequeue.
Ex.No:2
COMPLEX NUMBER MANIPULATION
AIM:
To write a program to perform addition, subtraction, multiplication in complex numbers using
constructors.
EXPLANATION
A constructor is a member function which initializes a class. It has the same name as the class
itself and has no return type. They are invoked automatically when the objects are created.
Types of constructors
Parameterized constructors
Default constructors
Copy constructors
Destructor is a special member function of a class which is used to destroy the memory of
object. The destructor has the same name as the class, but with a tilde (~). It does not take any
parameters.
ALGORITHM:
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: Define static method named as addition, subtraction,multiplication to perform particular
function defined inside the method.
6: Create an object for the class Complex Number and pass the values in the argument list.
7: Call the method by using object to get the values.
8: Print the result.
9: Stop the program.
COMPLEX NUMBER MANIPULATION
public class ComplexNumber
{
private int a;
private int b;
public ComplexNumber(){
}
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));
System.out.println("Multiplication of both Complex Numbers are :"
+ComplexNumber.multiplication(com1,com2));}}
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 :-8+22i
Result:
Thus the complex number program was executed and compiled successfully.
VIVA
Define a Constructor?
A constructor is a member function which initializes a class. It has the same name as the class
itself and has no return type. They are invoked automatically when the objects are created.
What are the types of constructor?
Types of constructors
Parameterized constructors
Default constructors
Copy constructors
Define Destructor?
Destructor is a special member function of a class which is used to destroy the memory of object.
The destructor has the same name as the class, but with a tilde (~). It does not take any parameters.
Ex.No:3
DATE CLASS SIMILAR TO JAVA.UTIL PACKAGE
AIM:
To write a java program to display the dates of before and after days for a given date.
EXPLANATION
Java.util package contains the collections framework, legacy collection classes, event model, date and
time facilities, internationalization, and miscellaneous utility classes.
The java.util.Date class represents a specific instant in time, with millisecond precision.
Date() - This constructor allocates a Date object and initializes it so that it represents the time at
which it was allocated, measured to the nearest millisecond.
boolean after(Date when) - This method tests if this date is after the specified date.
boolean before(Date when) - This method tests if this date is before the specified date.
int compareTo(Date anotherDate) - This method compares two Dates for ordering.
ALGORITHM:
1. Start the program.
2. Create a class with name Date
3. Declare the variables month, day, year as private and create constructor with arguments.
4. Check the condition for exception. If the date is valid, It will proceed the program otherwise
display the exception “Invalid”.
5. 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
11. Call the all methods to display the dates.
DATE CLASS SIMILAR TO JAVA.UTIL PACKAGE
public class Date {
private final int month;
private final int day;
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) {
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-2013
21-7-2013
false
true
true
1
Result:
Thus the Date class program was compiled and executed successfully.
VIVA
Define Java util package?
Java.util package contains the collections framework, legacy collection classes, event model, date and
time facilities, internationalization, and miscellaneous utility classes.
Define Java util date class?
The java.util.Date class represents a specific instant in time, with millisecond precision.
Define Date()?
Date() - This constructor allocates a Date object and initializes it so that it represents the time at
which it was allocated, measured to the nearest millisecond.
Define after() and before()?
boolean after(Date when) - This method tests if this date is after the specified date.
boolean before(Date when) - This method tests if this date is before the specified date.
Define compareo()?
int compareTo(Date anotherDate) - This method compares two Dates for ordering.
Ex.No:4
IMPLEMENTING DYNAMIC POLYMORPHISM IN JAVA
AIM:
To write a java program for abstract class to find areas of different shapes.
EXPLANATION
An Abstract Classis a class that is declared abstract—it may or may not include abstract
methods. Abstract classes cannot be instantiated, but they can be subclassed.
An Abstract Methodis a method that is declared without an implementation. If you want a class
to contain a particular method but you want the actual implementation of that method to be
determined by child classes, you can declare the method in the parent class as abstract.
Declaring a method as abstract has two results:
The class must also be declared abstract. If a class contains an abstract method, the class must
be abstract as well.
Any child class must either override the abstract method or declare itself abstract.
ALGORITHM:
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. Define abstract method area() inside the subclasses and call the constructor of class Shape
using super keyword.
7. 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.
IMPLEMENTING DYNAMIC POLYMORPHISM IN JAVA
abstract class Shape
{
double dim1;
double dim2;
double PI=3.14;
Shape(double a, double b)
{
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Shape
{
Rectangle(double a, double b)
{
super(a, b);
}
// override area for rectangle
double area()
{
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Shape
{
Triangle(double a, double b)
{
super(a, b);
}
// override area for right triangle
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[]) {
// Figure f = new Figure(10, 10); // illegal now
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());
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
Result:
Thus the Dynamic polymorphism was compiled and executed successfully.
VIVA
Define Abstract class?
An Abstract Class is a class that is declared abstract—it may or may not include abstract
methods. Abstract classes cannot be instantiated, but they can be subclassed.
What is Abstract method?
An Abstract Method is a method that is declared without an implementation. If you want a class
to contain a particular method but you want the actual implementation of that method to be
determined by child classes, you can declare the method in the parent class as abstract.
Rules for declaring a abstract method?
The class must also be declared abstract. If a class contains an abstract method, the class must
be abstract as well.
Any child class must either override the abstract method or declare itself abstract.
Ex.No:5
JAVA INTERFACE FOR ADT STACK
AIM:
To write the java program for ADT stack using interface.
EXPLANATION
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting
the abstract methods of the interface. The “extends” keyword is used to extend an interface, and the
child interface inherits the methods of the parent interface. An interface is different from a class in
several ways, including:
An interface cannot be instantiated.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces.
ALGORITHM:
1: Start the program
2: Create an interface which consists of three methods namely PUSH, POP and DISPLAY
3: Create a class which implements the above interface to implement the concept of stack through
Array
4: 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.
5: Create another class which implements the same interface to implement the concept of stack
through linked list.
6: Repeat STEP 4 for the above said class also.
7: In the main class, get the choice from the user to choose whether array implementation or linked
list implementation of the stack.
8: Call the methods appropriately according to the choices madeby the user in the previous step.
9: Repeat step 6 and step 7 until the user stops his/her execution
10: Stop the program
JAVA INTERFACE FOR ADT STACK
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++)
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
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
Result:
Thus the Interface for ADT stack program was compiled and executed successfully.
VIVA
What is peek operation?
Peek is an operation on certain abstract data types, specifically sequential collections such as stacks
and queues, which returns the value of the top of the collection without removing the value from the
data
What is Interface?
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting
the abstract methods of the interface. The “extends” keyword is used to extend an interface, and the
child interface inherits the methods of the parent interface.
State the difference between class and interface?
An interface is different from a class in several ways, including:
An interface cannot be instantiated.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces.
Ex. No: 6
DNA FILE CREATION
AIM
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.
EXPLANATION
Java File class is used for creation of files and directories, file searching, file deletion etc.
FileReader Class is used for reading streams of characters. FileWriter Class is used for writing
streams of characters
Define a class Filetransfer and define the main function inside the class.
Use the Filereader to read the input file and use the FileWriter to write the output file
Use the PrintStream to print the output into the file.
Get the input strings from the input file
Sort the string values in the input file using count and temp.
Write the sorted data into the output file
And close the file and display the results
ALGORITHM:
1. Start
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.
Count the number of TATA sequence in each line and store the count in another array.
5.
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.
6.
Write the sorted DNA sequence to the output file “File.txt”
7.
View the output file.
8. Stop.
DNA File creation:
import java.util.*;
import java.io.*;
import java.util.Arrays;
import java.util.Collections;
class FileDemo
{
public static void main(String args[])throws IOException
{
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++)
{
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 taaattaataaattagaattaaa
Aaaaaaacatcgtaaa tcaatatatataat
Ctaaaataaac gataaaaacaaataa
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 taaattaataaattagaattaaa
Ctaaaataaac gataaaaacaaataa
Result:
Thus the DNA sequences were read sorted and output was given to an output file.
VIVA
Define File class
Java File class is used for creation of files and directories, file searching, file deletion etc.
Define FileReader class
FileReader Class is used for reading streams of characters.
Define FileWriter class
FileWriter Class is used for writing streams of characters
Define IOException()
An Exception that Constructs an IOException with null as its error detail message.
What is the use of java.util.Collections
java.util.Collections class consists exclusively of static methods that operate on or return
collections of data
Ex.No:7
DEVELOPING A SIMPLE PAINT LIKE PROGRAM USING APPLET
AIM:
To develop a simple paint like program using applet in java.
EXPLANATION
An Applet is a Java class that extends the java.applet.Applet class.A JVM is required to view an
applet. The JVM can be either a plug-in of the Web browser or a separate runtime environment.
Life Cycle of an Applet:
init: This method is intended for whatever initialization is needed for your applet. It is called
after the param tags inside the applet tag have been processed.
start: This method is automatically called after the browser calls the init method. It is also
called whenever the user returns to the page containing the applet after having gone off to
other pages.
stop: This method is automatically called when the user moves off the page on which the
applet sits. It can, therefore, be called repeatedly in the same applet.
destroy: This method is only called when the browser shuts down normally. Because applets
are meant to live on an HTML page, you should not normally leave resources behind after a
user leaves the page that contains the applet.
paint: Invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser. The paint() method is actually inherited from the java.awt.
ALGORITHM:
1. Import the required class and packages.
2. Create a class Drawtest for creating an applet.
3. Initialize panels and controls in the init() method.
4. Define the destroy() method to destroy the same.
5. Create an instance for draw test class and call the init(0 and start() methods in the main
method.
6. 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 perform the required operations.
10. Display the result according to the mode selected.
DEVELOPING A SIMPLE PAINT LIKE PROGRAM USING APPLET
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());
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();
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();
/* draw the current lines */
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());
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) {
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:
Result:
Thus the Applet-Paint program was compiled and executed successfully.
VIVA
Define Applet?
An Applet is a Java class that extends the java.applet.Applet class.A JVM is required to view an
applet. The JVM can be either a plug-in of the Web browser or a separate runtime environment.
Life Cycle of an Applet?
Init(), start(), stop(), destroy(), paint()
Define init()
init: This method is intended for whatever initialization is needed for your applet. It is called after the
param tags inside the applet tag have been processed.
Define start()
start: This method is automatically called after the browser calls the init method. It is also called
whenever the user returns to the page containing the applet after having gone off to other pages.
Define stop()
stop: This method is automatically called when the user moves off the page on which the applet sits.
It can, therefore, be called repeatedly in the same applet.
Define destroy()
destroy: This method is only called when the browser shuts down normally. Because applets are
meant to live on an HTML page, you should not normally leave resources behind after a user leaves
the page that contains the applet.
Define paint()
paint: Invoked immediately after the start() method, and also any time the applet needs to repaint
itself in the browser. The paint() method is actually inherited from the java.awt.
Ex.No:8
DEVELOPING A SCIENTIFIC CALCULATOR
AIM:
To develop a scientific calculator in java.
EXPLANATION
Swing library is an official Java GUI toolkit released by Sun Microsystems. It is used to create
Graphical user interfaces with Java.
JFrame class – It has the components added to the frame are referred to as its contents; these are
managed by the contentPanel. It’s a window with title, border, (optional) menu bar and user-specified
components
The ActionListener interface is used for handling action events. For example, it's used by a JButton
for button clicks, by JCheckbox for checking and unchecking, by a JMenuItem when an option is
picked and many other graphical components.
JButton - is a component the user clicks to trigger a specific action.
ALGORITHM:
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. Set up the JMenu bar and add Mnemenics to them by using setMnemonic() method.
5. Set the frame layout for the applet and set the background color to gray using
setBackground() method .
6. Create a container using JPanel().
7. Create numeric JButtons for operators and numbers using JButtons().
8. Set all the Numbered JButtons to blue .the rest to red usig setForeGround() method.
9. 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().
12. Stop the program.
DEVELOPING A SCIENTIFIC CALCULATOR
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener{
// Variables
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(String name, int style, int size)
Creates a new Font from the specified name, style and point size.
*/
Font f12 = new Font("Times New Roman", 0, 12);
Font f121 = new Font("Times New Roman", 1, 12);
// Constructor
public Calculator()
{
/* Set Up the JMenuBar.
* Have Provided All JMenu's with Mnemonics
* Have Provided some JMenuItem components with Keyboard Accelerators
*/
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);
//Set frame layout manager
setBackground(Color.gray);
jplMaster = new JPanel();
jlbOutput = new JLabel("0");
jlbOutput.setHorizontalTextPosition(JLabel.RIGHT);
jlbOutput.setBackground(Color.WHITE);
jlbOutput.setOpaque(true);
// Add components to frame
getContentPane().add(jlbOutput, BorderLayout.NORTH);
jbnButtons = new JButton[23];
//
GridLayout(int rows, int cols, int hgap, int vgap)
JPanel jplButtons = new JPanel();
// container for Jbuttons
// Create numeric Jbuttons
for (int i=0; i<=9; i++)
{
// set each Jbutton label to the value of index
jbnButtons[i] = new JButton(String.valueOf(i));
}
// Create operator Jbuttons
jbnButtons[10] = new JButton("+/-");
jbnButtons[11] = new JButton(".");
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]);
//
Setting all Numbered JButton's to Blue. The rest to Red
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);
}
// Set panel layout manager for a 4 by 5 grid
jplButtons.setLayout(new GridLayout(4, 5, 2, 2));
//Add buttons to keypad panel starting at top left
// First row
for(int i=7; i<=9; i++)
{
jplButtons.add(jbnButtons[i]);
}
// add button / and sqrt
jplButtons.add(jbnButtons[13]);
jplButtons.add(jbnButtons[17]);
// Second row
for(int i=4; i<=6; i++)
{
jplButtons.add(jbnButtons[i]);
}
// add button * and x^2
jplButtons.add(jbnButtons[14]);
jplButtons.add(jbnButtons[18]);
// Third row
for( int i=1; i<=3; i++)
{
jplButtons.add(jbnButtons[i]);
}
//adds button - and %
jplButtons.add(jbnButtons[15]);
jplButtons.add(jbnButtons[19]);
//Fourth Row
// add 0, +/-, ., +, and =
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);
jplMaster.add(jplControl, BorderLayout.EAST);
jplMaster.add(jplButtons, BorderLayout.SOUTH);
// Add components to frame
getContentPane().add(jplMaster, BorderLayout.SOUTH);
requestFocus();
//activate ActionListener
for (int i=0; i<jbnButtons.length; i++){
jbnButtons[i].addActionListener(this);
}
jmenuitemAbout.addActionListener(this);
jmenuitemExit.addActionListener(this);
clearAll();
//add WindowListener for closing frame and ending program
addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e)
{
System.exit(0);
}
}
);
}
//End of Contructor Calculator
// Perform action
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);
}
// Search for the button pressed until end of array or key found
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:
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;
}
}
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);
}
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 the input string already contains a decimal point, don't
// do anything to it.
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;
}
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;
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();
//
contentPane.setLayout(new BorderLayout());
calci.setTitle("Java Swing Calculator");
calci.setSize(241, 217);
calci.pack();
calci.setLocation(400, 250);
calci.setVisible(true);
calci.setResizable(false);
}
}
//End of Swing Calculator Class.
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){
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);
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();
}
}
}
{
OUTPUT:
Result:
Thus the Scientific calculator program was compiled and executed successfully.
VIVA
Define swing
Swing library is an official Java GUI toolkit released by Sun Microsystems. It is used to create
Graphical user interfaces with Java.
Define JFrame class
JFrame class – It has the components added to the frame are referred to as its contents; these are
managed by the contentPanel. It’s a window with title, border, (optional) menu bar and user-specified
components
Define ActionListener interface
The ActionListener interface is used for handling action events. For example, it's used by a JButton
for button clicks, by JCheckbox for checking and unchecking, by a JMenuItem when an option is
picked and many other graphical components.
Define JButton
JButton - is a component the user clicks to trigger a specific action.
Ex.No:9
DEVELOPING A TEMPLATE FOR LINKED LIST
AIM:
To develop a template for linked list in java.
EXPLANATION
A linked list is a data structure consisting of a group of nodes which together represent a sequence.
Linked list is a dynamic data structure whose length can be increased or decreased at run time. Each
node consists of a data and pointer to the next node. First node in a list is said a head.
Various Operations that can be performed in a list are Inserting a node and deleting a node.
Template - a template is a generic class or other unit of source code that can be used as the basis for
unique units of code.
Import the util package for performing LinkedList operation
Develop a template class string for performing the operations of linked list.
“LinkedList<String> l1=new LinkedList<String>();”
Insert the elements of list using add() and perform all the operations of list.
ALGORITHM:
1. Import the necessary packages.
2. Declare the main function within the class Linked list demo.
3. Insert items in to the list using add() method use addLast() to insert at the end.
4. 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.
7. Display the list and handle the exceptions.
DEVELOPING A TEMPLATE FOR LINKED LIST
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");
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 deletion: " + 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); } }
OUTPUT:
E:\SQ>java LinkedListDemo
Original contents of l1:[F, A2, B, D, E, C, Z, A]
Contents of l1 after deletion: [A2, B, E, C, Z, A]
l1 after deleting first and last: [B, E, C, Z]
l1 after change: [B, E, CChanged, Z]
Result:
Thus the Linked list program was compiled and executed successfully.
VIVA
Define Linked list
A linked list is a data structure consisting of a group of nodes which together represent a sequence.
Linked list is a dynamic data structure whose length can be increased or decreased at run time. Each
node consists of a data and pointer to the next node. First node in a list is said a head.
What are the Various Operations in a list
Various Operations that can be performed in a list are Inserting a node and deleting a node.
Define Template
Template - a template is a generic class or other unit of source code that can be used as the basis for
unique units of code.
Ex.No:10
DEVELOP A MULTI THREADED PRODUCER CONSUMER
APPLICATION
AIM:
To develop a multithreaded producer and consumer application in java.
EXPLANATION
A multithreaded program contains two or more parts that can run concurrently. Each part of such a
program is called a thread, and each thread defines a separate path of execution.A multithreading is a
specialized form of multitasking.
Life Cycle of a Thread
New: A new thread begins its life cycle in the new state. It remains in this state until the program
starts the thread. It is also referred to as a born thread.
Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is
considered to be executing its task.
Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread
to perform a task.A thread transitions back to the runnable state only when another thread signals the
waiting thread to continue executing.
Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A
thread in this state transitions back to the runnable state when that time interval expires or when the
event it is waiting for occurs.
Terminated: A runnable thread enters the terminated state when it completes its task or otherwise
terminates.
ALGORITHM:
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. 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).
6. Declare the getmessage() method and ceck whether there is any message if no wait for
one.
7. After receiving the message remove the message and return it.
8. Create a constructor to assign values to them.
9. In the run method of consumer class call the getmessage() method of producer thread and
print the message.
10. Suspend the thread for 2 sec using sleep(2000).
11. Create two instances with different name for consumer thread.
12. Display the message.
DEVELOP A MULTI THREADED PRODUCER CONSUMER APLICATION
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 );
}
}
catch( InterruptedException e ) { }
}
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
Result:
Thus the Multithreaded program was compiled and executed successfully.
.
VIVA
Define Multithreading
A multithreaded program contains two or more parts that can run concurrently. Each part of such a
program is called a thread, and each thread defines a separate path of execution. A multithreading is a
specialized form of multitasking.
Life Cycle of a Thread
New, Runnable, Waiting, TimedWaiting, Terminated
Defne New state of a thread
A new thread begins its life cycle in the new state. It remains in this state until the program starts the
thread. It is also referred to as a born thread.
Define Runnable state of a thread
After a newly born thread is started, the thread becomes runnable. A thread in this state is considered
to be executing its task.
Define Waiting state of a thread
Sometimes a thread transitions to the waiting state while the thread waits for another thread to
perform a task.A thread transitions back to the runnable state only when another thread signals the
waiting thread to continue executing.
Define Timed waiting state of a thread
A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this
state transitions back to the runnable state when that time interval expires or when the event it is
waiting for occurs.
Define Terminated state of a thread
A runnable thread enters the terminated state when it completes its task or otherwise terminates.
Ex.No:11
GENERATING PRIME NUMBERS AND FIBONACCI SERIES
AIM:
To generate prime numbers and fibonacci series using java.
EXPLANATION
Create 2 array list for each series.
Start the thread for generating prime numbers, this calls the class MyThread1
Thread1 gets the series for prime numbers and add them to arraylist1
Start the thread2 for generating Fibonacci series, this calls the clas MyThread2
Thread1 gets the series for Fibonacci series and add them to arraylist2
retainAll() - This method is used to retain the elements of one list into another. In other word
we can say, it deletes all those elements of current list collection which do not exist in
specified collection object. It copies those elements which are equal in both list collection
objects and deletes rest of the other elements from the specified list. This method returns true
if the list has changed after the call, otherwise false.
Using retainAll() the list is compared and the common values are stored in list1 and displayed
ALGORITHM:
1. Import the necessary packages.
2. 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.
8. Create instances for pipedreader and pipedwriter prl and pwl respectively.
9. Get the Fibonacci series from the stream pr2 and store them in lsit2 by using retainAll()
method and print them.
GENERATING PRIME NUMBERS AND FIBONACCI SERIES
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;
}
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);
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
Result:
Thus the program was compiled and executed successfully.
VIVA
Define Multithreading
A multithreaded program contains two or more parts that can run concurrently. Each part of such a
program is called a thread, and each thread defines a separate path of execution. A multithreading is a
specialized form of multitasking.
Define retainAll()
This method is used to retain the elements of one list into another. In other word we can say, it deletes
all those elements of current list collection which do not exist in specified collection object. It copies
those elements which are equal in both list collection objects and deletes rest of the other elements
from the specified list. This method returns true if the list has changed after the call, otherwise false.
Ex.No:12
MULTITHREADED GUI APPLICATION
AIM:
To develop a multithreaded GUI application in java.
EXPLANATION
GUI - There are two sets of Java APIs for graphics programming: AWT (Abstract Windowing
Toolkit) and Swing.Java Graphics APIs - AWT and Swing - provide a huge set of reusable GUI
components, such as button, text field, label, choice, panel and frame for building GUI applications.
The java.awt package contains the core AWT graphics classes. The java.awt.event package supports
event handling. The java.awt.geom package contains models for a 2D point like x and y axis.
In this program the application has a ball that moves and bounces off the edges of a rectangle is
designed by using GUI in java.
Move() -Moves the ball to the next position, reversing direction if it hits one of the edges.
getShape() - Gets the shape of the ball at its current position
Using Jcomponent in java add() - Add a ball to the panel.
BounceThread - Shows animated bouncing balls
BallRunnable - A runnable that animates a bouncing ball.
BounceFrame - Usig JFrame frame is designed with panel and buttons
addButton - Adds a button to a container
addBall - Adds a bouncing ball to the canvas and starts a thread to make it bounce
ALGORITHM:
1. Create the class ball which implements a ball which moves and bounces of the edges of a
rectangle.
2. Using the move() method move the ball to the nect postion by reversing the direction if it
bits one of the edges.
3. Get the shapes of the ball at its current position.
4. Invoke the runnable() method to show the animated bouncing balls.
5. Using the sleep() method assign the time for ball to bounce in a given interval of time.
6. Construct the frame with the component for showing bouncing ball and start and close
buttons.
7. 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.
MULTITHREADED GUI APPLICATION
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.geom.*;
/**
A ball that moves and bounces off the edges of a
rectangle
* @version 1.33 2007-05-17
* @author Cay Horstmann
*/
class Ball
{
/**
Moves the ball to the next position, reversing direction
if it hits one of the edges
*/
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;
}
}
/**
Gets the shape of the ball at its current position.
*/
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
{
/**
* Add a ball to the panel.
* @param b the ball to add
*/
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>();
}
/**
* Shows animated bouncing balls.
* @version 1.33 2007-05-17
* @author Cay Horstmann
*/
public class BounceThread
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new BounceFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
/**
* A runnable that animates a bouncing ball.
*/
class BallRunnable implements Runnable
{
/**
* Constructs the runnable.
* @aBall the ball to bounce
* @aPanel the component in which the ball bounces
*/
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;
}
/**
* The frame with panel and buttons.
*/
class BounceFrame extends JFrame
{
/**
* Constructs the frame with the component for showing the bouncing ball and Start and Close
* buttons
*/
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);
}
/**
* Adds a button to a container.
* @param c the container
* @param title the button title
* @param listener the action listener for the button
*/
public void addButton(Container c, String title, ActionListener listener)
{
JButton button = new JButton(title);
c.add(button);
button.addActionListener(listener);
}
/**
* Adds a bouncing ball to the canvas and starts a thread to make it bounce
*/
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:
Result:
Thus the Multithreaded GUI application was compiled and executed successfully.
VIVA
Define GUI
Graphical User Interface (GUI) has graphics classes for developing application. There are two sets of
Java APIs for graphics programming: AWT (Abstract Windowing Toolkit) and Swing.Java Graphics
APIs - AWT and Swing - provide a huge set of reusable GUI components, such as button, text field,
label, choice, panel and frame for building GUI applications
Define java.awt package
The java.awt package contains the core AWT graphics classes.
Define java.awt.event package
The java.awt.event package supports event handling.
Define java.awt.geom package
The java.awt.geom package contains models for a 2D point like x and y axis.
Question Set
1. Develop a Java package with simple Stack and Queue classes. Use JavaDoc
comments for documentation.
2. Design a class for Complex numbers in Java. In addition to methods for basic
operations on complex numbers, provide a method to return the number of active
objects created.
3. Design a Date class similar to the one provided in the java.util package.
4. Develop with suitable hierarchy, classes for Point, Shape, Rectangle, Square, Circle,
Ellipse, Triangle, Polygon, etc. Design a simple test application to demonstrate
dynamic polymorphism.
5. Design a Java interface for ADT Stack. Develop two different classes that implement
this interface, one using array and the other using linked-list. Provide necessary
exception handling in both the implementations.
6. Write a Java program to read a file that contains DNA sequences of arbitrary length
one per line (note that each DNA sequence is just a String). Your program should sort
the sequences in descending order with respect to the number of 'TATA'
subsequences present. Finally write the sequences in sorted order into another file.
7. Develop a simple paint-like program that can draw basic graphical primitives in
different dimensions and colors. Use appropriate menu and buttons.
8. Develop a scientific calculator using even-driven programming paradigm of Java.
9. Develop a template for linked-list class along with its methods in Java.
10. Design a thread-safe implementation of Queue class. Write a multi-threaded
producer-consumer application that uses this Queue class.
11. Write a multi-threaded Java program to print all numbers below 100,000comthat are
both prime and fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a
thread that generates prime numbers below 100,000 and writes them into a pipe.
Design another thread that generates fibonacci numbers and writes them to another
pipe. The main thread should read both the pipes to identify numbers common to
both.
12. Develop a multi-threaded GUI application of your choice.
REFERENCES
http://www.java-examples.com/
www.tutorialspoint.com
http://www.ntu.edu.sg/home/ehchua/programming/java/J4a_GUI.html
“Programming with JAVA” By E.Balagurusamy
K. Arnold and J. Gosling, “The JAVA programming language”, Third edition, Pearson
Education, 2000.
Timothy Budd, “Understanding Object-oriented programming with Java”, Updated Edition,
Pearson Education, 2000.
C. Thomas Wu, “An introduction to Object-oriented programming with Java”, Fourth Edition,
Tata McGraw-Hill Publishing company Ltd., 2006.