0% found this document useful (0 votes)
13 views52 pages

Java Data Structures and Algorithms Guide

The document lists various experiments and programming tasks related to data structures and algorithms in Java, including linear search, binary search, stack and queue implementations, and payroll generation using inheritance. Each section outlines the aim, algorithm, and program code for the respective tasks. The results indicate successful execution of the programs for each experiment.

Uploaded by

umardude89
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views52 pages

Java Data Structures and Algorithms Guide

The document lists various experiments and programming tasks related to data structures and algorithms in Java, including linear search, binary search, stack and queue implementations, and payroll generation using inheritance. Each section outlines the aim, algorithm, and program code for the respective tasks. The results indicate successful execution of the programs for each experiment.

Uploaded by

umardude89
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

LIST OF EXPERIMENTS

[Link] DATE EXPERIMENT NAME PAGE SIGNATURE


NO.

1.A LINEAR SEARCH

1.B BINARY SEARCH

1.C SELECTON SEARCH

1.D INSERTION SEARCH

2.A STACK IMPLEMENTATION

2.B QUEUE IMPLEMENTATION

3. EMPLOYEE PAYROLL

4. ABSTRACT CLASS EXAMPLE

5. INTERFACES-DEVELOPING USER-DEFINED
INTERFACES

6. HANDLING USER-DEFINED EXCEPTION

7. MULTI-THREAD CONCEPT

8. FILE CONCEPT

9. FIND MAXIMUM ELEMENT USING GENERIC


FUNCTION

10. MINI PROJECT:TRAFFIC LIGHT


SIMULATION

11. DEVELOP A JAVA APPLICATION TO


IMPLEMENT CURRENCY CONVERTER
(DOLLAR TO INR, EURO TO INR, YEN TO
INR AND ICE VERSA), DISTANCE
CONVERTER (METER TO KM, MILES TP KM
AND VICE VERSA), TIME
CONVERTER(HOURS TO MINUTES,
SECONDS AMD VICE VERSA) USING
PACKAGES.
[Link].1 SOLVE PROBLEMS BY USING SEQUENTIAL SEARCH, BINARY SEARCH,
AND QUADRATIC SORTING ALGORITHMS (SELECTION, INSERTION)

[Link] Search

AIM:
To write java program to implement linear searching algorithm.

ALGORITHM:

Step 1:Start with the first item in the list.

Step 2:Compare the current item to the key.

Step [Link] the current value matches the key update with the location.

Step 4:Else repeat from 2.

PROGRAM:

class LinearSearch

static int linearSearch(int a[], int n, int val)

// Going through array sequencially

for (int i = 0; i < n; i++)

if (a[i] == val)

return i+1;

return -1;

public static void main(String args[])

int a[] = {55, 29, 10, 40, 57, 41, 20, 24, 45}; // given array

int val = 10; // value to be searched

int n = [Link]; // size of array

int res = linearSearch(a, n, val); // Store result


[Link]();

[Link]("The elements of the array are - ");

for (int i = 0; i < n; i++)

[Link](" " + a[i]);

[Link]();

[Link]("Element to be searched is - " + val);

if (res == -1)

[Link]("Element is not present in the array");

else

[Link]("Element is present at " + res +" position of array");

RESULT:

Thus the java program to perform linear searching algorithms was executed and verified
successfully.
[Link] SEARCH

AIM:
To write java program to implement binary searching algorithm.

ALGORITHM:

Step 1:Choose the middle element in the list.

Step 2:If it matches the middle element, its position in the list is returned.

Step 3:If the target values is ,less than or greater than the middle element, the search continues in the
lower or upper half of the array, respectively, eliminating the other half from consideration.

PROGRAM:

class BinarySearch

static int binarySearch(int a[], int beg, int end, int val)

int mid;

if(end >= beg)

mid = (beg + end)/2;

if(a[mid] == val)

return mid+1; /* if the item to be searched is present at middle */

/* if the item to be searched is smaller than middle, then it can only be in left subarray */

else if(a[mid] < val)

return binarySearch(a, mid+1, end, val);

/* if the item to be searched is greater than middle, then it can only be in right subarray */

else

return binarySearch(a, beg, mid-1, val);

}
}

return -1;

public static void main(String args[])

int a[] = {8, 10, 22, 27, 37, 44, 49, 55, 69}; // given array

int val = 37; // value to be searched

int n = [Link]; // size of array

int res = binarySearch(a, 0, n-1, val); // Store result

[Link]("The elements of the array are: ");

for (int i = 0; i < n; i++)

[Link](a[i] + " ");

[Link]();

[Link]("Element to be searched is: " + val);

