0% found this document useful (0 votes)
22 views63 pages

CS3381-OOPs Laboratory II CSE

Uploaded by

m.dnithi1728
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)
22 views63 pages

CS3381-OOPs Laboratory II CSE

Uploaded by

m.dnithi1728
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/ 63

Ex.

No: 1 A PROGRAM FOR SEQUENTIAL SEARCH


Date:

AIM

To implement sequential search using array.

ALGORITHM

1. Set starting position of first element(i=0)

2.If I is greater than the number of elements,go to step7

3.if arr[i]=key,then go to step6

4. update i to i+1

5.Return to step 2

6.Element key has been found at i:Exit

7.Element Not in list

8.Exit Rountine.

1
PROGRAM
public class LinSearch{
public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){

if(arr[i] == key){
return i;
} }
return -1;
}
public static void main(String a[]){

int[] a1= {10,20,30,50,70,90};


int key = 50;
System.out.println(key+" is found at index: "+linearSearch(a1, key));
}
}

2
OUTPUT
50 is found at the index:3

RESULT
Thus the java program for linear search is executed and the output is verified
successfully.

3
Ex.No: 1 B PROGRAM FOR BINARY SEARCH
Date:

AIM:
To implement binary search using array.

ALGORITHM

1.Identify the middle element of the sorted array.


2. Compare the target element with the middle element.
3.If the target matches with the middle element,the middle index is returned.
4.If the middle element is greater than the target search the lower sub array.

5.If the middle is less than the target search the upper sub array.
6.Identify the middle element of the sub array.
7.Repeat the steps 3 through 6 until the target is found.

4
PROGRAM
class BinSearch{
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 last=arr.length-1;
binarySearch(arr,0,last,key);
}
}

5
OUTPUT:
Element is found at the index:3

RESULT
Thus the java program for binary search is executed and the output is verified
successfully.

6
Ex.N0: 1 C
PROGRAM FOR QUADRATIC ALGORITHM
Date:

AIM:
To implement quadratic algorithm for insertion search in array.

ALGORITHM:
1. If the element is the first one, it is already sorted.

2 . Move to next element

3 . Compare the current element with all elements in the sorted array

4 . If the element in the sorted array is smaller than the current element, iterate to the
next element. Otherwise, shift all the greater element in the array by one position
towards the right

5 . Insert the value at the correct position

6 . Repeat until the complete list is sorted

7
PROGRAM
public class InsSort{
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--;

}
array[i+1] = key;
}
}
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:arr1){
System.out.print(i+" ");
}
System.out.println();
insertionSort(arr1);

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


for(int i:arr1){
System.out.print(i+" ");
} } }

8
OUTPUT
Before Insertion Sort
9 14 3 2 43 11 58 22
After Insertion Sort

2 3 9 11 14 22 43 58
Beforbbb Before Insertion Sort
AaA9 14 3 2 43 11 58 22
After Insertion Sort
2 3 9 11 14 22 43 58
Insertion Sort
9 14 3 2 43 11 58 22
After Insertion Sort
2 3 9 11 14 Before Insertion Sort
9 14 3 2 43 11 58 22
After Insertion Sort
2 3 9 11 14 22 43 58
22 43 58

RESULT
Thus the java program for insertion sort is executed and the output is verified
successfully.

9
Ex.No: 1 D PROGRAM FOR QUADRATIC ALGORITHM
Date:

AIM:
To implement quadratic algorithm for selection search in array.

ALGORITHM:
1. Get a list of unsorted numbers

2.Set a marker for the unsorted section at the front of the list.
3.Repeat steps 4-6 until one number remains in the unsorted section.
4.Compare all unsorted numbers in order to select the smallest one.
5.Swap this number with the first number in the unsorted section.
6.Advance the marker to the right one position
7.Stop

10
PROGRAM:
import java.util.Scanner;
public class SelSort {
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("Sorting 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("Now the Array after Sorting is :\n");


for(i=0; i<size; i++) {
System.out.print(arr[i]+ " ");
} } }

