0% found this document useful (0 votes)
15 views85 pages

Orig Oops Rec

study
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)
15 views85 pages

Orig Oops Rec

study
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
You are on page 1/ 85

Ex.

no:1)a) Sequential search

Date:

Aim:

To develop the java program to perform Sequential search

Algorithm:

Step 1: start

Step 2:Let the element to be search be x.

Step 3:Start from the leftmost element of arr[] and one by one compare x with each
element of arr[].

Step 4:If x matches with an element then return that index.

Step 5:If x doesn’t match with any of elements then return -1.

Step6: stop
Program:

import java.io.

import java.util.*

public class Sequential

public static void main(String[] args)

int Index,size,i,key;

Scanner sc= new. Scanner(System.in);

System.out.println("Enter size of an array");

Size=sc.nextInt();

int arr[]= new int[size];

System.out.println("Enter array elements");

For(i=0;i<size;i++)

arr[i]-se.nextInt();

System.out.println("Enter elements to search");

key=sc.nextInt();

Index=search(arr,key);

If(Index>-1)

System.out.println("Element found at index+Index);


}

else

System.out.println("element is not found");

public static int search(int[] x,int element)

for(int j=0;j<x.length;j++)

if(x[]== element)

return j;

return -1;

}
Output:

Enter size of an array

Enter array element

10

50

70

25

47

Enter element to search

47

Element found at index:4

Result:

Thus the application for sequencial search has been successfully executed
Ex.no:1)b) BinarySearch

Date:

Aim:

To develop the java program to perform binary search

Algorithm:

Step1:start

Step 2.First, compare key with the middle element.

Step 3: If x matches with the middle element, then you have to return the mid
index.

Step 4: Else, If key is greater than the mid element, then x can only lie in the right
side half array after the mid element. Hence you recur the right half.

Step 5: Else, if (key is smaller) then recur for the left half.

Step 6:stop
Program;

import java.io.*;

import java.util.";

class BinarySearch

public static void binarySearch(int arr[], int first, int last, int key)(

int mid = (first + last)/2;

while( first <= last){

if ( arr[mid] < key){

first = mid + 1;

}else if ( arr[mid] == key){

System.out.println("Element is found at index: " + mid);

break;

}else{

last = mid-1;

mid = (first + last)/2;

if (first > last){

System.out.println("Element is not found!");

}
public static void main(String args[])

/*int arr[]={10,20,30,40,50};

int key = 30; */

int Index,size,l,key:

Scanner sc=new Scanner(System.in);

System.out.println("Enter size of an array");

size=sc.nextInt();

int arr[]=new int[size];

System.out.println("Enter array elements");

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

arr[i]=sc.nextInt();

System.out.println("Enter elements to search");

key-sc.nextInt();

int last arr.length-1;

binarySearch(arr,0,last,key);

}
OUTPUT:

CrUsers NIPDesktop>Java BinarySearch Enter size of an array

Enter array elements

40

50

98 Enter elements to search

Element is found at index: 4 C:\UsersNHP\Desktop>

Result:

Thus the application for binary search has been successfully executed
Ex.no:1)c) Selection Sort

Date:

Aim:

To develop java program to perform selection sort

Algorithm:

Step 1: Set i to 0

Step 2 : Search for the smallest element in the array

Step 3 : Swap with value with the element at the i

Step 4 : Increment i to point to next element

Step 5 : Repeat until the complete array is sorted

Program:

import java.io.*;

import java.util.*;

public class Selection

public static void main(String args[])

int size, i, j, temp:

int arr[]= new int[50]:

Scanner scan new Scanner(System.in);

System.out.print("Enter Array Size: ");


size=scan.nextInt();

System.out.print("Enter Array Elements: ");

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

arr[i]-scan.nextInt();

System.out.print("Sort the Array using Selection Sort Technique..\n");

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

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

if(arr[i]> arr[j])

temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

System.out.print("After Sorting array elements are \n");

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

System.out.print(arr[i]+" ");
}

Output

: C:\Users\HP\Desktop>Javac Selection.java

C:\Users\HP\Desktop>Java Selection

Enter Array Size : 9 Enter Array Elements : 188

40

39

54

51

22

14

4 After Sorting array elements are : 4 14 22 40 54 61 89 90 189 C:\Users\HP\


Desktop>

Result:

Thus the application for selection sort has been executed successfully
Ex.no:1)d Insertion Sort

Date:

Aim:

To develop the java program to perform insertion sort

Algorithm:

Step 1: start

Step 2:Iterate from arr[1] to arr[N] over the array.

Step 3.Compare the current element (key) to its predecessor.

Step 4:If the key element is smaller than its predecessor, compare it to the elements
before. Move the greater elements one position up to make space for the swapped
element.

Step 5:To sort an array of size N in ascending order

Program:

import java.io.

import java.util.*;

public class InsertionSort

public static void insertionSort(int array[])

int n = array.length;

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