if (res == -1)

[Link]("Element is not present in the array");

else

[Link]("Element is present at " + res + " position of array");

RESULT:

Thus the java program to perform binary searching algorithms was executed and verified
successfully.
[Link] SORT

AIM:
To write java program to implement selection sorting algorithm.

ALGORITHM:

Step 1:Set Min_Index to 0.

Step 2:Search for the smallest element in the array.

Step 3:Swap with value with the element at the Min_Index.

Step 4:Increment Min_Index to point to next element.

Step 5:Repeat until the complete array is sorted.

PROGRAM:

public class Selection

void selection(int a[]) /* function to sort an array with selection sort */

int i, j, small;

int n = [Link];

for (i = 0; i < n-1; i++)

small = i; //minimum element in unsorted array

for (j = i+1; j < n; j++)

if (a[j] < a[small])

small = j;

// Swap the minimum element with the first element

int temp = a[small];

a[small] = a[i];

a[i] = temp;

void printArr(int a[]) /* function to print the array */

{
int i;

int n = [Link];

for (i = 0; i < n; i++)

[Link](a[i] + " ");

public static void main(String[] args)

int a[] = { 91, 49, 4, 19, 10, 21 };

Selection i1 = new Selection();

[Link]("\nBefore sorting array elements are - ");

[Link](a);

[Link](a);

[Link]("\nAfter sorting array elements are - ");

[Link](a);

[Link]();

RESULT:

Thus the java program to perform selection sorting algorithms was executed and verified
successfully.
[Link] SORT

AIM:
To write java program to implement insertion sorting algorithm.

ALGORITHM:

Step 1:Choose the first two elements in the list.

Step 2:If it is sorted leave as it is.

Step 3:If not swap the element with the previous.

Step 4:Check whether the elements in the sub list is sorted.

Step 5:Repeat until list is sorted.

PROGRAM:

public class InsertionSort

/*Function to sort array using insertion sort*/

void sort(int arr[])

int n = [Link];

for (int i = 1; i < n; ++i)

int key = arr[i];

int j = i - 1;

/* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current
position */

while (j >= 0 && arr[j] > key)

arr[j + 1] = arr[j];

j = j - 1;

arr[j + 1] = key;

/* A utility function to print array of size n*/


static void printArray(int arr[])

int n = [Link];

for (int i = 0; i < n; ++i)

[Link](arr[i] + " ");

[Link]();

// Driver method

public static void main(String args[])

int arr[] = { 12, 11, 13, 5, 6 };

InsertionSort ob = new InsertionSort();

[Link](arr);

printArray(arr);

};

RESULT:

Thus the java program to perform insertion sorting algorithms was executed and verified
successfully.
[Link].2 DEVELOP STACK AND QUEUE DATA STRUCTURES USING CLASSES AND
OBJECTS

[Link] Implementation

AIM:
To write java program to develop Stack data structure using classes and objects.

ALGORITHM:

Step 1: push() method inserts an item at the top of the stack(i.e., above its current top element).

Step 2: pop() method removes the object at the top of the stack and returns that object from the
[Link] stack size will be decremented by one.

Step 3: isEmpty() method tests if the stack is empty or not.

Step 4: isFull() method tests if the stack is full or not.

Step 5: peek() method returns the object at the top of the stack without removing it from the stack or
+modifying the stack in any way.

Step 6: size() method returns the total number of elements presents in the stack.

PROGRAM:

// Stack implementation in Java

class Stack

// store elements of stack

private int arr[];

// represent top of stack

private int top;

// total capacity of the stack

private int capacity;

// Creating a stack

Stack(int size)

// initialize the array

// initialize the stack variables

arr = new int[size];


capacity = size;

top = -1;

// push elements to the top of stack

public void push(int x)