11
OUTPUT:
Enter the array size: 6
Enter the array element:
23 11 56 78 34 43

Sorting Array using Selection Sort Technique


Now the Array after Sorting is
11 23 34 43 56 78

RESULT
Thus the java program for selection sort is executed and the output is verified
successfully.

12
Ex.No: 2 A PROGRAM TO IMPLEMENT STACK
Date:

AIM
To develop a java program to implement stack operation using array.

ALGORITHM:

1. Start
2. Define a array stack of size max = 5
3. Initialize top = -1
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
If top < max -1
Increment top
Store element at current position of top
Else
Print Stack overflow
Else If choice = 2 then
If top < 0 then
Print Stack underflow
Else
Display current top element
Decrement top
Else If choice = 3 then
Display stack elements starting from top
7. Stop

13
PROGRAM
import java.util.Stack;

public class Main {


public static void main(String a[]){
//declare a stack object
Stack<Integer> stack = new Stack<>();
//print initial stack
System.out.println("Initial stack : " + stack);
//isEmpty ()
System.out.println("Is stack Empty? : " + stack.isEmpty());
//push () operation
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
//print non-empty stack
System.out.println("Stack after push operation: " + stack);
//pop () operation
System.out.println("Element popped out:" + stack.pop());
System.out.println("Stack after Pop Operation : " + stack);
//search () operation
System.out.println("Element 10 found at position: " + stack.search(10));
System.out.println("Is Stack empty? : " + stack.isEmpty());
}
}

14
OUTPUT:
Initial stack : []
Is stack Empty? : true
Stack after push operation: [10, 20, 30, 40]
Element popped out:40
Stack after Pop Operation : [10, 20, 30]
Element 10 found at position: 3
Is Stack empty? : false

RESULT
Thus the java program for stack is executed and the output is verified successfully.

15
Ex.No: 2B PROGRAM TO IMPLEMENT QUEUE
Date:

AIM
To develop a java program to implement queue operation using array.

ALGORITHM:

1. Start
2. Define a array queue of size max = 5
3. Initialize front = rear = –1
4. Display a menu listing queue operations
5. Accept choice
6. If choice = 1 then
If rear < max -1
Increment rear
Store element at current position of rear
Else
Print Queue Full
Else If choice = 2 then
If front = –1 then
Print Queue empty
Else
Display current front element
Increment front
Else If choice = 3 then
Display queue elements starting from front to rear.
7. Stop

16
PROGRAM
public class Queue {
int SIZE = 5;

int items[] = new int[SIZE];


int front, rear;
Queue() {
front = -1;
rear = -1;
}

boolean isFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
return false;
}

boolean isEmpty() {
if (front == -1)
return true;
else
return false;
}

void enQueue(int element) {


if (isFull()) {
System.out.println("Queue is full");
}

17
else {
if (front == -1) {
front = 0;
}

rear++;
items[rear] = element;
System.out.println("Insert " + element);
}
}
int deQueue() {

int element;
if (isEmpty()) {
System.out.println("Queue is empty");
return (-1);
}
else {

element = items[front];
if (front >= rear) {
front = -1;
rear = -1;
}
else {

front++;
}
System.out.println( element + " Deleted");
return (element);

18
}
}
void display() {
int i;

if (isEmpty()) {
System.out.println("Empty Queue");
}
else {
System.out.println("\nFront index-> " + front);
System.out.println("Items -> ");

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


System.out.print(items[i] + " ");
System.out.println("\nRear index-> " + rear);
}
}
public static void main(String[] args) {

Queue q = new Queue();


q.deQueue();
for(int i = 1; i < 6; i ++) {
q.enQueue(i);
}
q.enQueue(6);

q.display();
q.deQueue();
q.display();
}}

19
OUTPUT:
Initial Queue:
Queue is Empy
Queue after Enqueue Operation

10,30,50,70
Front element of the Queue:10
Queue element is full
10,30,50,70
Queue after two dequeue operations: 50, 70
Front element of the queue is :50