{
int key = array[J];

int i=j-1;

while ((i > -1) && ( array [i]> key))

array [i+1] = array [i];

i--;

public static void main(String a[])

int[] arr1(9.14,3,2,43,11,58,22);

System.out.println("Before Insertion Sort");

for(int i=0;i<arrl.length;i++)

System.out.print(arr1[i]+" ");

System.out.println():

insertionSort(arr1);

System.out.println("After Insertion Sort"); for(int i=0;i<arr1.length;i++)

System.out.print(arr1[i]+" ");

}
Output:

Supere Sireertop/Javac Insertionsort Java

C:\Users\HP\Desktop>java InsertionSort Before Insertion Sort

9 14 3 2 43 11 58 22 After Insertion Sort 2 39 11 14 22 43 58

C:\Users\HP\Danktop>

Result:

Thus the application for insertion sort has been successfully executed
Ex.no:2)a)

Date: Stack Implementation

Aim:

To develop a java application for stack implementation

Algorithm:

1.start

2.push inserts an item at the top of the stack (i.e., above its current top element).
3.pop removes the object at the top of the stack and returns that object from the
function. The stack size will be decremented by one.
4.peek returns the object at the top of the stack without removing it from the stack
or modifying the stack in any way.
5.Search function used to find the particular element in the stack.

Program:

import java.io.*;

import java.util.*;

class Stackcode

// Pushing element on the top of the stack

static void stack_push(Stack<Integer> stack)

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


{

stack.push(i);

// Popping element from the top of the stack

static void stack_pop(Stack<Integer> stack)

System.out.println("Pop Operation:");

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

Integer y = (Integer) stack.pop();

System.out.println(y);

// Displaying element on the top of the stack

static void stack_peek(Stack<Integer> stack)

Integer element = (Integer) stack.peek();

System.out.println("Element on stack top: " + element);

}
// Searching element in the stack

static void stack_search(Stack<Integer> stack, int element)

Integer pos = (Integer) stack.search(element);

if(pos == -1)

System.out.println("Element not found");

else

System.out.println("Element is found at position: " + pos);

public static void main (String[] args)

Stack<Integer> stack = new Stack<Integer>();

stack_push(stack);

stack_pop(stack);

stack_push(stack);

stack_peek(stack);

stack_search(stack, 2);

stack_search(stack, 6);
}

Output

C:\Users\HP\Desktop>javac Stackcode.java

C:\Users\HP\Desktop>java Stackcode

Pop Operation:

Element on stack top: 9

Elenent is found at position: 8 Element is found at position: 4

C:\Users\HP\Desktop>

Result:

Thus the application for stack implantation has been successfully executed
Ex.no: 2)b QUEUE IMPLEMENTATION

Date:

Aim:

To develop the java program to perform queue implementation

Algorithm:

1.start

2.add an element to the end of the queue A

3.add an element to the end of the queue B

4.add an element to the end of the queue C

5.add an element to the end of the queue D

6..get the value of the front of queue without removing it peek ()

7.check if the queue is empty


Program:

//import java.util.LinkedList;

import java.util.*;//Queue;

class Que

public static void main(String[] args)

Queue<String> queue = new LinkedList<String>();

queue.add("A"); // Insert `A` into the queue

queue.add("B"); // Insert `B` into the queue

queue.add("C"); // Insert `C` into the queue

queue.add("D"); // Insert `D` into the queue

System.out.println("The front element is " + queue.peek());

queue.remove(); // removing the front element (`A`)

queue.remove(); // removing the front element (`B`)

System.out.println("The front element after remove " + queue.peek());

System.out.println("The queue size is " + queue.size());

if (queue.isEmpty()) {

System.out.println("The queue is empty");

else {
System.out.println("The queue is not empty");

}
Output:

C:\Users\HP Desktop Javac que Java Que.java:8: error: cannot find symbol
Queue<String> queue = new LinkedList<String><>;

symbol: class LinkedList

location: class Que

1 error

C:\Users\HP\Desktop>javac Que.java

C:\Users\HP\Desktop>java Que The front element is A

The front element is C The queue size is 2 The queue is not empty

C:\Users\HP\Desktop>javac Que.java

C:\Users\HP\Desktop>java Que The front element is A

The front element after remove C The queue size is 2 The queue is not empty

Result:

Thus the application for queue implementation has been successfully


executed
Ex.no:3 GENERATING EMPLOYEE PAYROLL DETAILS

AIM:

To develop a java application for generating pay slips of employees with


their gross and net salary.

ALGORITHM:

1. The package keyword is used to create a package in java.

2. Create a class Employee inside a package name employee.

3. Class Employee contains Emp_name, Emp_id, Address, Mail id, Mobile_no as


members

4. By using Constructor initialize the instance variable of Employee class and


display method is used to print employee details.

5. Create classes Programmer, Assistant Professor, Associate Professor and


Professor thatextends Employee class and define necessary constructor for sub
classes.

6. Each sub classes has its own instance variable like bPay and des.

7. Override the paySlip method in each sub class to calculate the cross and net
salary

8.by using super() method sub class initialize the super class conductor

9.import employee package and create the object for employee class

10.create different employee object to add array list<> class

11.display employee method is used to display all employee play slip details
Program:

Package employee;

public class Employee

Private string name;

Private string id;

Private string address;

Private string mailid;

Private string moblieNo;

Public Employee(String name, String id,String id, String address,String


mailId,String mobile No)

this.name=name;

this.id=id;

this.address=address;

this.mailId=mailId;

this.moblieNo= moblieNo;

public void display()

System.out.println("Emp_Name: "+name+""+"Emp_id: "+id);


System.out.println("Address: " + address);

System.out.println("Mail_id: "+mailld + "\t" + "Mobile_no: " + mobileNo);

Public void paySlip()

package employee;

public class Programmer extends Employee

private float bPay;

private String des;

public Programmer(String name, String id, String address, String mailld, String
mobileNo,

float bPay, String des)

super(name, id, address, mailld, mobileNo);

this.bPay =bPay;

this.des=des;

}
Public void payslip()