if (isFull()) {

[Link]("Stack OverFlow");

// terminates the program

[Link](1);

// insert element on top of stack

[Link]("Inserting " + x);

arr[++top] = x;

// pop elements from top of stack

public int pop()

// if stack is empty

// no element to pop

if (isEmpty())

[Link]("STACK EMPTY");

// terminates the program

[Link](1);

// pop element from top of stack

return arr[top--];

// return size of the stack

public int getSize()


{

return top + 1;

// check if the stack is empty

public Boolean isEmpty()

return top == -1;

// check if the stack is full

public Boolean isFull()

return top == capacity - 1;

// display elements of stack

public void printStack()

for (int i = 0; i <= top; i++)

[Link](arr[i] + ", ");

public static void main(String[] args)

Stack stack = new Stack(5);

[Link](1);

[Link](2);

[Link](3);

[Link]("Stack: ");

[Link]();

// remove element from stack

[Link]();
[Link]("\nAfter popping out");

[Link]();

RESULT:

Thus the java program to develop Stack data structures using classes and objects was
executed and verified successfully.
[Link] Implementation

AIM:
To write java program to develop Queue data structure using classes and objects.

ALGORITHM:

Step 1: The Enqueue() method inserts an item at the rear of the queue.

Step 2: The Dequeue() method removes the object from the front of the queue and returns it, thereby
decrementing queue size by one.

Step 3:Peek() method returns the object at the front of the queue without removing it.

Step 4:isEmpty() tests if the queue is empty or not.

Step 5: Size() method returns the total number of elements present in the queue.

PROGRAM:

public class Queue

int SIZE = 5;

int items[] = new int[SIZE];

int front, rear;

Queue() {

front = -1;

rear = -1;

// check if the queue is full

boolean isFull()

if (front == 0 && rear == SIZE - 1) {

return true;

return false;

// check if the queue is empty

boolean isEmpty()

{
if (front == -1)

return true;

else

return false;

// insert elements to the queue

void enQueue(int element)

// if queue is full

if (isFull())

[Link]("Queue is full");

Else

if (front == -1)

// mark front denote first element of queue

front = 0;

rear++;

// insert element at the rear

items[rear] = element;

[Link]("Insert " + element);

// delete element from the queue

int deQueue()

int element;

// if queue is empty
if (isEmpty())

[Link]("Queue is empty");

return (-1);

else

// remove element from the front of queue

element = items[front];

// if the queue has only one element

if (front >= rear)

front = -1;

rear = -1;

else

// mark next element as the front

front++;

[Link]( element + " Deleted");

return (element);

// display element of the queue

void display()

int i;

if (isEmpty())

[Link]("Empty Queue");
}

else

// display the front of the queue

[Link]("\nFront index-> " + front);

// display element of the queue

[Link]("Items -> ");

for (i = front; i <= rear; i++)

[Link](items[i] + " ");

// display the rear of the queue

[Link]("\nRear index-> " + rear);

public static void main(String[] args)

// create an object of Queue class

Queue q = new Queue();

// try to delete element from the queue

// currently queue is empty

// so deletion is not possible

[Link]();

// insert elements to the queue

for(int i = 1; i < 6; i ++)

[Link](i);

// 6th element can't be added to queue because queue is full

[Link](6);

[Link]();

// deQueue removes element entered first i.e. 1

[Link]();
// Now we have just 4 elements

[Link]();

RESULT:

Thus the java program to develop Queue data structures using classes and objects was
executed and verified successfully.
[Link].3
EMPLOYEE PAYROLL

AIM:
To develop a java application to generate pay slip for different category of employees using
the concept of inheritance

ALGORITHM:
1. Create the class employee with name, Empid, address, mailid, mobileno as members.
2. Inherit the classes programmer, asstprofessor,associateprofessor and professor from employee
class.
3. Add Basic Pay (BP) as the member of all the inherited classes.
4. Calculate DA as 97% of BP, HRA as 10% of BP, PF as 12% of BP, Staff club fund as 0.1% of BP.
5. Calculate gross salary and net salary.
6. Generate payslip for all categories of employees.
7. Create the objects for the inherited classes and invoke the necessary methods to display the Payslip.

PROGRAM:
import [Link].*;
class employee
{
int empid;
long mobile;
String name, address, mailid;
Scanner get = new Scanner([Link]);
void getdata()
{
[Link]("Enter Name of the Employee");
name = [Link]();
[Link]("Enter Mail id");
mailid = [Link]();
[Link]("Enter Address of the Employee:");
address = [Link]();
[Link]("Enter employee id ");
empid = [Link]();
[Link]("Enter Mobile Number");
mobile = [Link]();
}
void display()
{
[Link]("Employee Name: "+name);
[Link]("Employee id : "+empid);
[Link]("Mail id : "+mailid);
[Link]("Address: "+address);
[Link]("Mobile Number: "+mobile);
}
}
class programmer extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getprogrammer()
{
[Link]("Enter basic pay");
bp = [Link]();
}
void calculateprog()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
[Link]("************************************************");
[Link]("PAY SLIP FOR PROGRAMMER");
[Link]("************************************************");
[Link]("Basic Pay:Rs"+bp);
[Link]("DA:Rs"+da);
[Link]("PF:Rs"+pf);
[Link]("HRA:Rs"+hra);
[Link]("CLUB:Rs"+club);
[Link]("GROSS PAY:Rs"+gross);
[Link]("NET PAY:Rs"+net);
}
}
class asstprofessor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getasst()
{
[Link]("Enter basic pay");
bp = [Link]();
}
void calculateasst()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
[Link]("************************************************");
[Link]("PAY SLIP FOR ASSISTANT PROFESSOR");
[Link]("************************************************");
[Link]("Basic Pay:Rs"+bp);
[Link]("DA:Rs"+da);
[Link]("HRA:Rs"+hra);
[Link]("PF:Rs"+pf);
[Link]("CLUB:Rs"+club);
[Link]("GROSS PAY:Rs"+gross);
[Link]("NET PAY:Rs"+net);
}
}
class associateprofessor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getassociate()
{
[Link]("Enter basic pay");
bp = [Link]();
}
void calculateassociate()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
[Link]("************************************************");
[Link]("PAY SLIP FOR ASSOCIATE PROFESSOR");
[Link]("************************************************");
[Link]("Basic Pay:Rs"+bp);
[Link]("DA:Rs"+da);
[Link]("HRA:Rs"+hra);
[Link]("PF:Rs"+pf);
[Link]("CLUB:Rs"+club);
[Link]("GROSS PAY:Rs"+gross);
[Link]("NET PAY:Rs"+net);
}
}
class professor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getprofessor()
{
[Link]("Enter basic pay");
bp = [Link]();
}
void calculateprofessor()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
[Link]("************************************************");
[Link]("PAY SLIP FOR PROFESSOR");
[Link]("************************************************");
[Link]("Basic Pay:Rs"+bp);
[Link]("DA:Rs"+da);
[Link]("HRA:Rs"+hra);
[Link]("PF:Rs"+pf);
[Link]("CLUB:Rs"+club);
[Link]("GROSS PAY:Rs"+gross);
[Link]("NET PAY:Rs"+net);
}
}
/**
*
* @author CSE
*/
public class Salary {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int choice,cont;
do
{
[Link]("PAYROLL");
[Link](" [Link] \t [Link] PROFESSOR \t [Link]
PROFESSOR \[Link] ");
Scanner c = new Scanner([Link]);
choice=[Link]();
switch(choice)
{
case 1:
{
programmer p=new programmer();
[Link]();
[Link]();
[Link]();
[Link]();
break;
}
case 2:
{
asstprofessor asst=new asstprofessor();
[Link]();
[Link]();
[Link]();
[Link]();
break;
}
case 3:
{
associateprofessor asso=new associateprofessor();
[Link]();
[Link]();
[Link]();
[Link]();
break;
}
case 4:
{
professor prof=new professor();
[Link]();
[Link]();
[Link]();
[Link]();
break;
}
}
[Link]("Do u want to continue 0 to quit and 1 to continue ");
cont=[Link]();
}while(cont==1);
}
}