RESULT:

Thus the java program for queue is executed and the output is verified successfully.

20
Ex.No: 3 PROGRAM TO GENERATE PAYSLIP USING INHERITANCE
Date:

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

PROCEDURE

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.

21
PROGRAM
import java.util.*;
class employee
{

int empid;
long mobile;
String name, address, mailid;
Scanner get = new Scanner(System.in);
void getdata()
{

System.out.println("Enter Name of the Employee");


name = get.nextLine();
System.out.println("Enter Mail id");
mailid = get.nextLine();
System.out.println("Enter Address of the Employee:");
address = get.nextLine();

System.out.println("Enter employee id ");


empid = get.nextInt();
System.out.println("Enter Mobile Number");
mobile = get.nextLong();
}
void display()

{
System.out.println("Employee Name: "+name);
System.out.println("Employee id : "+empid);
System.out.println("Mail id : "+mailid);

22
System.out.println("Address: "+address);
System.out.println("Mobile Number: "+mobile);
}}
class programmer extends employee

{
double salary,bp,da,hra,pf,club,net,gross;
void getprogrammer(){
System.out.println("Enter basic pay");
bp = get.nextDouble();
}

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);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR PROGRAMMER");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);

System.out.println("DA:Rs"+da);
System.out.println("PF:Rs"+pf);
System.out.println("HRA:Rs"+hra);
System.out.println("CLUB:Rs"+club);

23
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}}
class asstprofessor extends employee

{
double salary,bp,da,hra,pf,club,net,gross;
void getasst()
{
System.out.println("Enter basic pay");
bp = get.nextDouble();

}
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);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR ASSISTANT PROFESSOR");
System.out.println("************************************************");

System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);

24
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}}

class associateprofessor extends employee


{
double salary,bp,da,hra,pf,club,net,gross;
void getassociate()
{
System.out.println("Enter basic pay");

bp = get.nextDouble();
}
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);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR ASSOCIATE PROFESSOR");
System.out.println("************************************************");

System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);

25
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}}

class professor extends employee


{
double salary,bp,da,hra,pf,club,net,gross;
void getprofessor()
{
System.out.println("Enter basic pay");

bp = get.nextDouble();
}
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);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR PROFESSOR");

System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);