float da=bPay *97/100;

float hra=bPay* 10/100;

double grossSalary=bPay + da + hra;

float pf=bPay* 12/100;

double scf=bPay 0.1/100;

double netSalary=grossSalary-pf-scf;

System.out.println(“---------Employee Pay Slips---------”);

Super.display();

System.out.println(“Designation:”+des);

System.out.println(“Basic_pay:”+bPay);

System.out.println(“Gross Salary:”=gross Salary+”\t”+”Net


Salary:”+”netSalary”);

System.out.println(“---------End of the statement---------”);

package employee;

public class Assistant Professor extends Employee

private float bPay;

private String des;

public Assistant Professor(String name, String id, String address, String mailld,
String

mobileNo, float bPay, String des)


{

super(name, id, address, mailld, mobileNo);

this.bPay Pay;

this.des-des;

public void payslip

float da= bPay* 97/100;

float hra=bPay *10/100;

double grossSalary=bPay +da+hra;

float pf=bPay* 12/100;

double scf=bPay* 0.1/100;

double netSalary grossSalary =pf-scf;

System.out.println("- -----Employee Pay Slips-------“);

super.display();

System.out.println("Designation: "+des);

System.out.println("Basic_Pay: "+bPay);

System.out.println(Gross Salary: “+ grossSalary+ “\t” + “Net Salary: “


+netSalary);

System.out.println(“____________End of the Statements___________”);

Package employee;
Public class Associate Professor extends Employee

Private floar bpay;

Private String des;

Public Associate Professor(String name, String id, String address, String mailld,
String mobileNo, float bpay, string des)

Super(name,id,address,mailld, mobileNo);

this.bPay= bPay;

this.des =des;

public void payslip()

float da=bPay 97/100;

float hra =bPay 10/100;

double grossSalary= bPay +da+hra;

float pf=bPay 12/100;

double scf-bPay 0.1/100;

double netSalary =grossSalary - pf-scf;

System.out.println("__________ Employees Pay Slips ____________”);

super.display();

System.out.println("Designation: "+des);

System.out.println("Basic_Pay: "+bPay);
System.out.println("Gross Salary: "+ grossSalary + "u" + "Net Salary:
"+netSalary);

System.out.println("__________End of the Statements ___________");

package employee;

public class Professor extends Employee

private float bPay;

private String des;

public Professor(String name, String id, String address, String mailld, String
mobileNo,float bpay,String des)

Super(name,id,address,mailld, mobileNo);

this.bpay=bpay;

this.des=des;

Public void paySlip()

float da=bpay*97/100;

float hra=bpay*10/100;

double grossSalary=bpay+da+hra;

float pf+bpay*12/100;
double scf=bpay*0.1/100;

double net salary=grossSalary-pf-scf;

system.out.println(“________Employees Pay Slips_________”);

super.display();

System.out.println("Designation: "+des);

System.out.println("Basic_Pay: "+bPay);

System.out.println("Gross Salary: "+ grossSalary + "\t"+"Net Salary: " +


netSalary);

System.out.println("_______End of the Statements ________");

import employee.*;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Scanner;

public class Emp

Employee e;

ArrayList<Employee> obj= new ArrayList();

Scanner get new Scanner(System.in);

public void addEmployee()

System.out.println("Enter the Emp_Name:");


String name = get.next();

System.out.println("Enter the Emp_id:");

String id= get.next();

System.out.println("Enter the Address:");

String address = get.next();

System.out.println(“Enter the Mail_id:”);

String mailld=get.next();

System.out.println(“Enter the Mobile_no:”);

String mobileNo=get.next();

System.out.println(“Enter the Designation:”);

String des= get.next();

System.out.println(“Enter the Basic_Pay:”);

Float bpay=get.nextFloat();

If(des.equalsIgnoreCase(“Programmer”))

e= new programmer (name,id,address,mailld, mobileNo, bpay, des);

obj.add(e);

else if(des.equalsIgnoreCase("Assistant Professor"))

e= new Assistant Professor(name, id, address, mailld, mobileNo, bPay,


des);
obj.add(e);

else if(des.equalsIgnoreCase("Associate Professor"))

e=new Associate Professor(name, id, address, mailld, mobileNo, bPay,


des);

obj.add(e);

public void displayEmployee()

for(Employee e:obj)

e.paySlip();

public static void main(String args[]) throws IOException

Emp x= new Emp();

String check;

do
{

x.addEmployee();

System.out.println("Do you what continue press 'y'"');

check-x.get.next();

while(check.equalsIgnoreCase("y"));

x.displayEmployee();

}
}

OUTPUT:

D:\>javac Emp java

D:\>java Emp

Enter the Emp Name:

Suresh

Enter the Emp_id:

E708

Enter the Address:


cuddalore

Enter the Mail_id: [email protected]

Enter the Mobile_no:

7894561230

Enter the Designation: Programmer

Enter the Basic_Pay:

7500

Do you what continue press 'y'

Enter the Emp Name:

Rakesh

Enter the Emp_id:

E705

Enter the address:

pondy

Enter the Mail id:

[email protected]

Enter the Mobile no:

4567891230

Enter the Designation:

Professor

Enter the Basic_Pay:

15000
Do you wnat continue press 'y'

Enter the Emp_Name:

kumar

Enter the Emp_id:

E405

Enter the Address:

madurai

Enter the Mail id:

[email protected]

Enter the Mobile_no:

1237894560

Enter the Designation:

Assistant Professor

Enter the Basic_Pay:

18000

Do you what continue press 'y

Enter the Emp_Name:

Naresh

Enter the Emp_id:

Enter the Address:

[email protected]
Enter the Mobile no

E102 villupuram

Enter the Mail id:

9873214560

Enter the Designation:

20000

Do you what continue press 'y' Π

Associate Professor Enter the Basic_Pay:

10

Employees Pay Slips

Emp Name: Suresh Emp_id:

E708

Address cuddalore

Mail_id:

[email protected]

Mobile_no: 7894561230

Designation:

Programmer

Basic Pay:

7500.0

Gross Salary:

15525.0

Net Salary:
14617.5

End of the Statements Employees Pay Slips

Emp Name:

Rakesh Emp_id: E705

Address:

pondy

Mobile_no:

4567891230

Gross Salary:

31050.0

Net Salary:

29235.0

Mail id:

[email protected]

Designation:

Professor Basic Pay:

15000.0

End of the Statements

Employees Pay Slips

Emp kumar

Emp_id: E405

Address
madurai

Mail id

[email protected]

Designation: Assistant Professor

Basic Pay:

18000.0

Mobile_no:

1237894560

Gross Salary:

37260.0

Net Salary:

35082.0

End of the Statements

Employees Pay Slips. Emp_id:

E102

Emp Name:

Naresh

Address:

villupuram

Mail id:

[email protected]

Mobile_no:
9873214560

Designation:

Associate Professor

Basic Pay: 20000.0

Gross Salary:

41400.0

Net Salary:

38980.0

End of the Statements

DS

RESULT:

Thus the application for generating pay slips of employees with their gross and net
salary has been successfully executed
Ex.no: 4 Area of Rectangle, Triangle, and Circle using abstract class

Date:

AIM:
To develop a java application for area of rectangle , triangle and
circle

Algorithm:
Step1: start
Step2: initialize the abstract class shapes
Step3: initialize the length and breadth
Step4: extent the class rectangle and print Area of rectangle is
length*breadth
Step5: extent the class triangle and print Area of triangle is
(breadth*length)/2
Step6: extent the class circle and print Area of circle is
(Math.PI*breadth*breadth))
Step7: create a new class for all shapes and print the values
Step8: stop

program:
import java.lang.*;
import java.io.*;
abstract class Shapes{
int length=3;
int breadth=4;
void printArea();
}
class Rectangle extends Shapes{
void printArea() {
System.out.println("Area of rectangle : "+length*breadth);
}
}
class Triangle extends Shapes{
void printArea(){
System.out.println("Area of triangle : "+(breadth*length)/2);
}
}
class Circle extends Shapes{
void printArea() {
System.out.println("Area of circle : "+
(Math.PI*breadth*breadth));
}
}
public class Main {
public static void main(String[] args){
Shapes rectangle = new Rectangle();
Shapes triangle = new Triangle();
Shapes circle = new Circle();
rectangle.printArea();
triangle.printArea();
circle.printArea();
}
}

Output:
Area of rectangle : 12
Area of triangle : 6
Area of circle : 50.26548245743669

RESULT:
Thus the application for area of rectangle , triangle and circle
Ex.no:5 Area of Rectangle, Triangle, and Circle using
interface

Date:

AIM:
To develop a java application for area of rectangle , triangle and
circle using interface

Algorithm:
Step1: start
Step2: initialize the interface shapes and declare the value of length and
breadth
Step3: implement the class rectangle in shapes print Area of rectangle is
length*breadth
step4: implement the class triangle in shapes print Area of triangle is
breadth*length /2
step5: implement the class circle in shapes print Area of circle is
Math.PI*breadth*breadth
Step6: create the new class for all the shapes and print the class
Step7: stop

program:
import java.lang.*;
import java.io.*;
interface Shapes{
int length=3;
int breadth=4;
static void printArea();
}
class Rectangle implements Shapes{
void printArea() {
System.out.println("Area of rectangle : "+length*breadth);
}
}
class Triangle implements Shapes{
void printArea(){
System.out.println("Area of triangle : "+(breadth*length)/2);
}
}
class Circle implements Shapes{
void printArea() {
System.out.println("Area of circle : "+
(Math.PI*breadth*breadth));
}
}
public class Main {
public static void main(String[] args){
Rectangle rectangle = new Rectangle();
Triangle triangle = new Triangle();
Circle circle = new Circle();
rectangle.printArea();
triangle.printArea();
circle.printArea();
}
}

Output:
Area of rectangle : 12
Area of triangle : 6
Area of circle : 50.26548245743669

RESULT:
Thus the application for area of rectangle , triangle and circle using
interface
Ex.no :

Date :

CREATING OWN EXCEPTIONS

AIM:

To write a java program to implement user defined exception handling.

ALGORITHM:

1. Import the java packages.

2. Create a subclass of Exception named as MyException it has only a


constructor plus an overloaded toString ( ) method that displays the value of the
exception.

3. The exception is thrown when compute ( ) integer parameter is greater than


10.

4. The main ( ) method sets up an exception handler for MyException, then calls
compute ( ) with a legal value (less than 10) and an illegal one to show both
paths through the code.

PROGRAM:

//File Name should be UserException.java

import java.io.*;

import java.util.*;

class MyException extends Exception

private int d;

MyException(int a)

d = a;

}
public String toString()

return "MyException [" + d + "]";

class UserException

static void compute(int a) throws MyException

System.out.println ("Called Compute(" + a + ")");

if(a>10)

throw new MyException(a);

System.out.println ("Normal Exit");

}public static void main(String args[])

try

compute(1);

compute(20);

catch(MyException e)

System.out.println("Caught " + e);

}
}