RESULT:

Thus the java program to implement employee payroll was executed and verified
successfully.
[Link].4A
ABSTRACT CLASS EXAMPLE

AIM:
To write a java program to calculate the area of rectangle, circle and triangle using the
concept of abstract class.

ALGORITHM:

1. Create an abstract class named shape that contains two integers and an empty method named
printarea().
2. Provide three classes named rectangle, triangle and circle such that each one of the classes extends
the class Shape.
[Link] of the inherited class from shape class should provide the implementation for the method
printarea().
[Link] the input and calculate the area of rectangle,circle and triangle .
5. In the shapeclass , create the objects for the three inherited classes and invoke the methods and
display the area values of the different shapes.

PROGRAM:
import [Link].*;
abstract class shape
{
int a,b;
abstract public void printarea();
}
class rectangle extends shape
{
public int area_rect;
@Override
public void printarea()
{
Scanner s=new Scanner([Link]);
[Link]("enter the length and breadth of rectangle");
a=[Link]();
b=[Link]();
area_rect=a*b;
[Link]("Length of rectangle "+a +"breadth of rectangle "+b);
[Link]("The area ofrectangle is:"+area_rect);
}
}
class triangle extends shape
{
double area_tri;
public void printarea()
{
Scanner s=new Scanner([Link]);
[Link]("enter the base and height of triangle");
a=[Link]();
b=[Link]();
[Link]("Base of triangle "+a +"height of triangle "+b);
area_tri=(0.5*a*b);
[Link]("The area of triangle is:"+area_tri);
}
}
class circle extends shape
{
double area_circle;
@Override
public void printarea()
{
Scanner s=new Scanner([Link]);
[Link]("enter the radius of circle");
a=[Link]();
area_circle=(3.14*a*a);
[Link]("Radius of circle"+a);
[Link]("The area of circle is:"+area_circle);
}
}
public class Shapeclass {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
rectangle r=new rectangle();
[Link]();triangle t=new triangle();
[Link]();
circle r1=new circle();
[Link]();
// TODO code application logic here
}
}