26
System.out.println("PF:Rs"+pf);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);

}}
class salary
{
public static void main(String args[])
{
int choice,cont;

do{
System.out.println("PAYROLL");
System.out.println(" 1.PROGRAMMER \t 2.ASSISTANT PROFESSOR \t
3.ASSOCIATE

PROFESSOR \t 4.PROFESSOR ");


Scanner c = new Scanner(System.in);
choice=c.nextInt();
switch(choice){
case 1:
{

programmer p=new programmer();


p.getdata();
p.getprogrammer();
p.display();
p.calculateprog();
break; }

27
case 2:
{
asstprofessor asst=new asstprofessor();
asst.getdata();

asst.getasst();
asst.display();
asst.calculateasst();
break;}
case 3:{
associateprofessor asso=new associateprofessor();

asso.getdata();
asso.getassociate();
asso.display();
asso.calculateassociate();
break;}
case 4:{

professor prof=new professor();


prof.getdata();
prof.getprofessor();
prof.display();
prof.calculateprofessor();
break;

}}
System.out.println("Do u want to continue 0 to quit and 1 to continue ");
cont=c.nextInt();
}while(cont==1);}}

28
OUTPUT

RESULT
Thus the java application to generate pay slip for different category of employees was
implemented using inheritance and the program was executed successfully.

29
Ex.No: 4 PROGRAM TO CALCULATE AREA USING ABSTRACT
CLASS
Date:

AIM

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

PROCEDURE

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.

3.Each of the inherited class from shape class should provide the implementation for the
method printarea().

4.Get 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.

30
PROGRAM
import java.util.*;
abstract class shape
{

int a,b;
abstract public void printarea();
}
class rectangle extends shape
{
public int area_rect;

public void printarea()


{
Scanner s=new Scanner(System.in);
System.out.println("enter the length and breadth of rectangle");
a=s.nextInt();
b=s.nextInt();

area_rect=a*b;
System.out.println("Length of rectangle "+a +"breadth of rectangle "+b);
System.out.println("The area ofrectangle is:"+area_rect);
}}
class triangle extends shape
{

double area_tri;
public void printarea()
{
Scanner s=new Scanner(System.in);

31
System.out.println("enter the base and height of triangle");
a=s.nextInt();
b=s.nextInt();
System.out.println("Base of triangle "+a +"height of triangle "+b);

area_tri=(0.5*a*b);
System.out.println("The area of triangle is:"+area_tri);
}}
class circle extends shape{
double area_circle;
public void printarea(){

Scanner s=new Scanner(System.in);


System.out.println("enter the radius of circle");
a=s.nextInt();
area_circle=(3.14*a*a);
System.out.println("Radius of circle"+a);
System.out.println("The area of circle is:"+area_circle);

}}
public class shapeclass{
public static void main(String[] args) {
rectangle r=new rectangle();
r.printarea();
triangle t=new triangle();

t.printarea();
circle r1=new circle();
r1.printarea();
}}

32
OUTPUT

RESULT

Thus a java program for calculate the area of rectangle,circle and triangle was
implemented and executed successfully.

33
Ex.No: 5 PROGRAM TO PERFORM AREA USING INTERFACE
Date:

AIM
To write a java program to calculate the area using interface.

PROCEDURE

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.

3.Each of the inherited class from shape class should provide the implementation for the
method printarea().

4.Get 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.

34
PROGRAM
interface shape
{
void print Area();
}
class Rectangle implement sshape
{
int x,y;
public void print Area()
{
System.out.println("Area of Rectangleis"+x *y);
}}
class Triangle implements shape
{
int x,y;
public void print Area()
{
System.out.println("Area of Triangle is"+(x * y) /2);
}
}
class Circle implements shape
{
int x;
public void print Area()
{
System.out.println("Area of Circle is"+(22* x*x)/7);
}}
public class Main
{
public static void main(String[]args)
{
Rectangle r=newRectangle();
r.x=10;
r.y=20;
r.printArea();
System.out.println(" ------------------------- ");
Triangle t= newTriangle();

35
t.x=30;
t.y =35;
t.printArea();
System.out.println(" ------------------------- ");
Circle c=newCircle();
c.x=2;
c.printArea();
System.out.println(" --------------------------- ");
}}

36
OUTPUT

Area of Rectangle is 200


-----------------
Area of Triangle is 525
------------------
Area of Circle is 12
------------------

RESULT
Thus a java program for calculate the area of rectangle,circle and triangle was
implemented and executed successfully.

37
Ex.No: 6
PROGRAM TO IMPLEMENT USER DEFINED
Date: EXCEPTION HANDLING

AIM

To write a java program to implement user defined exception handling

PROCEDURE

1.Create a class which extends Exception class.


2.Create a constructor which receives the string as argument.
3.Get the Amount as input from the user.
4.If the amount is negative , the exception will be generated.
5.Using the exception handling mechanism , the thrown exception is handled by the catch

construct.
6.After the exception is handled , the string “invalid amount “ will be displayed.
7.If the amount is greater than 0 , the message “Amount Deposited “ will be displayed

38
(a)PROGRAM
import java.util.Scanner;
class NegativeAmtException extends Exception
{

String msg;
NegativeAmtException(String msg){
this.msg=msg;
}
public String toString() {
return msg;

}}
public class userdefined {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.print("Enter Amount:");
int a=s.nextInt();

try{
if(a<0){
throw new NegativeAmtException("Invalid Amount");
}
System.out.println("Amount Deposited");
}

catch(NegativeAmtException e)
{
System.out.println(e);
}}}