OUTPUT:

RESULT:

Thus the Implementation for user defined exception handling has been
successfully executed.
Ex.no:

Date:

MULTI THREADED APPLICATION

AIM:

To write a program that implements a multi-threaded application that has


three threads. First thread generates a random integer every 1 second and if the
value is even,second thread computes the square of the number and prints. If the
value is odd, the third thread will print the value of cube of the number.

ALGORITHM:

1.Import the java packages.

2.Create a thread that generates random number, Obtain one random number
and check is odd or even.

3.If number is even then create and start thread that computes square of a
number, Compute number * number and display the answer.

4.Notify to Random number thread and goto step 7.

5.If number is odd then create and start thread that computes cube of a number,
Compute number * number * number and display the answer.

6.Notify to Random number thread and goto step 7.

7.Wait for 1 Second and Continue to Step 3 until user wants to exits.

PROGRAM:

//File Name should be Multithread.java

import java.util.*;

class Even implements Runnable

public int x;

public Even(int x)
{

this.x = x;

public void run()

System.out.println("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()

System.out.println("New Thread "+ x +" is ODD and Cube of " + x + " is: " + x
* x * x);

class Generate extends Thread

public void run()

{
int num = 0;

Random r = new Random();

try

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

num = r.nextInt(100);

System.out.println("Main Thread Generates Random Integer: " + num);

if (num % 2 == 0)

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

t1.start();

else

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

t2.start();

Thread.sleep(1000);

System.out.println("--------------------------------------");

catch (Exception ex)

{
System.out.println(ex.getMessage());

}public class Multithread

public static void main(String[] args)

Generate g = new Generate();

g.start();

OUTPUT:
RESULT:

Thus the Implementation for application for multithreading has been


successfully executed.
Ex.no:

Date:

GETTING FILE INFORMATION

AIM:

To write a java program to implement file information such as 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:

1. Import the java packages.

2. By using Scanner class get the input during runtime.

3. By using File class method create a File object associated with the file or
directory specified by pathname. The pathname can contain path information as
well as a file or directory name.

4. The exists() checks whether the file denoted by the pathname exists. Returns
true if and only if the file denoted by the pathname exists; false otherwise

5. The getAbsolutePath() returns the absolute pathname string of the pathname.

6. The canRead() checks whether the application can read the file denoted by
the pathname. Returns true if and only if the file specified by the pathname
exists and can be read by the application; false otherwise.

7. The canWrite() checks whether the application can modify to the file denoted
by the pathname. Returns true if and only if the file system actually contains a
file denoted by the pathname and the application is allowed to write to the file;
false otherwise.

8. The length() returns the length of the file denoted by the pathname. The
return value is unspecified if the pathname denotes a directory.

9. The endsWith() returns true if the given string ends with the string given as
argument for the method else it returns false.
10. The program uses conditional operator to check different functionalities of
the given file.

PROGRAM:

//File Name should be FileInfo.java

import java.io.*;

import java. util.*;

public class FileInfo

public static void main(String[] args) throws IOException

Scanner in=new Scanner(System.in);

System.out.print("\nEnter the FileName: ");

String fName = in.next();File f = new File(fName);

String result = f.exists() ? " exists." : " does not exist.";

System.out.println("\nThe given file " +fName + result);

System.out.println("\nFile Location: "+f.getAbsolutePath());

if(f.exists())

result = f.canRead() ? "readable." : "not readable.";

System.out.println("\nThe file is " + result);

result = f.canWrite() ? "writable." : "not writable.";

System.out.println("\nThe file is " + result);

System.out.println("\nFile length is " + f.length() + " in bytes.");

if (fName.endsWith(".jpg") || fName.endsWith(".gif") ||
fName.endsWith(".png"))
{

System.out.println("\nThe given file is an image file.");

else if (fName.endsWith(".pdf"))

System.out.println("\nThe given file is an portable document format.");

else if (fName.endsWith(".txt"))

System.out.println("\nThe given file is a text file.");

else

System.out.println("The file type is unknown.");

}
OUTPUT :
RESULT:

Thus the Implementation for getting file information has been successfully
executed.
Ex.no:

Date :

GENERIC PROGRAMMING

AIM:

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

ALGORITHM:

1.Import the java packages.

2.Comparable interface is used to order the objects of user-defined class.

3.This interface is found in java.lang package and contains only one method
named compareTo(Object).

4.The compareTo() method works by returning an int value that is either


positive,negative, or zero.

5.Create a generic method max(), that can accept any type of argument.

6.Then sets the first element as the max element, and then compares all other
elements with the max element using compareTo() method

7.Finally the function returns an element which has the maximum value.

8.We can call generic method by passing with different types of arguments, the
compiler handles each method.

PROGRAM:

//File Name should be MyGeneric.java

import java.util.*;

class MyGeneric {

public static <T extends Comparable<T>> T max(T... elements)

T max = elements[0];
for (T element : elements) {

if (element.compareTo(max) > 0)

max = element;

return max;

public static void main(String[] args)

System.out.println("Integer Max: " + max(Integer.valueOf(32),


Integer.valueOf(89)));

System.out.println("String Max: " + max("GaneshBabu", "Ganesh"));

System.out.println("Double Max: " + max(Double.valueOf(5.6),


Double.valueOf(2.9)));System.out.println("Boolean Max: " +
max(Boolean.TRUE, Boolean.FALSE));

System.out.println("Byte Max: " + max(Byte.MIN_VALUE,


Byte.MAX_VALUE));

}
OUTPUT:

RESULT:

Thus the Implementation for finding the maximum value from the given type of
elements using a generic function has been successfully executed.
Ex.no:

Date:

EVENT - DRIVEN PROGRAMMING

AIM:

To write a java program to design a calculator using event-driven programming


paradigm of Java with the following options.

a) Decimal manipulations

b) Scientific manipulations

ALGORITHM:

1. Import the java packages.

2. Create the class calculator by implementing the class Jframe and interface

actionListener.

3. Declare the buttons required using JButton.

4. Design the layout of the calculator using the setLayout,textpanel(),

Panel(),Jtextfield(),setfont() methods.

5. Define the actions to be performed for each key using ActionListener.

6. Enable the scientific or standard calculator using the method method add().

7. Define the mathematical operations to be performed for the mathematical


symbols.

8. Select the required mathematical operations using switch as the calculator.

9. Pass the parameters for the methods used.

10. Make the frame visible by using the method setVisible().

PROGRAM:

//File Name should be ScientificCalculator.java

import java.awt.*;
import javax.swing.*;

import java.awt.event.*;

import javax.swing.event.*;

public class ScientificCalculator extends JFrame implements ActionListener

JTextField tfield;

double temp, temp1, result, a;

static double m1, m2;

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

char ch;

JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, zero, clr, pow2, exp, plus, min, div,
log, rec,

mul, eq, dot, sqrt, sin, cos, tan;

Container cont;

JPanel textPanel, buttonpanel;ScientificCalculator()

cont = getContentPane();

cont.setLayout(new BorderLayout());

JPanel textpanel = new JPanel();

tfield = new JTextField(25);

tfield.setHorizontalAlignment(SwingConstants.RIGHT);

tfield.addKeyListener(new KeyAdapter() {

public void keyTyped(KeyEvent keyevent) {

char c = keyevent.getKeyChar();

if (c >= '0'&& c <= '9') {


} else {

keyevent.consume();

});

textpanel.add(tfield);

buttonpanel = new JPanel();

buttonpanel.setLayout(new GridLayout(8, 4, 2, 2));

boolean t = true;

b1 = new JButton("1");

buttonpanel.add(b1);

b1.addActionListener(this);

b2 = new JButton("2");

buttonpanel.add(b2);

b2.addActionListener(this);

b3 = new JButton("3");

buttonpanel.add(b3);

b3.addActionListener(this);

b4 = new JButton("4");

buttonpanel.add(b4);

b4.addActionListener(this);

b5 = new JButton("5");

buttonpanel.add(b5);

b5.addActionListener(this);
b6 = new JButton("6");

buttonpanel.add(b6);

b6.addActionListener(this);b7 = new JButton("7");

buttonpanel.add(b7);

b7.addActionListener(this);

b8 = new JButton("8");

buttonpanel.add(b8);

b8.addActionListener(this);

b9 = new JButton("9");

buttonpanel.add(b9);

b9.addActionListener(this);

zero = new JButton("0");

buttonpanel.add(zero);

zero.addActionListener(this);

plus = new JButton("+");

buttonpanel.add(plus);

plus.addActionListener(this);

min = new JButton("-");

buttonpanel.add(min);

min.addActionListener(this);

mul = new JButton("*");

buttonpanel.add(mul);

mul.addActionListener(this);

div = new JButton("/");


div.addActionListener(this);

buttonpanel.add(div);

dot = new JButton(".");

buttonpanel.add(dot);

dot.addActionListener(this);

eq = new JButton("=");

buttonpanel.add(eq);

eq.addActionListener(this);

rec = new JButton("1/x");

buttonpanel.add(rec);

rec.addActionListener(this);sqrt = new JButton("Sqrt");

buttonpanel.add(sqrt);

sqrt.addActionListener(this);

log = new JButton("log");

buttonpanel.add(log);

log.addActionListener(this);

sin = new JButton("SIN");

buttonpanel.add(sin);

sin.addActionListener(this);

cos = new JButton("COS");

buttonpanel.add(cos);

cos.addActionListener(this);

tan = new JButton("TAN");

buttonpanel.add(tan);
tan.addActionListener(this);

pow2 = new JButton("x^2");

buttonpanel.add(pow2);

pow2.addActionListener(this);

exp = new JButton("Exp");

exp.addActionListener(this);

buttonpanel.add(exp);

clr = new JButton("AC");

buttonpanel.add(clr);

clr.addActionListener(this);

cont.add("Center", buttonpanel);

cont.add("North", textpanel);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public void actionPerformed(ActionEvent e) {

String s = e.getActionCommand();

if (s.equals("1")) {

if (z == 0) {

tfield.setText(tfield.getText() + "1");

} else {

tfield.setText("");tfield.setText(tfield.getText() + "1");

z = 0;

}
if (s.equals("2")) {

if (z == 0) {

tfield.setText(tfield.getText() + "2");

} else {

tfield.setText("");

tfield.setText(tfield.getText() + "2");

z = 0;

if (s.equals("3")) {

if (z == 0) {

tfield.setText(tfield.getText() + "3");

} else {

tfield.setText("");

tfield.setText(tfield.getText() + "3");

z = 0;

if (s.equals("4")) {

if (z == 0) {

tfield.setText(tfield.getText() + "4");

} else {

tfield.setText("");

tfield.setText(tfield.getText() + "4");
z = 0;

if (s.equals("5")) {

if (z == 0) {

tfield.setText(tfield.getText() + "5");

} else {

tfield.setText("");

tfield.setText(tfield.getText() + "5");

z = 0;

}if (s.equals("6")) {

if (z == 0) {

tfield.setText(tfield.getText() + "6");

} else {

tfield.setText("");

tfield.setText(tfield.getText() + "6");

z = 0;

if (s.equals("7")) {

if (z == 0) {

tfield.setText(tfield.getText() + "7");

} else {
tfield.setText("");

tfield.setText(tfield.getText() + "7");

z = 0;

if (s.equals("8")) {

if (z == 0) {

tfield.setText(tfield.getText() + "8");

} else {

tfield.setText("");

tfield.setText(tfield.getText() + "8");

z = 0;

if (s.equals("9")) {

if (z == 0) {

tfield.setText(tfield.getText() + "9");

} else {

tfield.setText("");

tfield.setText(tfield.getText() + "9");

z = 0;

if (s.equals("0")) {
if (z == 0) {

tfield.setText(tfield.getText() + "0");

} else {tfield.setText("");

tfield.setText(tfield.getText() + "0");

z = 0;

if (s.equals("AC")) {

tfield.setText("");

x = 0;

y = 0;

z = 0;

if (s.equals("log")) {

if (tfield.getText().equals("")) {

tfield.setText("");

} else {

a = Math.log(Double.parseDouble(tfield.getText()));

tfield.setText("");

tfield.setText(tfield.getText() + a);

if (s.equals("1/x")) {

if (tfield.getText().equals("")) {
tfield.setText("");

} else {

a = 1 / Double.parseDouble(tfield.getText());

tfield.setText("");

tfield.setText(tfield.getText() + a);

if (s.equals("Exp")) {

if (tfield.getText().equals("")) {

tfield.setText("");

} else {

a = Math.exp(Double.parseDouble(tfield.getText()));

tfield.setText("");

tfield.setText(tfield.getText() + a);

}if (s.equals("x^2")) {

if (tfield.getText().equals("")) {

tfield.setText("");

} else {

a = Math.pow(Double.parseDouble(tfield.getText()), 2);

tfield.setText("");

tfield.setText(tfield.getText() + a);

}
if (s.equals(".")) {

if (y == 0) {

tfield.setText(tfield.getText() + ".");

y = 1;

} else {

tfield.setText(tfield.getText());

if (s.equals("+")) {

if (tfield.getText().equals("")) {

tfield.setText("");

temp = 0;

ch = '+';

} else {

temp = Double.parseDouble(tfield.getText());

tfield.setText("");

ch = '+';

y = 0;

x = 0;

tfield.requestFocus();

if (s.equals("-")) {

if (tfield.getText().equals("")) {
tfield.setText("");

temp = 0;

ch = '-';

} else {

x = 0;

y = 0;

temp = Double.parseDouble(tfield.getText());

tfield.setText("");ch = '-';

tfield.requestFocus();

if (s.equals("/")) {

if (tfield.getText().equals("")) {

tfield.setText("");

temp = 1;

ch = '/';

} else {

x = 0;

y = 0;

temp = Double.parseDouble(tfield.getText());

ch = '/';

tfield.setText("");

tfield.requestFocus();
}

if (s.equals("*")) {

if (tfield.getText().equals("")) {

tfield.setText("");

temp = 1;

ch = '*';

} else {

x = 0;

y = 0;

temp = Double.parseDouble(tfield.getText());

ch = '*';

tfield.setText("");

tfield.requestFocus();

if (s.equals("Sqrt")) {

if (tfield.getText().equals("")) {

tfield.setText("");

} else {

a = Math.sqrt(Double.parseDouble(tfield.getText()));

tfield.setText("");

tfield.setText(tfield.getText() + a);

}if (s.equals("SIN")) {
if (tfield.getText().equals("")) {

tfield.setText("");

} else {

a = Math.sin(Double.parseDouble(tfield.getText()));

tfield.setText("");

tfield.setText(tfield.getText() + a);

if (s.equals("COS")) {

if (tfield.getText().equals("")) {

tfield.setText("");

} else {

a = Math.cos(Double.parseDouble(tfield.getText()));

tfield.setText("");

tfield.setText(tfield.getText() + a);

if (s.equals("TAN")) {

if (tfield.getText().equals("")) {

tfield.setText("");

} else {

a = Math.tan(Double.parseDouble(tfield.getText()));

tfield.setText("");

tfield.setText(tfield.getText() + a);
}

if (s.equals("=")) {

if (tfield.getText().equals("")) {

tfield.setText("");

} else {

temp1 = Double.parseDouble(tfield.getText());

switch (ch) {

case '+':

result = temp + temp1;

break;

case '-':

result = temp - temp1;

break;

case '/':

result = temp / temp1;break;

case '*':

result = temp * temp1;

break;

tfield.setText("");

tfield.setText(tfield.getText() + result);

z = 1;

}
}

tfield.requestFocus();

public static void main(String args[]) {

try

UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLook
AndFeel");

catch (Exception e)

ScientificCalculator f = new ScientificCalculator();

f.setTitle("ScientificCalculator");

f.pack();

f.setVisible(true);

}
OUTPUT:

RESULT:

Thus the Implementation for designing the scientific calculator has been
successfully executed.
Ex.no:

Date:

MINI PROJECT - OPAC SYSTEM

AIM:

To develop a mini project OPAC system for library using Java concepts.

ALGORITHM:

1. Import the awt,swing packages.

2. Extend the JFrame which implements actionlistener to the class datas.

3. Create the textfield for id, name and button for next, address and the panel.

4. Create object for the getcontentpane().

5. Assign the length and breadth value for the layout using gridlayout.

6. Add the new labels for ISBN and book name.

7. Add the new button for the nextbook

8. Create the bookname under the driver jdbc odbc driver in the try block.

9. Create the object for exception as e and use it for catching the error.

10. Show all the records using showrecord.

PROGRAM:

//File Name should be Data.java

import java.sql.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Data extends JFrame implements ActionListener


{

JTextField id;

JTextField name;

JButton next;

JButton addnew;

JPanel p;

static ResultSet res;

static Connection conn;

static Statement stat;

public Data()

super("My Application");

Container c = getContentPane();

c.setLayout(new GridLayout(5,1));

id = new JTextField(20);

name = new JTextField(20);

next = new JButton("Next BOOK");

p = new JPanel();

c.add(new JLabel("ISBN Number",JLabel.CENTER));

c.add(id);

c.add(new JLabel("Book Name",JLabel.CENTER));

c.add(name);

c.add(p);

p.add(next);
next.addActionListener(this);

pack();

setVisible(true);

addWindowListener(new WIN());

public static void main(String args[])

Data d = new Data();

try

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

conn = DriverManager.getConnection("jdbc:odbc:stu");

// cust is the DSN Name

stat = conn.createStatement();

res = stat.executeQuery("Select * from stu"); // stu is the table name

res.next();

catch(Exception e)

System.out.println("Error" +e);

d.showRecord(res);

public void actionPerformed(ActionEvent e)


{

if(e.getSource() == next)

try

res.next();

catch(Exception e)

showRecord(res);

public void showRecord(ResultSet res)

try

id.setText(res.getString(2));

name.setText(res.getString(3));

catch(Exception e)

}//end of the main


//Inner class WIN implemented

class WIN extends WindowAdapter

public void windowClosing(WindowEvent w)

JOptionPane jop = new JOptionPane();

jop.showMessageDialog(null,"Thank you","My

Application",JOptionPane.QUESTION_MESSAGE);

}
OUTPUT:
RESULT:

Thus the program to develop the simple OPAC for the libraries is executed
successfully.

You might also like