RESULT:

Thus the java program for abstract class was executed successfully.
[Link].4B
ABSTRACT CLASS EXAMPLE

AIM:
To write a java program to calculate the area of rectangle,circle and triangle using the concept of
abstract class.

ALGORITHM:
[Link] the program.
[Link] a class with the name Shape.
[Link] the Rectangle, Triangle, Circle extends Shape.
[Link] the objects to the individual classes.
[Link] the numberOfSides() on individual object.

PROGRAM:

import [Link].*;
import [Link].*;
abstract class Shape
{
abstract void numberOfSides();
}
Class Trapezoid extends Shape
{
Void numberOfSides()
{
[Link](“Trapezoidal has four sides”);
}
}
Class Triangle extends Shape
{
Void numberOfSides()
{
[Link](“Trapezoidal has three sides”);
}
}
Class Hexagon extends Shape
{
Void numberOfSides()
{
[Link](“Trapezoidal has sixsides”);
}
}
Class ShapeDemo
{
Public static void main()String args[])
{
Trapezoid t=new Trapezoid();
Triangle r=new Triangle();
Hexagon h=new Hexagon();
Shape s;
s=t;
[Link]();
s=r;
[Link]();
s=h;
[Link]();
}
}

RESULT:

Thus the java program for abstract class was executed successfully.
[Link].5
INTERFACES-DEVELOPING USER DEFINED INTERFACES

AIM:
To write a java program to develop user defined interfaces.

ALGORITHM:

1. Create an Interface named shape that contains two integers and an empty method named
printarea().
2. Provide classes named rectangle and circle such that each one of the classes extends the class
Shape.
[Link] of the inherited class from shape class should provide the implementation for the method
printarea().
[Link] the input and calculate the area of rectangle and circle
5. In the shapeclass , create the objects for the three inherited classes and invoke the methods and
display the area values of the different shapes.

PROGRAM:

interface Shape

void input();

void area();

class Circle implements Shape

int r = 0;

double pi = 3.14, ar = 0;

@Override

public void input()

r = 5;

@Override

public void area()