39
(b) PROGRAM
class MyException extends Exception{
String str1;

MyException(String str2)
{
str1=str2;
}
public String toString() {
return ("MyException Occurred: "+str1) ;

}}
class example{
public static void main(String args[]){
try{
System.out.println("Starting of try block");
throw new MyException("This is My error Message"); }

catch(MyException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
}}}

40
OUTPUT

RESULT

Thus a java program to implement user defined exception handling has been implemented
and executed successfully.

41
Ex.No: 7
PROGRAM TO IMPLEMENT MULTITHREADED
Date: APPLICATION

AIM

To write a java program that implements a multi-threaded application .

PROCEDURE

1.Create a class even which implements first thread that computes .the square of the
number .

2. run() method implements the code to be executed when thread gets executed.

3.Create a class odd which implements second thread that computes the cube of the
number.

4.Create a third thread that generates random number.If the random number is even , it
displays
the square of the number.If the random number generated is odd , it displays the cube of
the
given number .

5.The Multithreading is performed and the task switched between multiple threads.

6.The sleep () method makes the thread to suspend for the specified time.

42
PROGRAM
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 A extends Thread{

public void run(){


int num = 0;
Random r = new Random();
try

43
{
for (int i = 0; i < 5; i++)
{
num = r.nextInt(100);

System.out.println("Main Thread and Generated Number is " + 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 multithreadprog{

public static void main(String[] args){


A a = new A();
a.start();
}}

44
OUTPUT

RESULT

Thus a java program for multi-threaded application has been implemented and executed
successfully.

45
Ex.No: 8

Date: PROGRAM FOR DISPLAYING FILE INFORMATION

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.

PROCEDURE

1.Create a class filedemo. Get the file name from the user .
2.Use the file functions and display the information about the file.
3.getName() displays the name of the file.
4.getPath() diplays the path name of the file.
5.getParent () -This method returns the pathname string of this abstract pathname’s parent,
or
null if this pathname does not name a parent directory.
6.exists() – 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.
12.length()- displays the size of the file.
13. delete() – deletes the file
14.Invoke the predefined functions abd display the iformation about the file.

46
PROGRAM
import java.io.*;
import java.util.*;
class filedemo{

public static void main(String args[]){


String filename;
Scanner s=new Scanner(System.in);
System.out.println("Enter the file name ");
filename=s.nextLine();
File f1=new File(filename);

System.out.println("*****************");
System.out.println("FILE INFORMATION");
System.out.println("*****************");
System.out.println("NAME OF THE FILE "+f1.getName());
System.out.println("PATH OF THE FILE "+f1.getPath());
System.out.println("PARENT"+f1.getParent());

if(f1.exists())
System.out.println("THE FILE EXISTS ");
else
System.out.println("THE FILE DOES NOT ExISTS ");
if(f1.canRead())
System.out.println("THE FILE CAN BE READ ");

else
System.out.println("THE FILE CANNOT BE READ ");
if(f1.canWrite())
System.out.println("WRITE OPERATION IS PERMITTED");

47
else
System.out.println("WRITE OPERATION IS NOT PERMITTED");
if(f1.isDirectory())
System.out.println("IT IS A DIRECTORY ");

else
System.out.println("NOT A DIRECTORY");
if(f1.isFile())
System.out.println("IT IS A FILE ");
else
System.out.println("NOT A FILE");

System.out.println("File last modified "+ f1.lastModified());


System.out.println("LENGTH OF THE FILE "+f1.length());
System.out.println("FILE DELETED "+f1.delete());
}}

48
OUTPUT

RESULT

Thus a java program to display file information has been implemented and executed
successfully.

49
Ex.No: 9 PROGRAM TO FIND THE MAXIMUM VALUE FROM THE GIVEN

Date: TYPE OF ELEMENTS USING GENERICS

AIM

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

PROCEDURE

1.Create a class Myclass to implement generic class and generic methods.


2.Get the set of the values belonging to specific data type.
3.Create the objects of the class to hold integer,character and double values.
4.Create the method to compare the values and find the maximum value stored in the
array.
5.Invoke the method with integer, character or double values . The output will be displayed
based on the data type passed to the method.

50
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 < vals.length; i++)
if(vals[i].compareTo(v) < 0)
v = vals[i];

return v;}
public T max() {
T v = vals[0];
for(int i=1; i < vals.length;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);

51
MyClass<Double>dob = new MyClass<Double>(d);
System.out.println("Max value in inums: " + iob.max());
System.out.println("Min value in inums: " + iob.min());
System.out.println("Max value in chs: " + cob.max());

System.out.println("Min value in chs: " + cob.min());


System.out.println("Max value in chs: " + dob.max());
System.out.println("Min value in chs: " + dob.min());
}}

52
OUTPUT

RESULT
Thus a java program to find the maximum value from the given type of elements has been
implemented using generics and executed successfully.

53
Ex.No: 10 PROGRAM TO DESIGN A CALCULATOR USING EVENT DRIVEN

Date: PROGRAMMING PARADIGM OF JAVA

AIM

To design a calculator using event driven programming paradigm of Java with the
following options

a) Decimal Manipulations
b) Scientific Manipulations