{

ar = pi * r * r;

[Link]("Area of circle:"+ar);

class Rectangle extends Circle

int l = 0, b = 0;

double ar;

public void input()

[Link]();

l = 6;

b = 4;

public void area()

[Link]();

ar = l * b;

[Link]("Area of rectangle:"+ar);

public class Demo

public static void main(String[] args) {

Rectangle obj = new Rectangle();

[Link]();

[Link]();

}
RESULT:

Thus the java program to implement user defined interface was created, executed and output
was verified successfully.
[Link].6
HANDLING USERDEFINED EXCEPTION

AIM:
To implement the user defined exception concept in java.

ALGORITHM:

[Link] a class which extends Exception class.

[Link] a constructor which receives the string as argument.

[Link] the Amount as input from the user.

[Link] the amount is negative , the exception will be generated.

[Link] the exception handling mechanism , the thrown exception is handled by the catch construct.

[Link] the exception is handled , the string “invalid amount “ will be displayed.

[Link] the amount is greater than 0 , the message “Amount Deposited “ will be displayed.

PROGRAM:

import [Link];

class NegativeAmtException extends Exception

String msg;

NegativeAmtException(String msg)

[Link]=msg;

public String toString()

return msg;

public class Userdefined

public static void main(String[] args)


{

Scanner s=new Scanner([Link]);

[Link]("Enter Amount:");

int a=[Link]();

try

if(a<0)

throw new NegativeAmtException("Invalid Amount");

[Link]("Amount Deposited");

catch(NegativeAmtException e)

[Link](e);

RESULT:

Thus a java program to implement user defined exception handling has been implemented and
executed successfully.
[Link].7
MULTITHREADING CONCEPT

AIM:
To implement a multithread application that has three threads. First thread generates random
integer for every second and if the value is even, second thread computes the square of number and
prints. If the value is odd, the third thread will print the value of cube of number.

ALGORITHM:

[Link] the program.

[Link] a class with the name “ even implements Runnable “and “odd implements Runnable”.

[Link] thread objects and Random class object.

[Link] the objects of our class to thread class.

[Link] the start method.

PROGRAM:

import [Link].*;

class even implements Runnable

public int x;

public even(int x)

this.x = x;

public void run()

[Link]("New Thread "+ x +" is EVEN and Square of " + x + " is: " + x *

x);

class odd implements Runnable

public int x;
public odd(int x)

this.x = x;

public void run()

[Link]("New Thread "+ x +" is ODD and Cube of " + x + " is: " + x * x * x);

class A extends Thread

public void run()

int num = 0;

Random r = new Random();

try

for (int i = 0; i < 5; i++)

num = [Link](100);

[Link]("Main Thread and Generated Number is " + num);

if (num % 2 == 0)

Thread t1 = new Thread(new even(num));

[Link]();

else

Thread t2 = new Thread(new odd(num));

[Link]();

}
[Link](1000);

[Link]("--------------------------------------");

catch (Exception ex)

[Link]([Link]());

public class multithreadprog

public static void main(String[] args)

A a = new A();

[Link]();

RESULT:

Thus the multithread program was executed successfully.


[Link].8
FILE CONCEPT

AIM:
To write a java program that reads a file name from the user, displays information about whether the
file exists, whether the file is readable, or writable, the type of file and the length of the file in bytes.
ALGORITHM:
[Link] a class filedemo. Get the file name from the user .
[Link] the file functions and display the information about the file.
[Link]() displays the name of the file.
[Link]() diplays the path name of the file.
[Link] () -This method returns the pathname string of this abstract pathname’s parent, or null if
this pathname does not name a parent directory.
[Link]() – Checks whether the file exists or not.
7. canRead()-This method is basically a check if the file can be read.
8. canWrite()-verifies whether the application can write to the file.
9. isDirectory() – displays whether it is a directory or not.
10. isFile() – displays whether it is a file or not.
11. lastmodified() – displays the last modified information.
[Link]()- displays the size of the file.
13. delete() – deletes the file.
[Link] the predefined functions abd display the iformation about the file.

PROGRAM:

import [Link].*;
import [Link].*;
class filedemo
{
public static void main(String args[])
{
String filename;
Scanner s=new Scanner([Link]);
[Link]("Enter the file name ");
filename=[Link]();
File f1=new File(filename);
[Link]("*****************");
[Link]("FILE INFORMATION");
[Link]("*****************");
[Link]("NAME OF THE FILE "+[Link]());
[Link]("PATH OF THE FILE "+[Link]());
[Link]("PARENT"+[Link]());
if([Link]())
[Link]("THE FILE EXISTS ");
else
[Link]("THE FILE DOES NOT ExISTS ");
if([Link]())
[Link]("THE FILE CAN BE READ ");
else
[Link]("THE FILE CANNOT BE READ ");
if([Link]())
[Link]("WRITE OPERATION IS PERMITTED");
else
[Link]("WRITE OPERATION IS NOT PERMITTED");
if([Link]())
[Link]("IT IS A DIRECTORY ");
else
[Link]("NOT A DIRECTORY");
if([Link]())
[Link]("IT IS A FILE ");
else
[Link]("NOT A FILE");
[Link]("File last modified "+ [Link]());
[Link]("LENGTH OF THE FILE "+[Link]());
[Link]("FILE DELETED "+[Link]());
}
}

RESULT:

Thus the java program to display the file details was executed successfully.
[Link].9
FIND MAXIMUM ELEMENT USING GENERIC FUNCTION

AIM:
To write a java program to find maximum element using generic function.
ALGORITHM:
[Link] the program.
[Link] the class named as MainClass.
[Link] the generic function x,y,z using function template.
[Link] the maximum of three elements x,y,z.
PROGRAM:
class MyClass<T extends Comparable<T>>
{
T[] vals;
MyClass(T[] o)
{
vals = o;
}
public T min()
{
T v = vals[0];
for(int i=1; i < [Link]; i++)
if(vals[i].compareTo(v) < 0)
v = vals[i];
return v;
}
public T max()
{
T v = vals[0];
for(int i=1; i < [Link];i++)
if(vals[i].compareTo(v) > 0)
v = vals[i];
return v;
}
}
class gendemo
{
public static void main(String args[])
{
int i;
Integer inums[]={10,2,5,4,6,1};
Character chs[]={'v','p','s','a','n','h'};
Double d[]={20.2,45.4,71.6,88.3,54.6,10.4};
MyClass<Integer> iob = new MyClass<Integer>(inums);
MyClass<Character> cob = new MyClass<Character>(chs);
MyClass<Double>dob = new MyClass<Double>(d);
[Link]("Max value in inums: " + [Link]());
[Link]("Min value in inums: " + [Link]());
[Link]("Max value in chs: " + [Link]());
[Link]("Min value in chs: " + [Link]());
[Link]("Max value in chs: " + [Link]());
[Link]("Min value in chs: " + [Link]());
}
}

RESULT:

Thus the java program to find maximum using generic function was executed successfully.
[Link].10
MINI PROJECT:TRAFFIC LIGHT SIMULATION

AIM:
To simulate a Traffic Light. The program lets the use select one of three lights: red, yellow or
green with radio buttons. On selecting radio button, an appropriate message with “stop” or “Ready” or
“Go” should appear above the button in selected color. Initially, there is no message shown.
ALGORITHM:
[Link] the program.
[Link] a class with the name A implements ItemListener.
[Link] the ButtonGroup, JRadiobuttons, JPanel.
[Link] to JFrame.
[Link] the components to the jFrame.
[Link] the JFrame.
PROGRAM:
import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

public class Traffic_Signal

extends JFrame implements ItemListener

JRadioButton jr1;

JRadioButton jr2;

JRadioButton jr3;

JTextField j1 = new JTextField(10);

ButtonGroup b = new ButtonGroup();

String msg = " ";

int x = 0, y = 0, z = 0;

public Traffic_Signal(String msg)

super(msg);

setLayout(new FlowLayout());
jr1 = new JRadioButton("Red");

jr2 = new JRadioButton("Yellow");

jr3 = new JRadioButton("Green");

[Link](this);

[Link](this);

[Link](this);

add(jr1);

add(jr2);

add(jr3);

[Link](jr1);

[Link](jr2);

[Link](jr3);

add(j1);

addWindowListener(new WindowAdapter()

public void windowClosing(WindowEvent e)

[Link](0);

});