PROCEDURE

1. Import the swing packages and awt packages.


2. Create the class scientific calculator that implements action listener.
3. Create the container and add controls for digits , scientific calculations and decimal
Manipulations.
4. The different layouts can be used to lay the controls.
5.When the user presses the control , the event is generated and handled .
6. The corresponding decimal , numeric and scientific calculations are performed.

54
PROGRAM
importjavafx.application.Application;
importjavafx.geometry.Insets;
importjavafx.geometry.Pos;
import javafx.scene.Scene;
importjavafx.scene.control.*;
importjavafx.scene.layout.BorderPane;

importjavafx.scene.layout.*;
importjavafx.scene.paint.Color;
import javafx.scene.text.Text;
importjavafx.stage.Stage;
public class JavaFXApplication1extendsApplication{
public void start(StageprimaryStage){

//CreatethetopsectionoftheUI
Text tNumber1 = new Text("Number 1:");
Text tNumber2 = new Text("Number 2:");
TexttResult=newText("Result:");
TextField tfNumber1 = new TextField();
TextField tfNumber2 = new TextField();

TextFieldtfResult = new TextField();


tfResult.setEditable(false);
Menu me=new Menu("Edit");
//createmenuitems
MenuItemm1=newMenuItem("Set DefaultValue");

55
MenuItemm2=newMenuItem("ClearAllvalues");
menume.getItems().add(m1);
menume.getItems().add(m2);
Menumc=newMenu("Bg_Color");

MenuItem c1 = new MenuItem("Red");


MenuItemc2=newMenuItem("Green");
mc.getItems().addAll(c1,c2);
MenuBarmb=newMenuBar();
mb.getMenus().add(mc);
m1.setOnAction(e>{tfNumber1.setText("10");tfNumber2.setText("20");});
m2.setOnAction(e>{tfNumber1.setText("");tfNumber2.setText("");tfResult.setText("");});
Button btSubtract = new Button("Subtract");
ButtonbtMultiply=newButton("Multiply");
Button btDivide=newButton("Divide");

HBoxcalcTop = new HBox(5);


calcTop.setAlignment(Pos.CENTER);
calcTop.setPadding(newInsets(5));
calcTop.getChildren().addAll(tNumber1,tfNumber1,tNumber2,tfNumber2,tResult,
tfResult);
HBoxcalcBottom = new HBox(5);calcBottom.setAlignment(Pos.CENTER);
calcBottom.setPadding(newInsets(5));
calcBottom.getChildren().addAll(btAdd,btSubtract,btMultiply,btDivide);
BorderPane pane = newBorderPane();
pane.setTop(vb);

pane.setCenter(calcTop);
pane.setBottom(calcBottom);

56
c1.setOnAction(e -> {
pane.setBackground(newBackground(newBackgroundFill(Color.RED,null,null)));});

c2.setOnAction(e -> {
pane.setBackground(newBackground(newBackgroundFill(Color.GREEN,null,null)));});
buttonsbtAdd.setOnAction(e ->{double a = getDoubleFromTextField(tfNumber1);
double b = getDoubleFromTextField(tfNumber2);tfResult.setText(String.valueOf(a+b));});

btSubtract.setOnAction(e->{double a = getDoubleFromTextField(tfNumber1);
double b = getDoubleFromTextField(tfNumber2);
tfResult.setText(String.valueOf(a-b));});
btMultiply.setOnAction(e ->{ double a = getDoubleFromTextField(tfNumber1);
doubleb=getDoubleFromTextField(tfNumber2);
tfResult.setText(String.valueOf(a*b));});

btDivide.setOnAction(e ->{double a = getDoubleFromTextField(tfNumber1);


double b = getDoubleFromTextField(tfNumber2);
tfResult.setText(b==0? "NaN":String.valueOf(a/b));});
Scene scene = new Scene(pane);
primaryStage.setTitle("SimpleCalculator");
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
}
Private static doublegetDoubleFromTextField(TextFieldt)
{returnDouble.parseDouble(t.getText());
}publicstaticvoidmain(String[]args){launch(args);

}}