public void itemStateChanged(ItemEvent ie)

if ([Link]() == jr1)

if ([Link]() == 1)

msg = "Stop!";

x = 1;

repaint();

}
else

msg = "";

if ([Link]() == jr2)

if ([Link]() == 1)

msg = "Get Ready to go!";

y = 1;

repaint();

else

msg = "";

if ([Link]() == jr3)

if ([Link]() == 1)

msg = "Go!!";

z = 1;

repaint();

else

msg = "";

}
[Link](msg);

public void paint(Graphics g)

[Link](100, 105, 110, 270);

[Link](120, 150, 60, 60);

[Link](120, 230, 60, 60);

[Link](120, 300, 60, 60);

if (x == 1)

[Link]([Link]);

[Link](120, 150, 60, 60);

[Link]([Link]);

[Link](120, 230, 60, 60);

[Link]([Link]);

[Link](120, 300, 60, 60);

x = 0;

if (y == 1)

[Link]([Link]);

[Link](120, 150, 60, 60);

[Link]([Link]);

[Link](120, 230, 60, 60);

[Link]([Link]);

[Link](120, 300, 60, 60);

y = 0;

if (z == 1)

[Link]([Link]);
[Link](120, 150, 60, 60);

[Link]([Link]);

[Link](120, 230, 60, 60);

[Link]([Link]);

[Link](120, 300, 60, 60);

z = 0;

public static void main(String args[])

JFrame jf = new Traffic_Signal("Traffic Light");

[Link](500, 500);

[Link](true);

RESULT:

Thus the java program for Traffic Light Simulation has been simulated successfully.
[Link].11 Develop a java application to implement currency converter (Dollar to INR, Euro to
INR, Yen to INR and ice versa), distance converter (meter to KM, miles tp KM and
vice versa), time converter(hours to minutes, seconds amd vice versa) using
packages.

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

ALGORITHM:
[Link] a Package currency conversion and place the class currency under the package
[Link] the methods to perform currency conversion from dollar to rupee, rupee to dollar, euro to
rupee, rupee to euro , yen to rupee and rupee to yen.
[Link] the package distance converion and create the class distance within the package
[Link] the methods to convert from meter to km, km to meter, miles to km, km to miles
[Link] the package time conversion and create the class timer.
[Link] the methods to convert from hours to minutes ,hours to seconds , minutes to hours and
seconds to hours
[Link] a class and import the packages currency conversion, distance conversion and time
conversion.
[Link] the objects for the class currency, distance and timer.
[Link] the choice from the user and invoke the methods to perform the corresponding conversion and

display the value.

PROGRAM:

package currencyconversion;
import [Link].*;
public class currency
{
double inr,usd;
double euro,yen;
Scanner in=new Scanner([Link]);
public void dollartorupee()
{
[Link]("Enter dollars to convert into Rupees:");
usd=[Link]();
inr=usd*67;
[Link]("Dollar ="+usd+"equal to INR="+inr);
}
public void rupeetodollar()
{
[Link]("Enter Rupee to convert into Dollars:");
inr=[Link]();
usd=inr/67;
[Link]("Rupee ="+inr+"equal to Dollars="+usd);
}
public void eurotorupee()
{
[Link]("Enter euro to convert into Rupees:");
euro=[Link]();
inr=euro*79.50;
[Link]("Euro ="+euro +"equal to INR="+inr);
}
public void rupeetoeuro()
{
[Link]("Enter Rupees to convert into Euro:");
inr=[Link]();
euro=(inr/79.50);
[Link]("Rupee ="+inr +"equal to Euro="+euro);
}
public void yentorupee()
{
[Link]("Enter yen to convert into Rupees:");
yen=[Link]();
inr=yen*0.61;
[Link]("YEN="+yen +"equal to INR="+inr);
}
public void rupeetoyen()
{
[Link]("Enter Rupees to convert into Yen:");
inr=[Link]();
yen=(inr/0.61);
[Link]("INR="+inr +"equal to YEN"+yen);
}
}
package distanceconversion;
import [Link].*;
public class distance
{
double km,m,miles;
Scanner sc = new Scanner([Link]);
public void kmtom()
{
[Link]("Enter in km ");
km=[Link]();
m=(km*1000);
[Link](km+"km" +"equal to"+m+"metres");
}
public void mtokm()
{
[Link]("Enter in meter ");
m=[Link]();
km=(m/1000);
[Link](m+"m" +"equal to"+km+"kilometres");
}
public void milestokm()
{
[Link]("Enter in miles");
miles=[Link]();
km=(miles*1.60934);
[Link](miles+"miles" +"equal to"+km+"kilometres");
}
public void kmtomiles()
{
[Link]("Enter in km");
km=[Link]();
miles=(km*0.621371);
[Link](km+"km" +"equal to"+miles+"miles");
}
}
package timeconversion;
import [Link].*;
public class timer
{
int hours,seconds,minutes;
int input;
Scanner sc = new Scanner([Link]);
public void secondstohours()
{
[Link]("Enter the number of seconds: ");
input = [Link]();
hours = input / 3600;
minutes = (input % 3600) / 60;
seconds = (input % 3600) % 60;
[Link]("Hours: " + hours);
[Link]("Minutes: " + minutes);
[Link]("Seconds: " + seconds);
}
public void minutestohours()
{
[Link]("Enter the number of minutes: ");
minutes=[Link]();
hours=minutes/60;
minutes=minutes%60;
[Link]("Hours: " + hours);
[Link]("Minutes: " + minutes);
}
public void hourstominutes()
{
[Link]("enter the no of hours");
hours=[Link]();
minutes=(hours*60);
[Link]("Minutes: " + minutes);
}
public void hourstoseconds()
{
[Link]("enter the no of hours");
hours=[Link]();
seconds=(hours*3600);
[Link]("Minutes: " + seconds);
}
}
import [Link].*;
import [Link].*;
import currencyconversion.*;
import distanceconversion.*;
import timeconversion.*;
class converter
{
public static void main(String args[])
{
Scanner s=new Scanner([Link]);
int choice,ch;
currency c=new currency();
distance d=new distance();
timer t=new timer();
do
{
[Link]("[Link] to rupee ");
[Link]("[Link] to dollar ");
[Link]("[Link] to rupee ");
[Link]("4..rupee to Euro ");
[Link]("[Link] to rupee ");
[Link]("[Link] to Yen ");
[Link]("[Link] to kilometer ");
[Link]("[Link] to meter ");
[Link]("[Link] to kilometer ");
[Link]("[Link] to miles");
[Link]("[Link] to Minutes");
[Link]("[Link] to Seconds");
[Link]("[Link] to Hours");
[Link]("[Link] to Hours");
[Link]("Enter ur choice");
choice=[Link]();
switch(choice)
{
case 1:
{
[Link]();
break;
}
case 2:
{
[Link]();
break;
}
case 3:
{
[Link]();
break;
}
case 4:
{
[Link]();
break;
}
case 5:
{[Link]();
break;}
case 6 :
{
[Link]();
break;
}
case 7 :
{
[Link]();
break;
}
case 8 :
{
[Link]();
break;
}
case 9 :
{
[Link]();
break;
}
case 10 :
{
[Link]();
break;
}
case 11 :
{
[Link]();
break;
}
case 12 :
{
[Link]();
break;
}
case 13 :
{
[Link]();
break;
}
case 14 :
{
[Link]();
break;
}}
[Link]("Enter 0 to quit and 1 to continue ");
ch=[Link]();
}while(ch==1);
}
}
RESULT:

Thus the java application to implement currency converter, distance converter and time
converter was implemented and executed successfully.

You might also like