57
OUTPUT:

58
RESULT:

Thus the java programs for scientific calculator has been implemented and executed
successfully.

59
Ex.No:11
CLIENT SERVER APPLICATION
Date:

AIM
To develop a java application to demonstrate Client Server chat.

PROCEDURE
Step 1: Start the program.
Step 2: Create a client window using swing components.
Step 3: Create a server window.
Step 4: Create a socket and establish the connection between client and server.
Step 5: Compile the client and server program.
Step 6: Execute the client program and server program.
Step 7: The message send by the client will be received by the server.

PROGRAM

Client1.java
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;
public class Client1 extends JFrame {
JTextField jtf; JButton jb1; Socket s; String temp=""; DataInputStream dis;
public Client1() {
try {
s=new Socket(InetAddress.getLocalHost(),1090);
dis=null;
}
catch(Exception e) {}
jtf=new JTextField(20);
jb1=new JButton("Click to send");
jb1.addActionListener(new B());
getContentPane().add("North", jtf);
getContentPane().add("South", jb1);
pack();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we){
System.exit(0);
}});
}
class B implements ActionListener {
public void actionPerformed(ActionEvent ae) {

60
String line="";
try {
dis=new DataInputStream(System.in);
String n=jtf.getText();
PrintStream ps=new PrintStream(s.getOutputStream(), true);
ps.println(n);
}
catch(Exception e){}
}}
public static void main(String ar[])throws Exception {
Client1 cl=new Client1();
cl.setSize(200,200);
cl.setLocation(200,200);
cl.setVisible(true);
cl.setTitle("Client");
}}

Server1.java
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
public class Server1 extends JFrame {
static JTextArea jta;
Socket client;
ServerSocket ss;
DataInputStream dis;
PrintWriter out;
public Server1() {
jta=new JTextArea(100,100);
getContentPane().add("Center", jta);
pack();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}});
}
void connection() {
try {
ss=new ServerSocket(1090);
System.out.println("Connection established");
while(true) {
ClientWorker w;
w = new ClientWorker(ss.accept(), jta);

61
Thread t = new Thread(w);
t.start();
}}
catch (Exception e) { }
}
public static void main(String sr[]) {
Server1 se=new Server1();
se.setSize(200,200);
se.setLocation(200,200);
se.setVisible(true);
se.setTitle("Server");
se.connection();
}}
class ClientWorker extends Server1 implements Runnable {
Socket client;
public ClientWorker(Socket client, JTextArea jta) {
this.client = client;
this.jta=jta;
}
public void run() {
try {
String line="";
DataInputStream dis=new DataInputStream(client.getInputStream());
while(true) {
line=dis.readLine();
jta.append(line+"\n");
}}
catch(Exception e){}
}}

62
OUTPUT

RESULT
Thus the Client server program was executed successfully.

63

You might also like