SlideShare a Scribd company logo
1 of 174
Download to read offline
1
DEPT OF COMPUTER SCIENCE AND ENGG
B.E[INFORMATION TECHNOLOGY]
V-SEMESTER
95808- OPERATING SYSTEM AND JAVA
PROGRAMMING LAB MANUAL
Lab Incharge
Dr. P. Aruna
Professor
Dept of CSE
2
Annamalai University
CYCLE-I
JAVA PROGRAMMING
Ex.no Name of the Exercises
1. Classes and Objects
2. Command Line Argument
3. Bitwise Operators
4. Method Overloading
5. Packages
6.
Interface
7. Inheritance
3
8. Exception Handling
9. User Defined Exception Handling
10. Multithreading:join() and isAlive()
11. Multithreading:Inter thread
communications
12. Addition of Two Numbers using Applet
4
CYCLE-II
UNIX PROGRAMMING
Ex.no Name of the Exercises
1. Job scheduling techniques
2.
Disk scheduling techniques
3.
Memory allocation techniques
4.
Memory management techniques
5.
Page replacement techniques
6. Producer consumer problem
7.
Bankers algorithm
8.
Dining Philosophers problem
5
Ex.No: 1
CLASSES AND OBJECTS
Aim:
To write a java program to work with the creation of objects for the class
with overloaded constructor and user defined methods returning a value.
Algorithm:
 Start
 Create an object called room.
 Create an object with overloaded constructor and get length and breadth.
 Create a function room where only length is passed and breadth remains
constant.
 Create a function getdata() to return the area.
 Create another class ex1 that includes the main function.
 Declare variable int l=0,b=0,float area.
 Get the dynamic input using exceptional try and catch.
 Pass the input values to the constructor.
 Calculate the input values to the getdata().
 Display the result.
Source code:
import java.io.*;
import java.io.DataInputStream;
class Room
{
float length,breadth;
Room(int a,int b)
{
length=a;
breadth =b;
}
Room(int a)
{
6
length =a;
breadth=100;
}
float getdata()
{
Return(length*breadth);
}
}
class ex1
{
public static void main(String args[])
{
float area;
int l=0,b=0;
DataInputStream in=new DataInputStream(System.in);
try
{
System.out.println(“n enter the value for Room length:”);
l=Integer.parseInt(in.readLine());
System.out.println(“n enter the value for Room breadth:”);
b=Integer.parseInt(in.readLine());
}
Catch(Exception e)
{}
Room room1=new Room(l,b);
area=room1.getdata();
System.out.println(“n length=”+room1.length);
System.out.println(“n breadth=”+room1.breadth);
System.out.println(“n Area=”+area);
7
System.out.println(“n passing only length of the room with breadth=100”);
Room room2=new Room(l);
area =room2,getdata();
System.out.println(“n length=”+room2.length);
System.out.println(“n breadth=”+room2.breadth);
System.out.println(“n Area=”+area);
}
}
Sample input and output:
Enter the value for Room length:100
Enter the value for Room breadth:200
Length =100.0
Breadth=200.0
Area=20000.0
Passing only length of the room with breadth=100
Length=100.0
Breadth=100.0
Area=10000.0
Result:
Thus the java program was executed successfully and the output was
verified.
8
ExNo: 2
COMMAND LINE ARGUMENT
Aim:
To write a java program to get and sort names by command line argument.
Algorithm:
 Create a class name ex2 and declare the variables int n and string s[]
 Allocate the memory of names for variable s.
 Get total number of names to be entered in the variable n.
 Using compareTo function sort the names in alphabetical order.
 Use forloop to sort the name.
 Print the sorted name list.
Source code:
import java.io.*;
import java.lang.*;
public static void main(String args[])throws IOException
{
String t;
int n=args.length;
int i,j;
System.out.println(“n you have entered”+n+”names to sort it in ascendingorder”);
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(args[i].compareTo(args[j])>0)
{
t=args[i];
args[i]=args[j];
args[j]=t;
9
}
}
}
System.out.println(“n sorted name list is…n);
for (i=0;i<n;i++)
{
System.out.println(args[i]);
}
}
}
Sample input and output:
E:>java ex2 one two three four five six seven eight nine ten eleven twelve
You have entered 12 names to sort it in ascending order
Sorted name list is…
Eight
Eleven
Five
Four
Nine
One
Seven
Six
Ten
Three
Twelve
two
Result:
Thus the java program was executed successfully and the output was
verified
10
ExNo: 3
BITWISE OPERATOR
Aim:
To write a java program to understand the concept of functionalities of different
Bitwise operators.
Algorithm:
 Create a class called ex3.
 Use DataInputStream to get stream of data.
 Display the menu and get choice from the user.
 Now,call the appropriate care.
 Display the output.
Source code:
import java.io.*;
public class ex3
{
public static void main(String args[])throws IOException
{
DataInputStream d=new DataInputStream(System.in);
System.out.println(“n enter value for x:”);
int x=Integer.parseInt(d.readLine());
System.out.println(“n enter value for y:”);
int y= Integer.parseInt(d.readLine());
int c;
do
{
System.out.println(“n BITWISE OPERATORn”);
System.out.println(“1.AND”);
System.out.println(“2.OR”);
System.out.println(“3.XOR”);
11
System.out.println(“ 4.LEFT SHIFT”);
System.out.println(“ 5.RIGHT SHIFT”);
System.out.println(“ 6.NOT”);
System.out.println(“ 7.EXITn”);
System.out.println(“ n enter your choice:”);
c=Integer.parseInt(d.readLine());
switch(c)
{
case 1:
System.out.println(“AND OPERATION:”+(x+y));
break;
case 2:
System.out.println(“OR OPERATION:”+(x|y));
break;
case 3:
System.out.println(“XOR OPERATION:”+(x^y));
break;
case 4:
System.out.println(“LEFT SHIFT:”+(x<<y));
break;
case 5:
System.out.println(“RIGHT SHIFT:”+(x>>y));
break;
case 6:
System.out.println(“NOT of x :”+(~x));
System.out.println(“NOT of y :”+(~y));
break;
case 7:
System.exit(1);
12
break;
default:
System.out.println(“n enter only 1 to 7”);
break;
}
}while(c!=7);
}
}
Sample input and output:
Enter value for x:10
Enter value for y:6
BITWISE OPERATOR
1.AND
2.OR
3.XOR
4.LEFT SHIFT
5.RIGHT SHIFT
6.NOT
7.EXIT
Enter your choice:1
AND OPERATION:2
BITWISE OPERATOR
1.AND
2.OR
3.XOR
4.LEFT SHIFT
5.RIGHT SHIFT
6.NOT
7.EXIT
13
Enter your choice:2
OR OPERATION:14
BITWISE OPERATOR
1.AND
2.OR
3.XOR
4.LEFT SHIFT
5.RIGHT SHIFT
6.NOT
7.EXIT
Enter your choice:3
XOR OPERATION:12
BITWISE OPERATOR
1.AND
2.OR
3.XOR
4.LEFT SHIFT
5.RIGHT SHIFT
6.NOT
7.EXIT
Enter your choice:4
LEFT SHIFT OPERATION:640
BITWISE OPERATOR
1.AND
2.OR
3.XOR
4.LEFT SHIFT
5.RIGHT SHIFT
6.NOT
14
7.EXIT
Enter your choice:5
RIGHT SHIFT OPERATION:0
BITWISE OPERATOR
1.AND
2.OR
3.XOR
4.LEFT SHIFT
5.RIGHT SHIFT
6.NOT
7.EXIT
Enter your choice:6
NOT of x :-11
NOT of y :-7
BITWISE OPERATOR
1.AND
2.OR
3.XOR
4.LEFT SHIFT
5.RIGHT SHIFT
6.NOT
7.EXIT
Enter your choice:7
Result:
Thus,the java program has been written to understand the concept of functionalities
of different bitwise operators and output were verified.
15
ExNo: 4
METHOD OVERRIDING
Aim:
To write a java program to understand the concept of Method Overriding.
Algorithm:
 Create a base class “vehicle” and declare the variable reg_no as string
and model as integer.
 Create a function read()inside the class to read data for the variables.
 Create a derived class”two-wheeler” and declare the variable
no_gear,power as integer.
 Create another deriver class”scooter” and declare variable
manufacturer,owner as string.
 Create a function read()to get the data for no_gear.
 Create another function print that prints the values of the
reg_no,model,power,no_gear
Source code:
import java.io.*;
class vehicle
{
String reg_no;
int model;
void read()throws IOException
{
DataInputStream d=new DataInputStream(System.in);
System.out.println(“n enter reg_no and model :”);
reg_no=d.readLine();
model=Integer.parseInt(d.readLine());
}
}
class two-wheeler extends vehicle
16
{
int no_gear,power;
void read()throws IOException
{
super.read();
DataInputStream d=new DataInputStream(System.in);
System.out.println(“n enter no_gear and power :”);
no_gear=Integer.parseInt(d.readLine());
power= Integer.parseInt(d.readLine());
}
}
class scooter extends two-wheeler
{
String manufacturer,owner;
void read()throws IOException
{
super.read();
DataInputStream d=new DataInputStream(System.in);
System.out.println(“n enter manufacturer and owner :”);
manufacturer=d.readLine();
owner= d.readLine();
}
void print()
{
System.out.println(“n”);
System.out.println(“n Reg_no :”+reg_no);
System.out.println(“n Model :”+model);
System.out.println(“n No_gear :”+no_gear);
System.out.println(“n Power :”+power);
17
System.out.println(“n Manufacturer :”+manufacturer);
System.out.println(“n Owner :”+owner);
}
}
class overriding
{
public static void main(String args[])throws IOException
{
scooter s=new scooter();
s.read();
s.print();
}
}
Sample input and output:
Enter reg_no and model:TN31AD1224 2010
Enter no_gear and power:5 798
Enter manufacturer and owner : Maruthi Sauresh.A
Reg_no : TN31AD1224
Model : 2010
No_gear : 5
Power : 798
Manufacturer : Maruthi
Owner : Sauresh.A
Result:
Thus, the java program has been written to understand the concept of Method
Overriding and output was verified.
18
ExNo: 5
PACKAGES
Aim:
To write a java program to understand the steps in the creation of packages.
Algorithm:
 Include the package complex.
 Create a class arith and declare rp,ip as integer.
 Define the function arith(),set rp and ip to 0
 Another function arith(int rp,int ip) set this.rp=rp and this.ip=ip.
 Create a function add() pass arguments with arith a1 and arith a2.
 Add a1.rp and a2.rp store in rp.
 Similarly add a1.ip and a2.ip and store in ip.
 Create a function sub(arith a1,arith a2)
 Subtract a1.rp and a2.rp store it in rp
 Subtract a1.ip and a2.ip store it in ip
Source code:
Package creation code:
package pkg;
public class arith
{
public int rp,ip;
public arith()
{
rp=0;
ip=0;
}
public arith(int rp,in rip)
{
this.rp=rp;
this.ip=ip;
19
}
public void add(arith a1,arith a2)
{
rp=a1.rp + a2.rp;
ip=a1.ip +a2.ip;
}
public void sub (arith a1,arith a2)
{
rp=a1.rp - a2.rp;
ip=a1.ip -a2.ip;
}
}
Main code:
import pkg.arith;
import java.io.*;
class package1
{
public static void main(String args[])throws IOException
{
int rp,ip;
DataInputStream d=new DataInputStream(System.in);
System.out.println(“n enter real part and imaginary part of 1st
complex no :”);
rp=Integer.parseInt(d.readLine());
ip= Integer.parseInt(d.readLine());
arith a1=new arith(rp,ip);
System.out.println(“n enter real part and imaginary part of 2nd complex no :”);
rp=Integer.parseInt(d.readLine());
ip= Integer.parseInt(d.readLine());
arith a2=new arith(rp,ip);
20
arith a3=new arith();
System.out.println(“n a1=”+a1.rp+ “+” +a1.ip+ “i”);
System.out.println(“n a2=”+a2.rp+ “+” +a2.ip+ “i”);
a3.add(a1,a2);
System.out.println(“n Added value:” +a3.rp+ “+” +a3.ip+ “i”);
a3.sub(a1,a2);
System.out.println(“n Subtacted value :” +a3.rp+ “-“ a3.ip + “i”);
}
}
Sample input and output:
Enter real part and imaginary part of 1st
complex no : 10 5
Enter real part and imaginary part of 2nd complex no : 3 6
a1= 10 + 5i
a2= 3 +6i
Added value : 13 +11i
Subtracted value : 7 – 1i
Result:
Thus, the java program has been written to create a package and output were
verified by importing it in another program
21
Ex.No : 6
INTERFACE
Aim:
To write java program to implement the concept of interface.
Algorithm:
 Create a class income,declare iamount as integer.
 Create a function get() to get the values for the variable.
 Create a class expenditure and declare the function get1().
 Create a derived class net_income that extends income and implements
expenditure.
 Declare variables eamount,namount as float.
 Create a function print() to print the values.
 Create a main class and create an object for net_income.
 Now,get the values using n.print().
 End.
Source code:
import java.io.*;
class income
{
float iamount;
void get()throws IOException
{
DataInputStream d=new DataInputStream(System.in);
System.out.println(“n enter the income :”);
iamount=Float.pareseFloat(d.readLine());
}
}
interface expenditure
{
22
public void get1();
}
class net_income extends income implements expenditure
{
float eamount,namount;
public void get1()
{
try
{
DataInputStream d=new DataInputStream(System.in);
System.out.println(“n enter expenditure:”);
eamount=Float.parseFloat(d.readLine());
}
Catch(IOException e)
{}
}
void print()
{
System.out.println(“n income :” +iamount);
System.out.println(“n expenditure :” +eamount);
System.out.println(“n net income :” +(iamount-eamount));
}
}
class interface6
{
public static void main(String args[])throws IOException
{
23
net_income n=new net_income();
n.get();
n.get1();
n.print();
}
}
Sample input and output:
Enter income : 1000
Enter expenditure : 200
Income : 1000.0
Expenditure : 200.0
Net income : 800.0
Result:
Thus, the java program was created and executed successfully and the output is
verified.
24
ExNo : 7
INHERITANCE
Aim:
To write a java program to handle the situation of exception multi inheritance.
Algorithm:
 Create a class student and declare variable rollno.
 Create function getnumber() and display().
 Create another class test which inherit student.
 Create function display().
 Create another interface sports with variable sport and function putsp().
 Create variable total and function putsp(),display().
 Create another class result which extends the test and sport.
 Create main class inhetitance7 and which has the student as object of class
result.
Source code:
import java.io.*;
class student
{
int roll_no;
void getnumber(int n)
{
roll_no=n;
}
void display()
25
{
System.out.println(“n Rollno:’ +roll_no);
}
}
class test extends student
{
int m1,m2;
void getmarks(int p,int q)
{
m1=p;
m2=q;
}
void display()
{
System.out.println(“n Rollno:’ +roll_no);
System.out.println(“n Marks Achieved”);
System.out.println(“n Mark1 :” +m1);
System.out.println(“n Mark2 :” +m2);
}
}
interface sports
{
float sport=6.0f;
26
void putsp();
}
class results extends test implements sports
{
float total;
public void putsp()
{
System.out.println(“n sports result =”+sport);
}
void display()
{
total=m1+m2+sport;
display();
putsp();
System.out.println(“n total score =” +total);
}
}
class inheritance7
{
public static void main(String args[])
{
result student1 = new results();
student1.getnumber(1256);
27
student1.getmarks(30,40);
student1.display();
}
}
Sample input and output:
Rollno :1256
Marks Achieved
Marks1 = 30
Marks2 =40
Sports result =6.0
Total score = 76.0
Result:
Thus, the java program was created and executed successfully and output is verified.
28
ExNo : 8
EXCEPTION HANDLING
Aim:
To write a java program to implement the concept of exception handling.
Algorithm:
 Create a class exception8
 Declare the integer a,b,c inside the class.
 Store length of the argument in a and get the variable for b.
 Calculate c=b/a.
 Print the value of a,b,c.
 Declare variable d[] = new int [a-2].
 End.
Source code:
import java.io.*;
class exception8
{
public static void main(String args[])throws IOException
{
DataInputStream din= new DataInputStream(System.in);
int a,b,c;
try
{
a=args.length;
System.out.println(“n enter b value :”);
b= Integer.pareseInt(din.readLine());
29
c=b/a;
System.out.println(“n a=”+a);
System.out.println(“n b=” +b);
System.out.println(“n b/a =” +c);
int d[] = new int[a-2];
d[42]=99;
}
catch(ArithmeticException e3)
{
System.out.println(e3);
}
catch(NegativeArraySizeException e2)
{
System.out.println(e2);
}
catch(ArrayIndexOutOfBoundsException e1)
{
System.out.println(e1);
}
catch(NumberFormatException e)
{
System.out.println(e);
}
30
Sample input and output:
C:>java exception8
Enter b value:
1
java.lang. ArithmeticException:/by zero
C:>java exception8 3
Enter b value: 4
a = 1
b = 4
b/a = 4
java.lang. NegativeArraySizeException
C:>java exception8 3 5
Enter b value: 5
a = 2
b = 5
b/a =2
java.lang. ArrayIndexOutOfBoundsException: 42
C:>java exception8 3 5
Enter b value: t
java.lang. NumberFormatException: for input string : “t”.
Result:
Thus, the java program was created and executed successfully and output is verified.
31
ExNo : 9
USER DEFINED EXCEPTION HANDLING
Aim:
To write a java program to implement the concept of user defined exception.
Algorithm:
 Create a class myexception that extends exception ,create variable and function
to read and return a message.
 Create another class exception , create variable eno ,ename ,job ,count ,as static
int and string.
 Create a function display() to display the employee details.
 The main function call the get() and display() function to red and print the
values.
Source code:
import java.io.*;
import java.lang.*;
class MyException extends Exception
{
String msg;
public MyException(String message)
{
msg = message;
}
public StringtoString()
{
return msg;
32
}
}
class exception9
{
static int eno[] = new int[];
static String ename[] = new String[3];
static String job[] = new String[3];
static int sal[] =new int[3];
static int count = 0;
static void get()throws IOException
{
int i;
DataInputStream d = new DataInputStream(System.in);
try
{
for(i=count;i<3;i++)
{
System.out.println(“n enter “ +(i+1)+” employee detail :”);
System.out.println(“n enter employee no and name :”);
eno[i] = Integer.parseInt(d.readLine());
if(eno[i]<=0)
throw new MyEception(“ enter valid number”);
ename[i] = d.readLine();
33
System.out.println(“n enter job and salary :”);
job[i] = d.readLine();
sal[i] = Integer.parseInt(d.readLine());
if(sal[i]<0)
throw new MyEception(“ enter valid salary”);
count++;
}
}
catch(MyException e)
{
System.out.println(“ Exception caught :” +e);
get();
}
}
static void disp()
{
for(int i=0;i<3;i++)
{
System.out.println(eno[i]+ “tt” +ename[i]+ “tt” +job[i]+ “tt”+ sal[i]);
}
}
public static void main(String args[])throws IOException
{
34
get();
System.out.println(“n ENOtt ENAMEtt JOBtt SALARYn”);
disp();
}
}
Sample input and output:
Enter 1 employee details:
Enter employee no and name : -5554
Exception caught : enter valid number
Enter 1 employee detail :
Enter employee no and name : 3001
R.Haricharan
Enter job and salary : lecturer 25000
Enter 2 employee detail :
Enter employee no and name : 5001
S.Kalaiselvan
Enter job and salary : reader
20000
Enter 3 employee detail :
Enter employee no and name : 7801
S.Rajadurai
Enter job and salary : director
23000
35
ENO ENAME JOB SALARY
3001 R.Haricharan lecturer 25000
5001 S.Kaliselvan reader 20000
7801 S.Rajadurai director 23000
Result:
Thus, the java program was created and executed successfully and output is verified.
36
ExNo : 10
MULTI THREADING – join() and isAlive()
Aim:
To create a java program in a multithread environment and implement join() and
isAlive() functions.
Algorithm:
 Create a class table that is derived from Thread.
 Declare name as string.
 Create a constructor table , pass thread name.
 Call super(threadname) , start() , start the thread.
 Create a function run() , print the multiples of 5.
 Create another class fseries that extends thread.
 Declare name as string and t1,t2,t3 as int and set f1=-1,f2=1.
 Create a constructor fseries pass thread name call super thread name()
 In the run() function display the Fibonacci series.
 Create a class multi in the main function , create object f for table.
 f.join() waits for thread to find
 create object f for fseries and do f.join().
Source code:
import java.io.*;
class table extends Thread
{
String name;
table(String threadname)
{
super(threadname);
37
name = threadname;
System.out.println(“n New thread :’ +this);
start();
}
public void run()
{
System.out.println(“n Five Table”);
for(int i=0;i<=10;i++)
{
System.out.println(“n i+ “*5=” +(i*5));
}
}
}
class fseries extends Thread
{
String name;
int f1 = -1 , f2 = 1 , f3;
fseries(String threadname)
{
super(threadname);
name = threadname;
System.out.println(“n New thread :” + this);
start();
38
}
public void run()
{
System.out.println(“n Fibonacci Series”);
for(int i= 1;i<=5 ;i++)
{
f3 = f1 +f2;
f1 = f2;
f2 = f3;
System.out.println( f3);
}
}
}
class multi
{
public static void main(String args[])
{
try
{
table t= new table(“Five Table”);
System.out.println(“n First thread is alive :’ +t.isAlive());
t.join();
System.out.println(“n First thread is alive :’ +t.isAlive());
39
fseries f = new fseries(“Fibonacci Series”);
System.out.println(“n Second thread is alive :” +f.isAlive());
}
catch(InterruptedException e)
{
System.out.println(“n Main thread is interrupted”);
}
System.out.println(“n Main thread is exiting”);
}
}
Sample input and output:
New thread : Thread[Five Table , 5, main]
First thread is alive : true
Five Table
1*5=5
2*5=10
3*5=15
4*5=20
5*5=25
6*5=30
7*5=35
8*5=40
9*5=45
40
10*5=50
First thread is alive : false
New thread [Fibonacci Series , 5, main]
Fibonacci series
Second thread is alive : true
0
1
1
2
3
Second thread is alive : false
Main thread is exiting.
Result:
Thus, the java program was created and executed successfully and output is verified.
41
ExNo : 11
MULTI THREADING : INTER-THREAD COMMUNICATON
Aim:
To write a java program to implement the concept of inter-thread communication.
Algorithm:
 creating a class q and declare variable n as int and declare value set(Boolean) as
false.
 Create synchronized method in get().
 Create another synchronized method void put(int n).
 If (value set) then go to try and catch . inside catch call notify() this tells
produces that it away put more about in the queue.
 Create a class producer , that implements runnable.
 Create object q. create a constructor producer where object is passed.
 Create a function run() , initialize and declare i= 0.
 Create a class consumer that implements runnable.
 Create constructor consumer , pass the object and create a function run().
 Create a class multi2 inside the main function and create object q.
Source code:
import java.io.*;
class consumer implements Runnable
{
Stock c;
Thread t;
Consumer(Stock c)
{
this.c=c;
42
t = new Thread(this , “producer thread”);
t.start();
}
public void run()
{
while(true)
{
try
{
t.sleep(750);
}
catch(InterrupedException e)
{}
c.getstock((int) (Math.random() * 100);
}
}
void stop()
{
t.stop();
}
}
class producer implements Runnable
{
43
Stock s;
Thread t;
producer(Stock s)
{
this.s=s;
t= new Thread(this , “producer thread”);
t.start();
}
public void run()
{
while(true)
{
try
{
t.sleep(750);
}
catch(InterrupedException e)
{}
c.getstock((int) (Math.random() * 100);
}
}
void stop()
{
44
t.stop();
}
}
class stock
{
int goods = 0;
public synchronized void addstock(int i)
{
goods = goods +i ;
System.out.println(“n stock added :” +i);
System.out.println(“n present stock :’ +goods);
notify();
}
public synchronized int getstock(int j)
{
while(true)
{
if(goods>=j)
{
goods = goods-j;
System.out.println(“n stock taken away :” +j);
System.out.println(“n present stock :” +goods);
break;
45
}
else
{
System.out.println(“n stock not enough…”);
System.out.println(“n waiting for stock to come..”);
try
{
wait();
}
catch(InterrupedException e)
{}
}
}
return goods;
}
public static void main(String args[])
{
stock j = new stock();
producer p = new producer (j);
consumer c =new consumer (j);
try
{
Thread.sleep(20000);
46
p.stop(); c.stop();p.t.join();c.t.join();
System.out.println(“n Thread stopped”);
}
catch(InterrupedException e)
{}
System.exit(0);
}
}
Sample input and output:
Stock added : 58
Present stock : 58
Stock taken away : 32
Present stock : 26
Stock not enough..
Waiting for stock to come..
Stock added : 15
Present stock : 41
Stock not enough …
Waiting for stock to come ..
Thread stopped.
Result:
Thus, the java program was created and executed successfully and output is verified.
47
Ex.No:12
ADDITION OF TWO NUMBERS USING APPLET
Aim:
To write a java program to implement applet concept.
Algorithm:
1. Start
2. Create a object for input stream class
3. Compile the program in java
4. Run the program using applet viewer
5. Enter the values
6. End.
Source Code:
import java.awt.*;
import java.applet.*;
public class userin extends applet
{
TextField text1,text2;
public void init()
{
text1=new TextField(8);
text2=new TextField(8);
add(text1);
add(text2);
48
text1.setText("0");
text2.setText("0");
}
public void paint(Graphics g)
{
int x=0,y=0,z=0;
String s1,s2,s;
g.drawString("input a number in each box",10,50);
try
{
s1=text1.getText();
x=Integer.parsseInt(s1);
s2=text2.getText();
y=Integer.parseInt(s2);
}
catch(Exception ex)
{}
z=x+y;
s=String.valueOf(z);
g.drawString("the sum is:",10,75);
g.drawString(s,100,75);
}
public boolean action(Event event,Object object)
49
{
repaint();
return true;
}
/*<applet
code="userin"
width=300
height=200>
</applet>*/
}
Execution Method:
C:j2sdk1.4.1_06bin>javac userin.java
Note:userin.java uses or overrides a deprecated API
Note:recpmpile with-deprecation for details
C:j2sdk1.4.1_06bin>appletviewer userin.java
Result:
Thus the java program to add two numbers using applet was created and executed
successfully and the output was verified.
50
Ex.No:13
JOB SCHEDULING TECHNIQUES
Aim:
To write a java program to implement the concept of different job scheduling
techniques like,
a) First Come First Served[FCFS]
b) Shortest Job First[SJF]
c) Round Robin
d) Priority Scheduling
Algorithm:
a) First Come First Served:
1. Get the number by jobs to be scheduled
2. Get the arrival time and service time of each and every job
3. Get the job according time as zero for each jobs
4. Initialize the waiting time as zero for each jobs
5. Compute each job and find the average waiting by dividing
total compute each job and find number of jobs
b) Shortest Job First:
1. Get the number of jobs to be scheduled
2. Get the arrival time and service time of each job
3. sort the job according to its service time
4. Intialize the waiting time as zero for each job
c) Round Robin:
51
1. Get the number of jobs to be scheduled
2. Get the arrival time ,service time and timeslice of each job
3. Sort the job according to its time of the arrival
4. Repeat the above steps intill all the jobs are completely
serviced
d) Priority scheduling:
1. Get the number of jobs to be scheduled
2.Get the arrival time, service time and priority of every jobs
3. Initialize the waiting time as zero for each jobs
4. While processing the jobs according to the started time and
the service time of the jobs being processed currently to the
waiting time for each job
5. Compute the total waiting time by adding individual waiting
time of the each job and find the arrange time of job
Source Code for FCFS:
import java.io.*;
class schedule
{
int hr,min,sec,ser,wait;
String name;
DataInputStream d=new DataInputStream(System.in);
void get()throws IOException
{
52
System.out.println("ENTER PROCESS NAME:");
name=d.readLine();
System.out.println("ENTER THE HOUR:");
hr=Integer.parseInt(d.readLine());
if(hr<=24)
{
System.out.println("ENTER THE MINUTES:");
min=Integer.parseInt(d.readLine());
if(min<=60)
{
System.out.println("ENTER THE SECONDS:");
sec=Integer.parseInt(d.readLine());
if(sec<=60)
{
System.out.println("ENTER THE SERVICE TIME:");
ser=Integer.parseInt(d.readLine());
}
else
{
System.out.println("ENTER THE SECONDS<=60");
sec=Integer.parseInt(d.readLine());
}
}
53
else
{
System.out.println("ENTER THE MINUTES<=60");
min=Integer.parseInt(d.readLine());
}
}
else
{
System.out.println("ENTER THE HOURS<=24");
hr=Integer.parseInt(d.readLine());
}
}
void put()
{
System.out.println(" "+name"tt"+hr":"+min+":"+sec+"ttt"+ser+"ttt"+wait);
}
}
class fcfs
{
public static void main(String args[])throws IOException
{
int i,j;
float total=0.0f;
54
schedule s[],t;
DataInputStream d=new DataInputStream(System.in);
System.out.println("ENTER THE NUMBER OF PROCESSES:");
int n=Integer.parseInt(d.readLine();
s=new schedule[10];
t=new schedule();
for(i=0;i<n;i++)
{
s[i]=new schedule();
s[i].get();
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(s[i].hr>s[j].hr)
{
t=s[i];
s[i]=s[j];
s[j]=t;
}
else if(s[i].hr==s[j].hr&&s[i].min>s[j].min&&s[i].sec>s[j].sec)
{
55
t=s[i];
s[i]=s[j];
s[j]=t;
}
else if(s[i].hr==s[j].hr&&s[i].min>s[j].min&&s[i].sec>s[j].sec)
{
t=s[i];
s[i]=s[j];
s[j]=t;
}
}
}
System.out.println("nPROCESStSTARTING TIMEt SERVICE TIMEtWAITING
TIMEn");
for(i=0;i<n;i++)
{
if(i==0)
s[i].wait=0;
else
s[i].wait=s[i-1].wait+s[i-1].ser;
total+=s[i].wait;
s[i].put();
}
56
System.out.println("nTOTAL WAITING TIME""+total);
System.out.println("nAVERAGE WAITING TIME:"+(total/n));
}
}
Source Code for SJF:
import java.io.*;
class schedule
{
int hr,min,sec,ser,wait;
int tot;
String name;
DataInputStream d=new DataInputStream(System.in);
void get()throws IOException
{
System.out.println("ENTER PROCESS NAME:");
name=d.readLine();
System.out.println("ENTER THE HOUR:");
hr=Integer.parseInt(d.readLine());
if(hr<=24)
{
System.out.println("ENTER THE MINUTES:");
min=Integer.parseInt(d.readLine());
if(min<=60)
57
{
System.out.println("ENTER THE SECONDS:");
sec=Integer.parseInt(d.readLine());
if(sec<=60)
{
System.out.println("ENTER THE SERVICE TIME:");
ser=Integer.parseInt(d.readLine());
}
else
{
System.out.println("ENTER THE SECONDS<=60");
sec=Integer.parseInt(d.readLine());
}
}
else
{
System.out.println("ENTER THE MINUTES<=60");
min=Integer.parseInt(d.readLine());
}
}
else
{
System.out.println("ENTER THE HOURS<=24");
58
hr=Integer.parseInt(d.readLine());
}
tot=hr+min+sec;
}
void put()
{
System.out.println(name+"t"+hr+":"+min+":"+sec+"ttt"+ser+"ttt"+wait);
}
}
class sjf
{
public static void main(String args[])throws IOException
{
int i,j;
float total=0.0f;
schedule s[],t;
DataInputStream d=new DataInputStream(System.in);
System.out.println("ENTER THE NUMBER OF PROCESSES:"):
int n=Integer.parseInt(d.readLine());
s=new schedule[10];
t=new schedule();
for(i=0;i<n;i++)
{
59
s[i]=new schedule();
s[i].get();
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(s[i].ser>s[j].ser)
{
t=s[i];
s[i]=s[j];
s[j]=t;
}
}
}
System.out.println("nPROCESStSTARTING TIMEtSERVICE TIMEtWAITING
TIME");
for(i=0;i<n;i++)
{
if(i==0)
s[i].wait=0;
else
s[i].wait=s[i-1].wait+s[i-1].ser;
60
total+=s[i].wait;
s[i].put();
}
System.out.println("nTOTAL WAITING TIME:"+total);
System.out.println("nAVERAGE WAITING TIME:"+(total/n));
}
}
Source Code for Round Robin:
import java.io.*;
class schedule
{
int hr,min,sec,ser,wait;
String name;
DataInputStream d=new DataInputStream(System.in);
void get()throws IOException
{
System.out.println("ENTER PROCESS NAME:");
name=d.readLine();
System.out.println("ENTER THE HOUR:");
hr=Integer.parseInt(d.readLine());
if(hr<=24)
{
System.out.println("ENTER THE MINUTES:");
61
min=Integer.parseInt(d.readLine());
if(min<=60)
{
System.out.println("ENTER THE SECONDS:");
sec=Integer.parseInt(d.readLine());
if(sec<=60)
{
System.out.println("ENTER THE SERVICE TIME:");
ser=Integer.parseInt(d.readLine());
}
else
{
System.out.println("ENTER THE SECONDS<=60");
sec=Integer.parseInt(d.readLine());
}
}
else
{
System.out.println("ENTER THE MINUTES<=60");
min=Integer.parseInt(d.readLine());
}
}
else
62
{
System.out.println("ENTER THE HOURS<=24");
hr=Integer.parseInt(d.readLine());
}
}
void put()
{
System.out.println(name+"t"+hr+":"+min+":"+sec+"ttt"+ser+"ttt"+wait);
}
}
class round
{
public static void main(String args[])throws IOException
{
int i,j,k,round,max,ts,ml,w;
int mod[][]=new int[20][20];
int tser[]=new int[20];
float total=0.0f;
schedule s[],t;
DataInputStream d=new DataInputStream(System.in);
System.out.println("ENTER THE NUMBER OF PROCESSES:"):
int n=Integer.parseInt(d.readLine());
s=new schedule[10];
63
t=new schedule();
for(i=0;i<n;i++)
{
s[i]=new schedule();
s[i].get();
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(s[i].hr>s[j].hr)
{
t=s[i];
s[i]=s[j];
s[j]=t;
}
else if(s[i].hr==s[j].hr&&s[i].min>s[j].min)
{
t=s[i];
s[i]=s[j];
s[j]=t;
}
else if(s[i].hr==s[j].hr&&s[i].min>s[j].min&&s[i].sec>s[j].sec)
64
{
t=s[i];
s[i]=s[j];
s[j]=t;
}
}
}
System.out.println("enter the time slice:");
ts=Integer.parseInt(d.readLine());
max=0;
for(i=0;i<n;i++)
{
tser[i]=s[i].ser;
if(max<tser[i])
max=tser[i];
}
round=max/ts+1;
for(i=1;i<round;i++)
{
for(j=0;j<n;j++)
{
if(tser[j]!=0)
{
65
m1=tser[j]-ts;
if(m1>0)
{
mod[i][j]=ts;
tser[j]=tser[j]-ts;
}
else
{
mod[i][j]=tser[j];
tser[j]=0;
}
}
else
mod[i][j]=0;
}
}
for(k=0;k<n;k++)
{
w=0;
s[k].wait=0;
for(i=1;i<round;i++)
{
if(mod[i][k]==ts)
66
{
for(j=0;j<n;j++)
{
if(k!=j)
w=w+mod[i][j];
}
}
else
if(mod[i][k]!=0)
for(j=0;j<k;j++)
w=w+mod[i][j];
}
s[k].wait=w;
}
System.out.println("nPROCESStSTARTING TIMEtSERVICE TIMEtWAITING
TIME");
for(i=0;i<n;i++)
{
total+=s[i].wait;
s[i].put();
}
System.out.println("nTOTAL WAITING TIME:"+total);
System.out.println("nAVERAGE WAITING TIME:"+(total/n));
67
}
}
Source Code for priority scheduling:
import java.io.*;
class schedule
{
int hr,min,sec,ser,wait,pr;
int tot;
String name;
DataInputStream d=new DataInputStream(System.in);
void get()throws IOException
{
System.out.println("ENTER PROCESS NAME:");
name=d.readLine();
System.out.println("ENTER THE HOUR:");
hr=Integer.parseInt(d.readLine());
if(hr<=24)
{
System.out.println("ENTER THE MINUTES:");
min=Integer.parseInt(d.readLine());
if(min<=60)
{
System.out.println("ENTER THE SECONDS:");
68
sec=Integer.parseInt(d.readLine());
if(sec<=60)
{
System.out.println("ENTER THE SERVICE TIME:");
ser=Integer.parseInt(d.readLine());
System.out.println("ENTER THE PRIORITY:");
pr=Integer.parseInt(d.readLine());
}
else
{
System.out.println("ENTER THE SECONDS<=60");
sec=Integer.parseInt(d.readLine());
}
}
else
{
System.out.println("ENTER THE MINUTES<=60");
min=Integer.parseInt(d.readLine());
}
}
else
{
System.out.println("ENTER THE HOURS<=24");
69
hr=Integer.parseInt(d.readLine());
}
tot=hr+min+sec;
}
void put()
{
System.out.println(name+"t"+hr+":"+min+":"+sec+"ttt"+ser+"ttt"+wait);
}
}
class pri
{
public static void main(String args[])throws IOException
{
int i,j;
float total=0.0f;
schedule s[],t;
DataInputStream d=new DataInputStream(System.in);
System.out.println("ENTER THE NUMBER OF PROCESSES:"):
int n=Integer.parseInt(d.readLine());
s=new schedule[10];
t=new schedule();
for(i=0;i<n;i++)
{
70
s[i]=new schedule();
s[i].get();
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(s[i].pr>s[j].pr)
{
t=s[i];
s[i]=s[j];
s[j]=t;
}
}
}
System.out.println("nPROCESStSTARTING TIMEtSERVICE TIMEtWAITING
TIME");
for(i=0;i<n;i++)
{
if(i==0)
s[i].wait=0;
else
s[i].wait=s[i-1].wait+s[i-1].ser;
71
total+=s[i].wait;
s[i].put();
}
System.out.println("nTOTAL WAITING TIME:"+total);
System.out.println("nAVERAGE WAITING TIME:"+(total/n));
}
}
Sample Input and Output:
FCFS:
ENTER THE NUMBER OF PROCESSES:
4
ENTER PROCESS NAME:
P1
ENTER THE HOUR:
2
ENTER THE MINUTES:
5
ENTER THE SECONDS:
3
ENTER THE SERVICE TIME:
1
ENTER THE PROCESS NAME:
P2
72
ENTER THE HOUR:
4
ENTER THE MINUTES:
6
ENTER THE SECONDS:
3
ENTER THE SERVICE TIME:
4
ENTER PROCESS NAME:
P3
ENTER THE HOUR:
8
ENTER THE MINUTES:
3
ENTER THE SECONDS:
2
ENTER THE SERVICE TIME:
5
ENTER PROCESS NAME:
P4
ENTER THE HOUR:
6
ENTER THE MINUTES:
73
3
ENTER THE SECONDS:
1
ENTER THE SERVICE TIME:
6
PROCESS STARTING TIME SERVICE TIME WAITING TIME
P1 2:5:3 1 0
P2 4:6:3 4 1
P4 6:3:1 6 5
P3 8:3:2 5 11
TOTAL WAITING TIME:17.0
AVERAGE WAITING TIME:4.25
SJF:
ENTER THE NUMBER OF PROCESSES:
4
ENTER PROCESS NAME:
P1
ENTER THE HOUR:
4
ENTER THE MINUTES:
5
ENTER THE SECONDS:
3
74
ENTER THE SERVICE TIME:
2
ENTER THE PROCESS NAME:
P2
ENTER THE HOUR:
2
ENTER THE MINUTES:
1
ENTER THE SECONDS:
0
ENTER THE SERVICE TIME:
4
ENTER PROCESS NAME:
P3
ENTER THE HOUR:
3
ENTER THE MINUTES:
5
ENTER THE SECONDS:
2
ENTER THE SERVICE TIME:
7
ENTER PROCESS NAME:
75
P4
ENTER THE HOUR:
5
ENTER THE MINUTES:
2
ENTER THE SECONDS:
1
ENTER THE SERVICE TIME:
4
PROCESS STARTING TIME SERVICE TIME WAITING TIME
P1 4:5:3 2 0
P2 2:1:0 4 2
P4 5:2:1 4 6
P3 3:5:2 7 10
TOTAL WAITING TIME:18.0
AVERAGE WAITING TIME:4.5
Round Robin:
ENTER THE NUMBER OF PROCESSES:
4
ENTER PROCESS NAME:
P1
ENTER THE HOUR:
1
76
ENTER THE MINUTES:
1
ENTER THE SECONDS:
1
ENTER THE SERVICE TIME:
1
ENTER THE PROCESS NAME:
P2
ENTER THE HOUR:
2
ENTER THE MINUTES:
2
ENTER THE SECONDS:
2
ENTER THE SERVICE TIME:
2
ENTER PROCESS NAME:
P3
ENTER THE HOUR:
3
ENTER THE MINUTES:
3
ENTER THE SECONDS:
77
3
ENTER THE SERVICE TIME:
3
ENTER PROCESS NAME:
P4
ENTER THE HOUR:
4
ENTER THE MINUTES:
4
ENTER THE SECONDS:
4
ENTER THE SERVICE TIME:
4
Enter the time slice:
3
PROCESS STARTING TIME SERVICE TIME WAITING TIME
P1 1:1:1 1 0
P2 2:2:2 2 1
P3 3:3:3 3 6
P4 4:4:4 4 6
TOTAL WAITING TIME:13.0
AVERAGE WAITING TIME:3.25
78
Priority Scheduling:
ENTER THE NUMBER OF PROCESSES:
4
ENTER PROCESS NAME:
P1
ENTER THE HOUR:
1
ENTER THE MINUTES:
2
ENTER THE SECONDS:
3
ENTER THE SERVICE TIME:
4
ENTER THE PRIORITY:
3
ENTER THE PROCESS NAME:
P2
ENTER THE HOUR:
2
ENTER THE MINUTES:
5
ENTER THE SECONDS:
6
79
ENTER THE SERVICE TIME:
3
ENTER THE PRIORITY:
2
ENTER PROCESS NAME:
P3
ENTER THE HOUR:
6
ENTER THE MINUTES:
2
ENTER THE SECONDS:
1
ENTER THE SERVICE TIME:
6
ENTER THE PRIORITY:
1
ENTER PROCESS NAME:
P4
ENTER THE HOUR:
7
ENTER THE MINUTES:
3
ENTER THE SECONDS:
80
1
ENTER THE SERVICE TIME:
5
ENTER THE PRIORITY:
4
PROCESS STARTINGTIME SERVICETIME WAITINGTIME PRIORITY
P3 6:2:1 6 0 1
P2 2:5:6 3 6 2
P1 1:2:3 4 9 3
P4 7:3:1 5 13 4
TOTAL WAITING TIME:28.0
AVERAGE WAITING TIME:7.0
Result:
Thus the java program to implement the job scheduling techniques was
created,executed successfully and the output was verified.
81
Ex.No:14
DISK SCHEDULING TECHNIQUES
Aim:
To write a java program to implement the concept of different disk scheduling
techniques like,
a)First Come First Server[FCFS]
b)Shortest Seek Time First[SSTF]
c)Scan
d)C-Scan
e)Look
f)C-Look
Algorithm:
a) First Come First Serverd:
Move the head according to the request
b) Shortest Seek Time First:
Move the disk arm to the request position from the current position inward
or outward that maintain minimizes arm movements
c) Scan:
1.Move the disk arm to the requested position in the path
2.Change the direction when there are no more request to service in
the count direction
d) C-Scan:
Move the disk arm to the requested position which moving towards
inward and direction
82
e) Look:
The arm goes only as far as the final request in each direction then it reverse it
direction
f) C-Look:
1. Move head from current position
2. Process the request untill the condition is satisfied
Source Code for FCFS:
import java.io.*;
import java.lang.*;
class disk_fcfs
{
public static void main(String args[])throws IOException
{
int i,sum=0,n,st;
int b[],dd[],a[];
a=new int[20];
b=new int[20];
dd=new int[20];
DataInputStream d=new DataInputStream(System.in);
do
{
System.out.println("Enter the block number between 0 and 200:");
st=Integer.parseInt(d.readLine());
83
}while((st>=200)||(st<0));
System.out.println("nOur disk head is on the"+st+"th block");
a[0]=st;
System.out.println("nEnter the no.of request:");
n=Integer.parseInt(d.readLine());
System.out.println("nEnter request:n");
for(i=1;i<=n;i++)
{
do
{
System.out.println("Enter "+i+"Request:");
a[i]=Integer.parseInt(d.readLine());
if((a[i]>200)||(a[i]<0))
{
System.out.println("nBlock number must be between 0 and 200!n");
}
}while((a[i]>200)||(a[i]<0));
}
for(i=0;i<=n;i++)
dd[i]=a[i];
System.out.println("nnttFIRST COME FIRST SERVE");
System.out.println("nDISK QUEUE:");
for(i=0;i<=n;i++)
84
{
System.out.println("t"+a[i]);
System.out.println("nnACCESS ORDER:");
for(i=0;i<=n;i++)
{
System.out.println("t"+dd[i]);
if(i!=n)
sum+=Math.abs(dd[i]-dd[i+1]);
}
System.out.println("nnTotal no.of head Movements:"+sum);
}
}
Source Code for SSTF:
import java.io.*;
import java.lang.*;
class disk_sstf
{
public static void main(String args[])throws IOException
{
int i,j,z,c=0,sum=0,n,n1,min,st;
int b[],dd[],a[];
a=new int[20];
b=new int[20];
85
dd=new int[20];
DataInputStream d=new DataInputStream(System.in);
do
{
System.out.println("Enter the block number between 0 and 200:");
st=Integer.parseInt(d.readLine());
}while((st>=200)||(st<0));
System.out.println("nOur disk head is on the"+st+"th block");
a[0]=st;
System.out.println("nEnter the no.of request:");
n=Integer.parseInt(d.readLine());
System.out.println("nEnter request:n");
for(i=1;i<=n;i++)
{
do
{
System.out.println("Enter "+i+"Request:");
a[i]=Integer.parseInt(d.readLine());
if((a[i]>200)||(a[i]<0))
{
System.out.println("nBlock number must be between 0 and 200!n");
}
}while((a[i]>200)||(a[i]<0));
86
}
for(i=0;i<=n;i++)
dd[i]=a[i];
n1=n;
b[0]=dd[0];
st=dd[0];
while(n1>0)
{
j=1;
min=Math.abs(dd[0]=dd[1]);
for(i=2;i<n1+1;i++)
{
if(Math.abs(st-dd[i]<=min)
{
min=Math.abs(st-dd[i]);
j=i;
}
}
c++;
b[c]=dd[j];
st=dd[j];
dd[0]=dd[j];
--n1;
87
for(z=j;z<n1+1;z++)
dd[z]=dd[z+1];
dd[z]='0';
}
System.out.println("nnttSHORTEST SEEK TIME FIRST:");
System.out.println("nDISK QUEUE:");
for(i=0;i<=n;i++)
System.out.println("t"+a[i]);
System.out.println("nnACCESS ORDER:");
for(i=0;i<=c;i++)
{
System.out.println("t"+b[i]);
if(i!=c)
sum+=Math.abs(b[i]-b[i+1]);
}
System.out.println("nn Total no.of head movements:"+sum);
}
}
Source Code for Scan:
import java.io.*;
import java.lang.*;
class disk_scan
{
88
public static void main(String args[])throws IOException
{
int i,j,c=0,sum=0,n,st,temp,t;
int b[],dd[],a[];
a=new int[20];
b=new int[20];
dd=new int[20];
DataInputStream d=new DataInputStream(System.in);
do
{
System.out.println("Enter the block number between 0 and 200:");
st=Integer.parseInt(d.readLine());
}while((st>=200)||(st<0));
System.out.println("nOur disk head is on the"+st+"th block");
a[0]=st;
System.out.println("nEnter the no.of request:");
n=Integer.parseInt(d.readLine());
System.out.println("nEnter request:n");
for(i=1;i<=n;i++)
{
do
{
System.out.println("Enter "+i+"Request:");
89
a[i]=Integer.parseInt(d.readLine());
if((a[i]>200)||(a[i]<0))
{
System.out.println("nBlock number must be between 0 and 200!n");
}
}while((a[i]>200)||(a[i]<0));
}
for(i=0;i<=n;i++)
dd[i]=a[i];
for(i=0;i<=n;i++)
for(j=i+1;j<=n;j++)
if(dd[i]>dd[j])
{
temp=dd[i];
dd[i]=dd[j];
dd[j]=temp;
}
for(i=0;i<=n;i++)
{
if(st==dd[i])
{
t=i+1;
b[c]=st;
90
for(j=i-1;j>=0;j--)
b[++c]=dd[j];
b[++c]=0;
for(j=t;j<=n;j++)
b[++c]=dd[j];
}
}
System.out.println("nnttSCAN TECHNIQUE:");
System.out.println("nDISK QUEUE:");
for(i=0;i<=n;i++)
System.out.println("t"+a[i]);
System.out.println("nnACCESS ORDER:");
for(i=0;i<=c;i++)
{
System.out.println("t"+b[i]);
if(i!=c)
sum+=Math.abs(b[i]-b[i+1]);
}
System.out.println("nn Total no.of head movements:"+sum);
}
}
91
Source Code for C-Scan:
import java.io.*;
import java.lang.*;
class disk_c_scan
{
public static void main(String args[])throws IOException
{
int i,j,sum=0,n,st,temp,t,c=0;
int b[],dd[],a[];
a=new int[20];
b=new int[20];
dd=new int[20];
DataInputStream d=new DataInputStream(System.in);
do
{
System.out.println("Enter the block number between 0 and 200:");
st=Integer.parseInt(d.readLine());
}while((st>=200)||(st<0));
System.out.println("nOur disk head is on the"+st+"th block");
a[0]=st;
System.out.println("nEnter the no.of request:");
n=Integer.parseInt(d.readLine());
System.out.println("nEnter request:n");
92
for(i=1;i<=n;i++)
{
do
{
System.out.println("Enter "+i+"Request:");
a[i]=Integer.parseInt(d.readLine());
if((a[i]>200)||(a[i]<0))
{
System.out.println("nBlock number must be between 0 and 200!n");
}
}while((a[i]>200)||(a[i]<0));
}
for(i=0;i<=n;i++)
dd[i]=a[i];
for(i=0;i<=n;i++)
for(j=i+1;j<=n;j++)
if(dd[i]>dd[j])
{
temp=dd[i];
dd[i]=dd[j];
dd[j]=temp;
}
for(i=0;i<=n;i++)
93
{
if(st==dd[i])
{
t=i;
b[c]=st;
for(j=t+1;j>=n;j++)
b[++c]=dd[j];
b[++c]=199;
b[++c]=0;
for(j=0;j<t;j++)
b[++c]=dd[j];
}
}
System.out.println("nnttC-SCAN TECHNIQUE:");
System.out.println("nDISK QUEUE:");
for(i=0;i<=n;i++)
System.out.println("t"+a[i]);
System.out.println("nnACCESS ORDER:");
for(i=0;i<=c;i++)
{
System.out.println("t"+b[i]);
if(i!=c)
sum+=Math.abs(b[i]-b[i+1]);
94
}
System.out.println("nn Total no.of head movements:"+sum);
}
}
Source Code for Look:
import java.io.*;
import java.lang.*;
class disk_look
{
public static void main(String args[])throws IOException
{
int i,j,c=0,sum=0,n,st,temp,t,s;
int b[],dd[],a[];
a=new int[20];
b=new int[20];
dd=new int[20];
DataInputStream d=new DataInputStream(System.in);
do
{
System.out.println("Enter the block number between 0 and 200:");
st=Integer.parseInt(d.readLine());
}while((st>=200)||(st<0));
System.out.println("nOur disk head is on the"+st+"th block");
95
a[0]=st;
System.out.println("nEnter the no.of request:");
n=Integer.parseInt(d.readLine());
System.out.println("nEnter request:n");
for(i=1;i<=n;i++)
{
do
{
System.out.println("Enter "+i+"Request:");
a[i]=Integer.parseInt(d.readLine());
if((a[i]>200)||(a[i]<0))
{
System.out.println("nBlock number must be between 0 and 200!n");
}
}while((a[i]>200)||(a[i]<0));
}
for(i=0;i<=n;i++)
dd[i]=a[i];
s=a[0];
for(i=0;i<=n;i++)
for(j=i+1;j<=n;j++)
if(dd[i]>dd[j])
{
96
temp=dd[i];
dd[i]=dd[j];
dd[j]=temp;
}
for(i=0;i<=n;i++)
{
if(st==dd[i])
{
b[c]=st;
for(j=i-1;j>=0;j--)
b[++c]=dd[j];
b[++c]=200;
for(j=n;j>i;j--)
b[++c]=dd[j];
}
}
System.out.println("nnttLOOK TECHNIQUE:");
System.out.println("nDISK QUEUE:");
for(i=0;i<=n;i++)
System.out.println("t"+a[i]);
System.out.println("nnACCESS ORDER:");
for(i=0;i<=c;i++)
{
97
System.out.println("t"+b[i]);
if(i!=c)
sum+=Math.abs(b[i]-b[i+1]);
}
System.out.println("nn Total no.of head movements:"+sum);
}
}
Source Code for C-Look:
import java.io.*;
import java.lang.*;
class disk_c_look
{
public static void main(String args[])throws IOException
{
int i,j,c=0,sum=0,n,st,temp,t,s;
int b[],dd[],a[];
a=new int[20];
b=new int[20];
dd=new int[20];
DataInputStream d=new DataInputStream(System.in);
do
{
System.out.println("Enter the block number between 0 and 200:");
98
st=Integer.parseInt(d.readLine());
}while((st>=200)||(st<0));
System.out.println("nOur disk head is on the"+st+"th block");
a[0]=st;
System.out.println("nEnter the no.of request:");
n=Integer.parseInt(d.readLine());
System.out.println("nEnter request:n");
for(i=1;i<=n;i++)
{
do
{
System.out.println("Enter "+i+"Request:");
a[i]=Integer.parseInt(d.readLine());
if((a[i]>200)||(a[i]<0))
{
System.out.println("nBlock number must be between 0 and 200!n");
}
}while((a[i]>200)||(a[i]<0));
}
for(i=0;i<=n;i++)
dd[i]=a[i];
s=a[0];
for(i=0;i<=n;i++)
99
for(j=i+1;j<=n;j++)
if(dd[i]>dd[j])
{
temp=dd[i];
dd[i]=dd[j];
dd[j]=temp;
}
for(i=0;i<=n;i++)
{
if(st==dd[i])
{
t=i;
b[c]=st;
for(j=t+1;j<=n;j++)
b[++c]=dd[j];
for(j=0;j<t;j++)
b[++c]=dd[j];
}
}
System.out.println("nnttC-LOOK TECHNIQUE:");
System.out.println("nDISK QUEUE:");
for(i=0;i<=n;i++)
System.out.println("t"+a[i]);
100
System.out.println("nnACCESS ORDER:");
for(i=0;i<=c;i++)
{
System.out.println("t"+b[i]);
if(i!=c)
sum+=Math.abs(b[i]-b[i+1]);
}
System.out.println("nn Total no.of head movements:"+sum);
}
}
Sample Input and Output:
FCFS:
Enter the block number between 0 and 200:53
Our disk head is on the 53th block
Enter the no.of request:5
Enter Request:
Enter 1 Request:123
Enter 2 Request:45
Enter 3 Request:20
Enter 4 Request:100
Enter 5 Request:199
FIRST COME FIRST SERVE
DISK QUEUE : 53 123 45 20 100 199
101
ACCESS ORDER : 53 123 45 20 100 199
Total no.of head movements : 352
SSTF:
Enter the block number between 0 and 200:53
Our disk head is on the 53th block
Enter the no.of request:5
Enter Request:
Enter 1 Request:123
Enter 2 Request:45
Enter 3 Request:20
Enter 4 Request:100
Enter 5 Request:199
SHORTEST SEEK TIME FIRST
DISK QUEUE : 53 123 45 20 100 199
ACCESS ORDER : 53 45 20 100 123 199
Total no.of head movements : 212
SCAN:
Enter the block number between 0 and 200:53
Our disk head is on the 53th block
Enter the no.of request:5
Enter Request:
Enter 1 Request:45
Enter 2 Request:20
102
Enter 3 Request:123
Enter 4 Request:100
Enter 5 Request:199
SCAN TECHNIQUE:
DISK QUEUE : 53 45 20 123 100 199
ACCESS ORDER : 53 45 20 0 100 123 199
Total no.of head movements : 252
C-SCAN:
Enter the block number between 0 and 200:53
Our disk head is on the 53th block
Enter the no.of request:5
Enter Request:
Enter 1 Request:123
Enter 2 Request:45
Enter 3 Request:20
Enter 4 Request:100
Enter 5 Request:199
C-SCAN TECHNIQUE:
DISK QUEUE : 53 123 45 20 100 199
ACCESS ORDER : 53 100 123 199 199 0 20 45
Total no.of head movements : 390
LOOK:
Enter the block number between 0 and 200:53
103
Our disk head is on the 53th block
Enter the no.of request:5
Enter Request:
Enter 1 Request:123
Enter 2 Request:45
Enter 3 Request:20
Enter 4 Request:100
Enter 5 Request:199
LOOK TECHNIQUE:
DISK QUEUE : 53 123 45 20 100 199
ACCESS ORDER : 53 45 20 200 100 123 100
Total no.of head movements : 313
C-LOOK:
Enter the block number between 0 and 200:53
Our disk head is on the 53th block
Enter the no.of request:5
Enter Request:
Enter 1 Request:123
Enter 2 Request:45
Enter 3 Request:20
Enter 4 Request:100
Enter 5 Request:199
104
C-LOOK TECHNIQUE:
DISK QUEUE : 53 123 45 20 100 199
ACCESS ORDER : 53 100 123 199 20 45
Total no.of head movements : 350
Results:
Thus the java program to implement the disk scheduling techniques was created,
executed successfully and the output was verified.
105
Ex.No:15
MEMORY ALLOCATION TECHNIQUES
Aim:
To write a java program to implement the concept of different memory allocation
techniques like,
a) First Fit
b) Best Fit
c) Worst Fit
d) Next Fit
Algorithm:
a) First Fit
1. Get thenumber of process to be allocated
2. Get the number of free blocks available and its size
3. Find the first free block from the starting, so that the new
process can allocated fully in that block
b) Best Fit
1. Get the number of process to be allocated
2. Get the number of free blocks available and its size
3. Repeat the above steps, so that all the process can be allocated
c) Worst Fit
1. Get the number of process to be allocated
2. Get the number of free blocks available and size
3. Get the memory size of the process to be allocated
106
4. Repeat the above steps, so that all the process can be allocated
d) Next Fit
1. Get the number of process to be allocated
2. Get the memory of free blocks available and its size
3. Get the memory size of the process to be allocated
4. Find the first free block from the starting, so that the new
process can be allocated in that block.
Source Code:
import java.lang.*;
import java.io.*;
class MALLOCATION
{
static int f1,p,next,c,l;
static int bsize[]=new int[30];
static int fsize[]=new int[30];
static int f1size[]=new int[30];
static int asize[]=new int[30];
static void firstFit(int n)
{
int k=0,i=1;
for(i=0;i<f1;i++)
{
if(fsize[i]>=n)
107
{
asize[i]=asize[i]+n;
next=i+1;
System.out.println("nMEMORY ALLOCATION IN BLOCK:"+i);
int s1=50;
for(l=0;l<i;l++)
s1=s1+fsize[l]+asize[l];
System.out.println("nMemory allocated for process:"+asize[l]);
fsize[i]=-n;
k=1;
break;
}
}
if(k==0)
System.out.println("nNo matching block for:"+n);
System.out.println("n");
}
static void bestFit(int n)
{
int l,s,k=0;
int min1=10000;
for(int i=0;i<f1;i++)
{
108
if((fsize[i]-n)>=0)
{
s=fsize[i]-n;
if(s<min1)
{
min1=s;
k=i+1;
{
int l,k=0;
for(int i=next;i<f1;i++)
{
if((fsize[i]-n)>=n)
{
next=i+1;
fsize[i]=fsize[i]-n;
asize[i]=asize[i]+n;
int s1=50;
for(l=0;l<i;l++)
s1=s1+fsize[l]+asize[l];
System.out.println("n Memory allocated for process:"+asize[l]);
System.out.println("n Memory allocated in block:"+(k-1));
k=1;
break;
109
}
}
if(k==0)
System.out.println("n No matching block for:"+n);
System.out.println();
}
public static void main(String args[])
{
try
{
BufferedReader ob=new BufferedReader(new InputStreamReader(System.in));
char ch;
int var=1;
int b1size,i;
next=0;
System.out.println("nttMEMORY ALLOCATION TECHNIQUES");
System.out.println("ntt*************************************");
System.out.println("Output for memory allocation techniques");
System.out.println("nEnter the number of free block:");
f1=Integer.parseInt(ob.readLine());
int sum=50;
System.out.println("Enter within the width 480");
System.out.println(Enter width within the limit");
110
for(i-0;i<f1;i++)
{
System.out.println("nEnter the size of the block"+i+":");
fsize[i]=Integer.parseInt(ob.readLine());
if(fsize[i]>481)
{
System.out.println("nExecuting the limit, re-enter the value!");
System.out.println();
continue;
}
}
}
if(k!=0)
{
next=k;
fsize[k-1]=min1;
asize[k-1]+=n;
int s1=50;
for(l=0;l<k-1;l++)
s1=s1+fsize[l]+asize[l];
System.out.println("n Memory allocated for process:"+asize[l]);
System.out.println("n Memory allocated in block:"+(k-1));
}
111
else
System.out.println("n No matching block for:"+n);
}
static void worstFit(int n)
{
int l,s,k-0;
int max1=0;
for(int i=0;i<f1;i++)
{
if((fsize[i]-n)>0)
{
s=fsize[i]-n;
if(s>=max1)
{
max1=s;
k=i+1;
}
}
}
if(k!=0)
{
next=k;
fsize[k-1]=max1;
112
fsize[k-1]=asize[k-1]+n;
int s1=50;
for(l=0;l<k-1;l++)
s1+=fsize[l]+asize[l];
System.out.println("n Memory allocated for process:"+asize[l]);
System.out.println("n Memory allocated in block:"+(k-1));
}
else
System.out.println("n No matching block for:"+n);
}
static void nextFit(int n)
{
f1size[i]=fsize[i];
asize[i]=0;
sum=sum+fsize[i];
}
System.out.println("nHow many no.of process:");
p=Integer.parseInt(ob.readLine());
for(i=0;i<p;i++)
{
System.out.println("n Enter the size of allocated memory process"+i+":");
bsize[i]=Integer.parseInt(ob.readLine());
}
113
while(var!=0)
{
System.out.println("nttMEMORY ALLOCATION TECHNIQUES");
System.out.println("ntt*************************************");
System.out.println("n1.FIRST FITn2.BEST FITn3.WORST FITn4.NEXT
FITn5.EXIT"):
System.out.println("nEnter your choice:");
c=Integer.parseInt(ob.readLine());
switch(c)
{
case 1:
for(i=0;i<p;i++)
firstFit(bsize[i]);
break;
case 2:
for(i=0;i<p;i++)
bestFit(bsize[i]);
break;
case 3:
for(i=0;i<p;i++)
worstFit(bsize[i]);
break;
case 4:
114
for(i=0;i<p;i++)
nextFit(bsize[i]);
break;
case 5:
System.exit(0);
default:
System.out.println("nENTERED WRONG CHOICE:"+c);
System.out.flush();
System.exit(0);
}
System.out.println("nDo you want to continue:");
ch=(char)ob.readLine().charAt(0);
if(ch=='n'||ch=='N')
System.exit(0);
sum=50;
for(i=0;i<f1;i++)
{
asize[i]=0;
sum=sum+f1size[i];
fsize[i]=f1size[i];
}
}
}
115
catch(IOException e)
{
System.out.println("n Exception Raised");
}
catch(Exception e)
{
}
}
}
Sample Input and Output:
MEMORY ALLOCATION TECHNIQUES
*************************************
Output for memory allocation techniques
Enter the number of free block:3
Enter within the width 480
Enter width within the limit
Enter the size of the block 0:100
Enter the size of the block 1:50
Enter the size of the block 2:200
How many no.of process:
3
Enter the size of allocated memory process 0:200
Enter the size of allocated memory process 1:250
116
Enter the size of allocated memory process 2:100
MEMORY ALLOCATION TECHNIQUES
*************************************
1.FIRST FIT
2.BEST FIT
3.WORST FIT
4.NEXT FIT
5.EXIT
Enter your choice:1
MEMORY ALLOCATION IN BLOCK : 2
Memory allocated for process : 200
No matching block for : 250
MEMORY ALLOCATION IN BLOCK : 0
Memory allocated for process : 100
Do you want to continue : Y
MEMORY ALLOCATION TECHNIQUES
*************************************
1.FIRST FIT
2.BEST FIT
3.WORST FIT
4.NEXT FIT
5.EXIT
Enter your choice : 2
117
Memory allocated for process : 200
Memory allocated in block : 2
No matching block for : 250
Memory allocated for process : 100
Memory allocated in block : 0
Do you want to continue : Y
MEMORY ALLOCATION TECHNIQUES
*************************************
1.FIRST FIT
2.BEST FIT
3.WORST FIT
4.NEXT FIT
5.EXIT
Enter your choice : 3
No matching block for : 200
No matching block for : 250
Memory allocated for process : 0
Memory allocated in block : 2
Do you want to continue : Y
MEMORY ALLOCATION TECHNIQUES
*************************************
1.FIRST FIT
2.BEST FIT
118
3.WORST FIT
4.NEXT FIT
5.EXIT
Enter your choice : 4
No matching block for : 200
No matching block for : 250
No matching block for : 100
Do you want to continue : Y
MEMORY ALLOCATION TECHNIQUES
*************************************
1.FIRST FIT
2.BEST FIT
3.WORST FIT
4.NEXT FIT
5.EXIT
Enter your choice : 5
Result:
Thus the java program to implement the memory allocation techniques was created,
executed successfully and the output was verified.
119
Ex.No:16
MEMORY MANAGEMENT TECHNIQUES
Aim:
To write a java program to implement the concept of different memory
management techniques like,
1.Paging
2.Demand paging
Algorithm:
1.Paging
i)Display option
a)store
b)Retrieve
c)Exit
ii)Read ch
iii)if ch=’a’ then get page size and process size
iv)allocate process in pages
v)if ch=’2’ then get logical address to the retrieve
2.Page demand
i)Display option
a)Store
b)Retrieve
c)Exit
ii)Read ch
iii)allocate the content to the page
iv)Enter the page number
Source code for paging:
import java.io.*;
class pagemanagementsub
{
120
String name;
class pagemanagementsub
{
String content;
}
pagemanagementsub page[]=new pagemanagementsub[10];
public pagemanagement()
{
for(int i=0;i<10;i++)
{
page[i]=new pagemanagementsub();
}
}
}
class mem_management
{
int pagememsize,pageprocesssize,ppage,ptotalpage;
int pframe[]=new int[10];
pagemanagement p[]=new pagemanagement[10];
public mem_management()
{
for(int i=0;i<10;i++)
{
p[i]=new pagemanagement();
}
}
void pagestore()throws IOException
{
DataInputStream d=new DataInputStream(System.in);
121
int i=0,j=0,e=0,t;
do
{
System.out.println(“nEnter the logical memory size(power of 2):”);
pagememsize=Integer.parseInt(d.readLine());
}
while(ispow2(pagememsize)!=0);
do
{
System.out.println(“nEnter the process size:”);
pageprocesssize=Integer.parseInt(d.readLine());
if(pageprocesssize>pagememsize)
System.out.println(“nError:process size should not exceed logical memory size!”);
}while(pageprocesssize>pagememsize);
do
{
System.out.println(“Enter the page size(power of 2):”);
ppage=Integer.parseInt(d.readLine());
}
while(ispow2(ppage)!=0);
ptotalpage=pageprocesssize/ppage;
if((pageprocesssize%ppage)!=0)
ptotalpage++;
for(i=0;i<ptotalpage;i++)
{
System.out.println(“Enter the content of page[“+i+”]:”);
for(j=0;j<ppage;j++)
{
System.out.println(“Enter the content[“+j+”]:”);
122
p[i].page[j].content=d.readLine();
e++;
if(e==pageprocessize)
break;
}
}
System.out.println(“Page Not Frame No”);
for(i=0;i<ptotalpage;i++)
{
System.out.println(“ “+i+”tt”);
pframe[i]=Integer.parseInt(d.readLine());
}
System.out.println(“ntPhysical memoryn”);
e=0;
for(i=0;i<ptotalpage;i++)
{
System.out.println(“nContent of page[“+i+”]:”);
for(i=0;i<ppage;i++)
{
t=(pframe[i]*ppage)+j;
System.out.println(“Content[“+t+”]:”);
System.out.println(p[i].page[j].content);
e++;
if(e==pageprocesssize)
break;
}
}
if((pageprocesssize%ppage)!=0)
Syatem.out.println(“nThe page has internal fragmentation”);
123
}
int ispow(int no)
{
float n=(float)no;
for(;n>2;)
n/=2;
if(n==2.0)
return 0;
else
return 1;
}
void pageretreive()throws IOException
{
DataInputStream d=new DataInputStream(System.in);
int offset=0,physical_addr=0,logical_addr;
int pageno,frameno;
System.out.println (“nEnter logical address to retrieve:”);
logical_addr=Integer.parseInt(d.readLine());
if(logical_addr>=pageprocesssize||logical_addr<0)
{
System.out.println(“Logical address exceeds process size!”);
return;
}
pageno=logical_addr/ppage;
frameno=pframe[pageno];
offset=logical_addr%ppage;
physical_addr=offset+(frameno*ppage);
System.out.println(“nPage no:”+pageno);
System.out.println(“nFrame no:”+frameno);
124
System.out.println(“nOffset value:”+offset);
System.out.println(“nPhysical address:”+physical_addr);
System.out.println(“nContent:”+p[pageno].page[offset].content);
}
}
class mem_paging
{
public static void main(String args[])throws IOException
{
mem_management m=new mem_management();
int ch;
DataInputStream d=new DataInputStream(System.in);
System.out.println(“nMEMORY MANAGEMENT TECHNIQUE:”);
System.out.println(“PAGING:”);
do
{
System.out.println(“n1.Store”);
System.out.println(“n2.Retreive”);
System.out.println(“n3.Exit”);
System.out.println(“nEnter your choice:”);
ch=Integr.parseInt(d.readLine());
switch(ch)
{
case 1:
m.pagestore();
break;
case 2:
m.pageretreive();
break;
125
case 3:
System.exit(0);
break;
default:
continue;
}
}
while(true);
}
}
Source code for Demand Paging:
import java.io.*;
class demand_paging
{
int prs,t;
int pmt[]=new int[20];
int limit[]=new int[20];
int base[]=new int[20];
String frame[]=new String[50];
String val[]=new String[50];
String cont=”y”;
void demandstore()throws IOException
{
int i,j,k=0;
DataInputStream d=new DataInputStream(System.in);
System.out.println(“nDemand Paging Storing”);
System.out.println(“nEnter the logical memory size:”);
prs=Integer.parseInt(d.readLine());
System.out.println(“nLogical memory contents:”);
126
for(i=0;i<prs;<i++)
{
System.out.println(“Enter the value[“+i+”]:”);
val[i]=d.readLine();
}
System.out.println(“nFrame Details:”);
for(i=0;i<prs;i++)
{
System.out.println(“Enter the frame no to store”’+val[i]+’”:”);
k=Integer.parseInt(d.readLine());
pmt[i]=k;
frame[i]=val[i];
}
t=prs;
System.out.println();
for(i=0;i<t;i++)
{
System.out.println(“Store”’+val[i]+’”in frame”+pmt[i]+”[Y/N]:”);
cont=d.readLine();
if(cont.equalsIgnoreCase(“y”))
{
base[i]=1;
j=0;
while(true)
{
if(val[i].compareTo(frame[j])==0)
{
limit[i]=pmt[i];
break;
127
}
else
j++;
}
}
else
{
limit[i]=-1;
base[i]=-1;
}
}
System.out.println(“nPage map table:”);
System.out.println(“PAGE NOtFRAME NOtCONTENT”);
for(i=0;i<t;i++)
{
System.out.println(“ “+i+”tt”+limit[i]+”tt”+val[i]);
}
System.out.println(“n(-1)represents frame number which is not loaded”);
}
void demandretreive()throws IOException
{
int I,j,k=0;
DataInputStream d=new DataInputStream(System.in);
System.out.println(“nDemand page retrieval:”);
System.out.print(“Enter the page no to retrieve [0-“+(prs-1)+”]:”);
i=Integer.parseInt(d.readLine());
while(i<prs)
{
if(base[i]==1)
128
{
System.out.println(“nThe page is loaded to frame”+limit[i]+”and content”val[i]);
break;
}
else
{
k=0;
while(true)
{
if(val[i].compareTo(frame[k])==0)
{
limit[i]=pmt[i];
base[i]=1;
break;
}
else
k++;
}
}
}
System.out.println(“nPage map table:”);
System.out.println(“PAGE NOtFRAME NOtCONTENT”);
for(i=0;i<t;i++)
{
System.out.println(“ “+i+”tt”+limit[i]+”tt”+val[i]);
}
System.out.println(“n(-1)represents frame no which is not loaded”);
}
}
129
class mem_demand
{
public static void main(String args[])throws IOException
{
demand_paging dp=new demand_paging();
int c;
DataInputStream d=new DataInputStream(System.in);
System.out.println(“nMEMORY MANAGEMENT TECHNIQUE”);
System.out.println(DEMAND Paging:”);
do
{
System.out.println(“n1.Store”);
System.out.println(“2.Retreive”);
System.out.println(“3.Exit”);
System.out.println(“nEnter your choice:”);
c=Integer.parseInt(d.readLine());
switch (c)
{
case 1:
dp.demandstore();
break;
case 2:
dp.demandretreive();
break;
case 3:
System.exit(0);
break;
default:
continue;
130
}
}
while(true);
}
}
Sample Input and Output:
Paging
MEMORY MANAGEMENT TECHNIQUE:
PAGING:
1.Store
2.Retreive
3.Exit
Enter your choice:1
Enter the logical memory size(power of 2):16
Enter the process size:10
Enter the page size(power of 2):4
Enter the content of page[0]:
Enter the content[0]:00
Enter the content[1]:01
Enter the content[2]:02
Enter the content[3]:03
Enter the content of page[1]:
Enter the content[0]:10
Enter the content[1]:11
Enter the content[2]:12
Enter the content[3]:13
Enter the content of page[2]:
Enter the content[0]:20
Enter the content[1]:21
131
Page No Frame No
0 1
1 3
2 0
Physical memory
Content of page[0]:
Content[4]:00
Content[5]:01
Content[6]:02
Content[7]:03
Content of page[1]:
Content[12]:10
Content[13]:11
Content[14]:12
Content[15]:13
Content of page[2]:
Content[0]:20
Content[1]:21
The page has internal fragmentation
1.Store
2.Retreive
3.Exit
Enter your choice:2
Enter logical address to retrieve:2
Page no:0
Frame no:1
Offset value:2
Physical address:6
Content:02
132
1.Store
2.Retreive
3.Exit
Enter your choice:3
Demand Paging
MEMORY MANAGEMENT TECHNIQUE:
DEMAND PAGING:
1.Store
2.Retreive
3.Exit
Enter your choice:1
Demand Paging Storing
Enter the logical memory size:10
Logical memory contents:
Enter the value[0]:one
Enter the value[1]:Two
Enter the value[2]:Three
Enter the value[3]:Four
Enter the value[4]:Five
Enter the value[5]:Six
Enter the value[6]:Seven
Enter the value[7]:Eight
Enter the value[8]:Nine
Enter the value[9]:Ten
Frame Details:
Enter the frame no to store ‘One’:11
Enter the frame no to store ‘Two’:22
Enter the frame no to store ‘Three’:33
133
Enter the frame no to store ‘Four’:44
Enter the frame no to store ‘Five’:55
Enter the frame no to store ‘Six’:66
Enter the frame no to store ‘Seven’:77
Enter the frame no to store ‘Eight’:88
Enter the frame no to store ‘Nine’:99
Enter the frame no to store ‘Ten’:100
Store ‘One’in frame 11[Y/N]:Y
Store ‘Two’in frame 22[Y/N]:Y
Store ‘Three’in frame 33[Y/N]:Y
Store ‘Four’in frame 44[Y/N]:Y
Store ‘Five’in frame 55[Y/N]:Y
Store ‘Six’in frame 66[Y/N]:N
Store ‘Seven’in frame 77[Y/N]:Y
Store ‘Eight’in frame 88[Y/N]:Y
Store ‘Nine’in frame 99[Y/N]:Y
Store ‘Ten’in frame 100[Y/N]:N
Page map table:
PAGE NO FRAME NO CONTENT
0 11 One
1 22 Two
2 33 Three
3 44 Four
4 55 Five
5 -1 Six
6 77 Seven
7 88 Eight
8 99 Nine
9 -1 Ten
134
(-1) represents frame number which is not loaded
1.Store
2.Retreive
3.Exit
Enter your choice:2
Demand page retrieval:
Enter the page no to retrieve[0-9]:1
The page is loaded to frame 22 and content Two
Page map table:
PAGE NO FRAME NO CONTENT
0 11 One
1 22 Two
2 33 Three
3 44 Four
4 55 Five
5 -1 Six
6 77 Seven
7 88 Eight
8 99 Nine
9 -1 Ten
(-1) represents frame number which is not loaded
1.Store
2.Retreive
3.Exit
Enter your choice:3
Result:
Thus the java program to implement the memory management techniques was
created, executed successfully and the output was verified
135
Ex.No:17
PAGE REPLACEMENT TECHNIQUES
Aim:
To write a java program to implement the concept of different page replacement
techniques.
Algorithm:
1.Start the program execution
2.enter the number of pages and frames
3.enter the value into pages
4.display menu
5.if ch=1,the FIFO
6.if ch=2,then LRU
7.if ch=3,then exit
8.if any page fault then print page fault occurs
9.Stop the execution
Source code:
import java.io.*;
class page_r
{
int page[][]=new int[50][50];
int p[]=new int[50];
int ht[]=new int[10];
int n,fr;
void get()throws IOException
{
int i;
DataInputStream d=new DataInputStream(System.in);
System.out.print(“nEnter the no.of page:”);
n=Integer.parseInt(d.readLine());
136
System.out.print(“nEnter the no.of frame:”);
fr=Integer.parseInt(d.readLine());
System.out.println(“nEnter the content:”);
for(i=0;i<n;i++)
p[i]=Integer.parseInt(d.readLine());
}
void fifo()
{
int i,j,k,l,c,t;
int flg,nw,pf;
c=0;
for(i=0;i<fr;i++)
page[i][c]=-1;
page[0][0]=p[0];
pf=1;
nw=1;
i=1;
while(i<n)
{
t=p[i];
flg=0;
for(k=0;k<fr;k++)
{
if(page[k][c]==t)
flg=1;
}
if(flg==0)
{
c++;
137
for(k=0;k<fr;k++)
{
page[k][c]=page[k][c-1];
}
page[nw][c]=t;
nw++;
pf++;
if(nw==fr)
nw=0;
}
else
{
i++;
}
}
System.out.println(“nnttFIFO”);
System.out.println(“nPage number:”);
for(i=0;i<n;i++)
System.out.print(p[i]+” ”);
System.out.println(“nnPage table:”);
for(k=0;k<fr;k++)
{
for(i=0;i<=c,i++)
{
if(page[k][i]==-1)
System.out.prin(“-“);
else
System.out.print(page[k][i]+” ”);
}
138
System.out.println();
}
System.out.println(“nTotal no.of page fault:”+pf);
}
void lru
{
int page1[][]=new int[fr][n];
int frame[]=new int[fr];
int count[]=new int[fr];
int I,j,k,ts,flg,pf=0,min,c=0;
ts=0;
for(i=0;i<fr;i++)
{
frame[i]=-1;
page1[i][c]=-1;
count[i]=0;
}
for(i=0;i<n;i++)
{
flg=0;
for(j=0;j<fr;j++)
{
if(frame[j]==-1)
{
if(flg==0)
{
page1[j][c]=p[i];
frame[j]=p[i];
ts++;
139
c++;
count[j]=ts;
flg=1;
continue;
}
}
if((frame[j]!=-1&&flg==0)||(frame[j]==-1&&flg==1))
{
page1[j][c]=page1[j][c-1];
}
}
if(flg==0)
{
for(j=0;j<fr;j++)
{
if(frame[j]==p[i])
{
ts++;
count[j]=ts;
flg=1;
}
else
{
page1[j][c]=page1[j][c-1];
}
}
}
if(flg==0)
{
140
min=100;
for(j=0;j<fr;j++)
{
if(count[j]<min)
min=count[j];
}
for(j=0;j<fr;j++)
{
if(count[j]==min)
{
frame[j]=p[i];
page1[j][c]=p[i];
ts++;
c++;
count[j]=ts;
}
else
{
page1[j][c]=page1[j][c-1];
}
}
}
}
System.out.println(“nttLRU”);
System.out.println(“nPage number:”);
for(i=0;i<n,i++)
System.out.print(p[i]+” “);
System.out.println(“nnPage table:”);
for(k=0;k<fr;k++)
141
{
for(i=0;i<c;i++)
if(page1[k][i]==-1)
System.out.print(“-“);
else
System.out.print(page1[k][i]+” “);
}
System.out.println(“nTotal no.of page fault:”+c);
}
void hitcount(int pos)
{
int i;
for(i=0;i<fr;i++)
if(i==pos)
ht[i]=1;
else if(ht[i]!=0)
ht[i]++;
}
}
class pagereplace
{
public static void main(String args[])throws IOException
{
DataInputStream d=new DataInputStream(System.in);
int ch;
page_r p=new page_r();
p.get();
do
{
142
System.out.println(“nn1.FIFO”);
System.out.println(“2.LRU”);
System.out.println(“3.Exit”);
System.out.print(“nEnter your choice:”);
ch=Integer.parseInt(d.readLine());
switch(ch)
{
case 1:
p.fifo();
break;
case 2:
p.lru();
break;
case 3:
System.out.println(“you are exiting”);
default:
System.out.println(“Invalid choice!!”);
}
}
while(ch!=3);
}
}
Sample Input and Output:
Enter the no.of page:5
Enter the no.frame:5
Enter the content:
2
3
4
143
5
6
1.FIFO
2.LRU
3.Exit
Enter your choice:1
FIFO
page number:
2 3 4 5 6
Page table:
2 2 2 2 2
- 3 3 3 3
- - 4 4 4
- - - 5 5
- - - - 6
Total no. of page fault:5
1.FIFO
2.LRU
3.Exit
Enter your choice:2
LRU
Page number:
2 3 4 5 6
Page table:
2 2 2 2 2
- 3 3 3 3
- - 4 4 4
144
- - - 5 5
- - - - 6
Total no. of page fault:5
1.FIFO
2.LRU
3.Exit
Enter your choice:3
you are exiting
Result:
Thus the java program to implement the different page replacement techniques
was created, executed successfully and the output was verified.
145
Ex.No:18
PRODUCER CONSUMER PROBLEM
Aim:
To write a java program to implement the concept of the producer consumer
problem.
Algorithm:
a)Display the menu Read the choice
1.Produce a problem
2.consume a problem
3.display
4.exit
b)if choice=1 then do
1.get the process to be proceed
2.check whether process already existing if(yes) display
3.check whether process already existing if(yes)then consume the process
4.display all the process to be consumed
i)get the process to be consumed
ii)check the process is already produced, if yes then consume.
Source code:
import java.io.*;
class semaphore
{
int s=0,z=0;
String wait[]=new String[50];
String produce[]=new String[50];
void producer()throws IOException
{
int i,j=0,check=0;
String ch=”y”;
146
do
{
DataInputStream d=new DataInputStream(System.in);
System.out.println(“nenter the process name to produce:”);
++s;
produce[s]=d.readLine();
for(i=1;i<s;i++)
{
if(produce[i].compareTo(produce[s])==0)
{
System.out.println(“nprocess already exists!!”);
--s;
break;
}
}
for(i=1;i<=z;i++)
{
if(produce[s].compareTo(wait[i])==0)
{
System.out.println(“Waiting process”);
System.out.println(produce[s]+”is now consumed”);
j=1;
--s;
check=1;
break;
}
}
if(check==1)
{
147
for(i=j;i<z;i++)
wait[i]=wait[i+1];
z--;
}
if(check==0)
{
System.out.println(“nProduced process”);
for(i=1;i<=s;i++)
System.out.println(produce[i]);
}
System.out.println(“nnDo you want to continue?”);
ch=d.readLine();
}
while(ch.equalsIgnoreCase(“y”));
}
void consumer()throws IOException
{
DataInputStream d=new DataInputStream(System.in);
String consume,ch;
int i,j=0,flag;
if(s==0)
{
System.out.println(“nNo process produced please wait”);
return;
}
System.out.println(“nnConsume a process”);
do
{
flag=0;
148
System.out.println(“nEnter the consume process”);
consume=d.readLine();
for(i=1;i<=s;i++)
{
if(produce[i].compareTo(consume)==0)
{
flag=1;
j=i;
break;
}
}
for(i=1;i<=z;i++)
{
if(wait[i].compareTo(consume)==0)
{
flag=2;
break;
}
}
if(flag==1)
{
System.out.println(“nprocess”+consume+” is now consumed”);
for(i=j;i<s;i++)
produce[i]=produce[i+1];
--s;
}
else if(flag==2)
System.out.println(“nprocess already exists”);
else
149
{
System.out.println(“nprocess”+consume+”has to be produced”);
System.out.println(“nIt has to wait”);
wait[++z]=consume;
}
if(z==0)
System.out.println(“nNo waiting process”);
else
{
System.out.println(“nWaiting process”);
for(i=1;i<=z;i++)
System.out.println(wait[i]);
}
System.out.print(“nDo you want to continue?”);
ch=d.readLine();
}
while(ch.equalsIgnoreCase(“y”));
}
void display()
{
int i;
System.out.println(“nnPRODUCED PROCESS”);
for(i=1;i<=s;i++)
System.out.println(produce[i]);
System.out.println(“nnWAITING PROCESS”);
for(i=1;i<=z;i++)
System.out.println(wait[i]);
}
}
150
class prod_cons
{
public static void main(String args[])throws IOException
{
DataInputStream d=new DataInputStream(System.in);
semaphore se=new semaphore();
int c;
do
{
System.out.println(“nnProducer--> Consumer problem”);
System.out.println(“n1.produce a process”);
System.out.println(“2.Consume a process”);
System.out.println(“3.Display”);
System.out.println(“4.Exit”);
System.out.println(“nEnter your choice:”);
c=Integer.parseInt(d.readLine());
switch(c)
{
case 1:
se.producer();
break;
case 2:
se.consumer();
break;
case 3:
se.display();
break;
case 4:
System.exit(0);
151
default:
System.out.println(“Option not valid”);
}}
while(true);
}}
Sample Input and Output:
Producer- ->Consumer problem
1.Produce a process
2.Consume a process
3.Display
4.Exit
Enter your choice:1
Enter the process name to produce:
P1
Produced process
P1
Do you want to continue?Y
Enter the process name to produce:
P2
Produced process
P1
P2
Do you want to continue?N
Producer- ->Consumer problem
1.Produce a process
2.Consume a process
3.Display
4.Exit
Enter your choice:2
152
Consume a process
Enter the consume process
P3
Process P3 has to be produced
It has to wait
Waiting process
P3
Do you want to continue?N
Producer- ->Consumer problem
1.Produce a process
2.Consume a process
3.Display
4.Exit
Enter your choice:3
PRODUCED PROCESS
P1
P2
WAITING PROCESS
P3
Producer- ->Consumer problem
1.Produce a process
2.Consume a process
3.Display
4.Exit
Enter your choice:4
Result:
Thus the java program to implement the producer consumer problem was created,
executed successfully and the output was verified.
153
Ex.No:19
BANKERS ALGORITHM
Aim:
To write a java program to implement Bankers Algorithm
Algorithm:
1.If request be the array of process p
2.If request [i]=k then process p wants k instance of resource type R
3.when a request for resources is made by process p then following action are taken
i)if request<=available go to step 3
ii)the system pretend to have allocated the request resource to p
Available=Available-request
Allocation=Allocation+ request
Need=Need-request
Source code:
import java.lang.*;
import java.io.*;
public static void main(String args[])
{
BankSub BS=new BankSub();
try
{
BS.mainFun();
}
catch(Exception E)
{
System.out.println(“Exception caught from main”);
}
}
}
154
class BankSub
{
int alloc[][],max[],need[][],ne[][],al[][],interavail[][];
int finish[],avail[],requ[],work[],order[];
int pre,av[];
int n,j,i,f,ch,inc,a,r,flag;
char c;
public BankSub()
{
alloc=new int[10][10];
max=new int[10][10];
need=new int[10][10];
ne=new int[10][10];
al=new int[10][10];
interavail=new int[10][10];
finish=new int[10];
avail=new int[10];
requ=new int[10];
work=new int[10];
order=new int[10];
pre=0;
av=new int[10];
inc=0;
}
public void mainFun()throws IOException
{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
155
System.out.print(“nnHow many process to be entered:”);
n=Integer.parseInt(br.readLine());
System.out.print(“nEnter Number of resources:”);
r=Integer.parseInt(br.readLine());
System.out.println(“nEnter the allocated value for each process:”);
for(i=0;i<n;i++)
{
System.out.println(“P”+(i+1)+”-->”);
for(j=0;j<r;j++)
{
alloc[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println(“nEnter maximum value for each process:”);
for(i=0;i<n;i++)
{
System.out.println(“P”+(i+1)+”-->”);
for(j=0;j<r;j++)
{
max[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println(“nEnter available value:”);
System.out.prin(“n”);
for(i=0;i<r;i++)
{
System.out.println(“Resource”+(i+1)+”-->”);
avail[i]=Integer.parseInt(br.readLine());
}
156
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
need[i][j]=max[i][j]-alloc[i][j];
}
}
do
{
System.out.print(“nnn1.Safety algorithmn2.Resource Request
algorithmn3.ExitnnEnter your choice:”);
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
safety();
break;
case 2:
try
{
resources();
}
catch(IOException e) {}
break;
case 3:
System.exit(0);
}
}while(ch<+3);
}
157
catch(IOException e)
{
System.out.println(“Number format invalid”);
}
}
void safety()
{
int con[]=new int[10];
a=0;
inc=0;
for(i=0;i<n;i++)
finish[i]=0;
for(i=0;i<r;i++)
work[i]=avail[i];
do
{
for(i=0;i<n;i++)
{
con[i]=check();
if(finish[i]==0&&con[i]==1)
{
for(j=0;j<r;j++)
{
work[j]=work[j]+alloc[i][j];
}
finish[i]=1;
order[a]=i+1;
a++;
/*for(j=0;j<r;j++)
158
{
interavail[i][j]=work[j]
}*/
}
}
inc++;
}while(inc!=2);
f=0;
for(i=0;i<n;i++)
{
if(finish[i]==00
f=1;
}
if(f==0)
{
System.out.println(“nnntThe system in safe state:”);
System.out.println(“nThe safe sequence:”);
for(i=0;i<a;i++)
System.out.print(order[i]+” “);
}
else
{
System.out.prntln(“nnntThe system in unsafe state:”);
pre=1;
}
System.out.println();
summerize();
System.out.println();
}
159
void summerize()
{
System.out.println(“nnSummerizing..”);
System.out.println(“nMax valuetAllocated valuetNeeded valuetRemaining
available”);
System.out.println(“nt”);
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
System.out.println(max[i][j]+” “);
System.out.print(“t”);
for(j=0;j<r;j++)
System.out.println(alloc[i][j]+” “);
System.out.print(“t”);
for(j=0;j<r;j++)
System.out.println(need[i][j]+” “);
System.out.print(“t”);
for(j=0;j<r;j++)
System.out.println(interavail[i][j]+” “);
System.out.println();
}
System.out.print(“The available resource:”);
for(i=0;i<r;i++)
System.out.print(avail[i]+” “);
}
int check()
{
int f=1,flag=1;
for(j=0;j<r;j++)
160
{
if(need[i][j]<=work[j])
f=1;
else
f=0;
flag=flag*f;
}
return flag;
}
void resource()throws IOException
{
try
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int pno,f=1,var=1,flag;
while(var!=0)
{
System.out.print(“nEnter the process no1)-->”+n+”:”);
pno=Integr.parseInt(b.readLine());
if(pno<=n&&pno!=0)
{
pno--;
System.out.print(“nEnter the current request for this process:”);
for(i=0;i<r;i++)
requ[i]=Integer.parseInt(b.readLine());
for(flag=1,i=0;i<r;i++)
{
if(requ[i]<=need[pno][i])
{
161
flag=1;
}
else
{
flag=0;
}
//flag=flag*f;
}
System.out.println();
for(i=0;i<r;i++)
{
if(flag!=0)
{
if(requ[i]<=avail[i])
{
al[pno][i]=alloc[pno][i];
ne[pno][i]=need[pno][i];
av[i]=avail[i];
alloc[pno][i]=alloc[pno][i]+requ[i];
need[pno][i]=need[pno][i]-requ[i];
avail[i]=avail[i]-requ[i];
}
else
{
System.out.println(“nThe process has to wait”);
f=0;
System.out.println();
break;
}
162
}
else
{
System.out.println(“nERROR”);
f=0;
System.out.println(“nSince proceaa requires more than what it had already asked”);
break;
}
}
if(f!=0)
{
summerize();
if(pre!=0)
{
alloc[pno][i]=al[pno][i];
need[pno][i]=ne[pno][i];
avail[i]=av[i];
pre=0;
}
}
var=0;
}
else
{
continue;
}
}
}
catch(IOException e)
163
{}
}
}
Sample Input and Output:
How many process to be entered:5
Enter number of resources:4
Enter the allocated value for each process:
P1-->
0
0
1
2
P2-->
1
0
0
0
P3-->
1
3
5
4
P4-->
0
0
1
4
P5-->
0
164
6
3
2
Enter maximum value for each process:
P1-->
0
0
1
2
P2-->
1
7
5
0
P3-->
2
3
5
6
P4-->
0
6
5
6
P5-->
0
6
5
2
165
Enter available value:
Resource1-->1
Resource2-->5
Resource3-->2
Resource4-->0
1.Safety Algorithm
2.Resource request algorithm
3.Exit
Enter your choice:1
The system in safe state.
The Safe sequence:
1 3 4 5 2
Summerizing..
Max value Allocated value Needed value Remaining Available
0 0 1 2 0 0 1 2 0 0 0 0 1 5 3 2
1 7 5 0 1 0 0 0 0 7 5 0 3 14 12 12
2 3 5 6 1 3 5 4 1 0 0 2 2 8 8 6
0 6 5 6 0 0 1 4 0 6 4 2 2 8 9 10
0 6 5 2 0 6 3 2 0 0 2 0 2 14 12 12
The available resource:1 5 2 0
1.Safety Algorithm
2.Resource request algorithm
3.Exit
Enter your choice:2
Enter the process no 1)-->5:2
Enter the current request for this process:0
4
2
0
166
Summerizing..
Max value Allocated value Needed value Remaining Available
0 0 1 2 0 0 1 2 0 0 0 0 1 1 1 2
1 7 5 0 1 4 2 0 0 3 3 0 3 14 12 12
2 3 5 6 1 3 5 4 1 0 0 2 2 4 6 6
0 6 5 6 0 0 1 4 0 6 4 2 2 10 10 10
0 6 5 2 0 6 3 2 0 0 2 0 2 10 9 8
The available resource:1 1 0 0
1.Safety Algorithm
2.Resource request algorithm
3.Exit
Enter your choice:3
Result:
Thus the java program to implement the Bankers Algorithm was created, executed
successfully and the output was verified.
167
Ex.No:20
DINING PHILOSOPHER PROBLEM
Aim:
To write a java program to implement the concept of the Dining Philosopher
problem.
Algorithm:
1.Get the total number of philosopher
2.get the number of philosopher who are hungry
3.if all are hungry then deadlock occurs
4.get the philosopher position
5.display the menu
6.Two can eat at a time
7.one can eat at a time
8.if choice is one,then
a)get the philosopher states of eating position
b)display the means of those who are waiting.
Source code:
import java.io.*;
import.java.math.*;
public class DinPhilo
{
public static void main(String args[])
{
DinPhilosopher OB;
OB=new DinPhilosopher();
try
{
OB.mainFun();
}
168
catch(IOException e)
{
System.out.println(“Exception caught from main.”);
}
}
}
class DinPhilosopher
{
String[] philname;
char op,conf=’Y’;
int status[],hu[],pos,cho,x,i,j,r,t,tph,howhung,s;
public DinPhilosopher()
{
philname=new String[20];
status=new int[20];
hu=new int[20];
s=0;
}
void one()
{
pos=0;
System.out.println(“nALLOW ONE PHILOSOPHER TO EAT AT ANY TIMEn”);
for(i=0;i<howhung;i++,pos++)
{
System.out.println(“tPHILOSOPHER<”+philname[hu[pos]]+”>IS GRANTED TO
EAT”);
for(x=pos;x<howhung;x++)
System.out.println(“tPHILOSOPHER<”+philname[hu[x]]+”>IS WAITING”);
}
169
}
void two()
{
System.out.println(“nTWO PHILOSOPHER TO EAT AT SAME TIMEn”);
for(i=0;i<howhung;i++)
{
for(j=i+1;j<howhung;j++)
{
if(Math.abs(hu[i]-hu[j])>=1&&Math.abs(hu[i]-hu[j])!=4)
{
System.out.println(“nnCOMBINATION”+(s+1)+”n”);
t=hu[i];
r=hu[j];
s++;
System.out.println(“<”+philname[hu[i]]+”>AND<”+philname[hu[j]]+”>ARE
GRANTED TO EAT”);
for(x=0;x<howhung;x++)
{
if((hu[x]!=t)&&(hu[x]!=r))
System.out.println(“PHILOSOPHER<”+philname[hu[x]]+”>IS WAITING”);
}
}
}
}
}
void menu()throws IOException
{
try
{
170
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
do(
System.out.println(“nnDINING PHILOSOPHER PROBLEM”);
System.out.print(“n1.One can eat at a timen2.Two can eat at a timen3.ExitnnEnter
your choice:”);
cho=Integer.parseInt(br.readLine());
switch(cho)
{
case 1:one();
break;
case 2:two();
break;
case 3:System.exit(0);
default:System.out.println(“nInvalid option..”);
}
System.out.print(“nContinue with main menu(Y/N):”);
conf=(char)br.read();
br.readLine();
}while(conf==’Y’||conf==’y’);
}
catch(IOException e)
{
System.out.println(“IOException handled”);
}
}
public void mainFun()throws IOException
{
try
{
171
BufferReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“nnDINING PHILOSOPHER PROBLEM”);
System.out.println(“nENTER THE TOTAL PHILOSOPHER:”);
tph=Integer.parseInt(br.readLine());
System.out.print(“n”);
for(i=0;i<tph;i++)
{
System.out.print(“PHILOSOPHER”+(i+1)+”:”);
philname[i]=br.readLine();
status[i]=1;
}
System.out.print(“nnHow many are hungry:”);
howhung=Integer.parseInt(br.readLine());
if(howhung==tph)
{
System.out.print(“nDO YOU WANT ALL PHILOSOPHER EAT AT A TIME:”);
op=(char)br.readLine();
if(op==’y’||op==’Y’)
{
System.out.println(“nAll are hungry..nDead lock stage will occur”);
System.out.println(“nExiting..”);
}
}
else
{
System.out.print(“n”);
for(i=0;i<howhung;i++)
{
System.out.print(“ENTER PHILOSOPHER”+(i+1)+”POSITION:”);
172
hu[i]=Integer.parseInt(br.readLine());
status[hu[i]]=2;
}
menu();
}
}
catch(IOException ex)
{
System.out.println(“nException caught from mainfun method”);
}
}
}
Sample Input and Output:
DINING PHILOSOPHER PROBLEM
ENTER THE TOTAL PHILOSOPHER:5
PHILOSOPHER 1:a
PHILOSOPHER 2:b
PHILOSOPHER 3:c
PHILOSOPHER 4:d
PHILOSOPHER 5:e
How many are hungry:3
ENTER PHILOSOPHER 1 POSITION:2
ENTER PHILOSOPHER 2 POSITION:4
ENTER PHILOSOPHER 3 POSITION:5
DINING PHILOSOPHER PROBLEM
1.One can eat at a time
2.Two can eat at a time
3.Exit
Enter your choice:1
173
ALLOW ONE PHILOSOPHER TO EAT AT ANY TIME
PHILOSOPHER<c>IS GRANTED TO EAT
PHILOSOPHER<e>IS WAITING
PHILOSOPHER<null>IS WAITING
PHILOSOPHER<e>IS GRANTED TO EAT
PHILOSOPHER<null>IS WAITING
PHILOSOPHER<null>IS GRANTED TO EAT
Continue with main menu(Y/N):Y
DINING PHILOSOPHER PROBLEM
1.One can eat at a time
2.Two can eat at a time
3.Exit
Enter your choice:2
TWO PHILOSOPHER TO EAT AT SAME TIME
COMBINATION 1
<c>AND<e>ARE GRANTED TO EAT
PHILOSOPHER<null>IS WAITING
COMBINATION 2
<c>AND<null>ARE GRANTED TO EAT
PHILOSOPHER<e>IS WAITING
COMBINATION 3
<e>AND<null>ARE GRANTED TO EAT
PHILOSOPHER<c>IS WAITING.
Continue with main menu(Y/N):Y
DINING PHILOSOPHER PROBLEM
1.One can eat at a time
2.Two can eat at a time
3.Exit
Enter your choice:3
174
Result:
Thus the java program to implement the Dining philosopher problem was created,
executed successfully and the output was verified

More Related Content

What's hot

Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in javaGoogle
 
Asp.NET Validation controls
Asp.NET Validation controlsAsp.NET Validation controls
Asp.NET Validation controlsGuddu gupta
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdmHarshal Misalkar
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
Object oriented programming c++
Object oriented programming c++Object oriented programming c++
Object oriented programming c++Ankur Pandey
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdfNehaSpillai1
 
basic of desicion control statement in python
basic of  desicion control statement in pythonbasic of  desicion control statement in python
basic of desicion control statement in pythonnitamhaske
 
Validation Controls in asp.net
Validation Controls in asp.netValidation Controls in asp.net
Validation Controls in asp.netDeep Patel
 
Java: Java Applets
Java: Java AppletsJava: Java Applets
Java: Java AppletsTareq Hasan
 

What's hot (20)

Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
C# Lab Programs.pdf
C# Lab Programs.pdfC# Lab Programs.pdf
C# Lab Programs.pdf
 
Java program structure
Java program structureJava program structure
Java program structure
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Asp.NET Validation controls
Asp.NET Validation controlsAsp.NET Validation controls
Asp.NET Validation controls
 
Inheritance C#
Inheritance C#Inheritance C#
Inheritance C#
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
 
Encapsulation C++
Encapsulation C++Encapsulation C++
Encapsulation C++
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java swing
Java swingJava swing
Java swing
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Object oriented programming c++
Object oriented programming c++Object oriented programming c++
Object oriented programming c++
 
Python-DataAbstarction.pptx
Python-DataAbstarction.pptxPython-DataAbstarction.pptx
Python-DataAbstarction.pptx
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
basic of desicion control statement in python
basic of  desicion control statement in pythonbasic of  desicion control statement in python
basic of desicion control statement in python
 
Validation Controls in asp.net
Validation Controls in asp.netValidation Controls in asp.net
Validation Controls in asp.net
 
Generics
GenericsGenerics
Generics
 
Java: Java Applets
Java: Java AppletsJava: Java Applets
Java: Java Applets
 

Viewers also liked

Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments rajni kaushal
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarROHIT JAISWAR
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
WAP to store 10 numbers in an array and find out the largest and the smallest...
WAP to store 10 numbers in an array and find out the largest and the smallest...WAP to store 10 numbers in an array and find out the largest and the smallest...
WAP to store 10 numbers in an array and find out the largest and the smallest...One97 Communications Limited
 
Webdesing lab part-b__java_script_
Webdesing lab part-b__java_script_Webdesing lab part-b__java_script_
Webdesing lab part-b__java_script_Shivanand Algundi
 
Google Drive Split Page Tutorial
Google Drive Split Page TutorialGoogle Drive Split Page Tutorial
Google Drive Split Page TutorialMeredith Martin
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALPrabhu D
 
Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1javatrainingonline
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - PraticalsFahad Shaikh
 
Java Regular Expression PART I
Java Regular Expression PART IJava Regular Expression PART I
Java Regular Expression PART IOXUS 20
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesOXUS 20
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART IIOXUS 20
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesOXUS 20
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and GraphicsOXUS 20
 

Viewers also liked (20)

Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
Java lab 2
Java lab 2Java lab 2
Java lab 2
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
All experiment of java
All experiment of javaAll experiment of java
All experiment of java
 
WAP to store 10 numbers in an array and find out the largest and the smallest...
WAP to store 10 numbers in an array and find out the largest and the smallest...WAP to store 10 numbers in an array and find out the largest and the smallest...
WAP to store 10 numbers in an array and find out the largest and the smallest...
 
Webdesing lab part-b__java_script_
Webdesing lab part-b__java_script_Webdesing lab part-b__java_script_
Webdesing lab part-b__java_script_
 
Google Drive Split Page Tutorial
Google Drive Split Page TutorialGoogle Drive Split Page Tutorial
Google Drive Split Page Tutorial
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
 
Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
 
Java Regular Expression PART I
Java Regular Expression PART IJava Regular Expression PART I
Java Regular Expression PART I
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI Examples
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART II
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 

Similar to Java programming lab manual (20)

Java final lab
Java final labJava final lab
Java final lab
 
Java practical
Java practicalJava practical
Java practical
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Review Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdfReview Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdf
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
 
5 Rmi Print
5  Rmi Print5  Rmi Print
5 Rmi Print
 
Java file
Java fileJava file
Java file
 
Java file
Java fileJava file
Java file
 
srgoc
srgocsrgoc
srgoc
 
Java Practical File Diploma
Java Practical File DiplomaJava Practical File Diploma
Java Practical File Diploma
 
3.Lesson Plan - Input.pdf.pdf
3.Lesson Plan - Input.pdf.pdf3.Lesson Plan - Input.pdf.pdf
3.Lesson Plan - Input.pdf.pdf
 
Java Unit 1 Project
Java Unit 1 ProjectJava Unit 1 Project
Java Unit 1 Project
 
Java programs
Java programsJava programs
Java programs
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
programming for Calculator in java
programming for Calculator in javaprogramming for Calculator in java
programming for Calculator in java
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
JAVA Question : Programming Assignment
JAVA Question : Programming AssignmentJAVA Question : Programming Assignment
JAVA Question : Programming Assignment
 

More from sameer farooq

Can a firewall alone effectively block port scanning activity
Can a firewall alone effectively block port scanning activityCan a firewall alone effectively block port scanning activity
Can a firewall alone effectively block port scanning activitysameer farooq
 
Virtual Circuit Switching: Frame Relay and ATM
Virtual Circuit Switching:Frame Relayand ATMVirtual Circuit Switching:Frame Relayand ATM
Virtual Circuit Switching: Frame Relay and ATMsameer farooq
 
Data structure manual
Data structure manualData structure manual
Data structure manualsameer farooq
 
Software Project management
Software Project managementSoftware Project management
Software Project managementsameer farooq
 
Radio Frequency Waves ,Data communication & Networks
Radio Frequency Waves ,Data communication & NetworksRadio Frequency Waves ,Data communication & Networks
Radio Frequency Waves ,Data communication & Networkssameer farooq
 

More from sameer farooq (8)

Idps book
Idps bookIdps book
Idps book
 
Can a firewall alone effectively block port scanning activity
Can a firewall alone effectively block port scanning activityCan a firewall alone effectively block port scanning activity
Can a firewall alone effectively block port scanning activity
 
Windows firewall
 Windows firewall  Windows firewall
Windows firewall
 
Virtual Circuit Switching: Frame Relay and ATM
Virtual Circuit Switching:Frame Relayand ATMVirtual Circuit Switching:Frame Relayand ATM
Virtual Circuit Switching: Frame Relay and ATM
 
Data structure manual
Data structure manualData structure manual
Data structure manual
 
Software Project management
Software Project managementSoftware Project management
Software Project management
 
kerberos
kerberoskerberos
kerberos
 
Radio Frequency Waves ,Data communication & Networks
Radio Frequency Waves ,Data communication & NetworksRadio Frequency Waves ,Data communication & Networks
Radio Frequency Waves ,Data communication & Networks
 

Recently uploaded

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 

Recently uploaded (20)

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 

Java programming lab manual

  • 1. 1 DEPT OF COMPUTER SCIENCE AND ENGG B.E[INFORMATION TECHNOLOGY] V-SEMESTER 95808- OPERATING SYSTEM AND JAVA PROGRAMMING LAB MANUAL Lab Incharge Dr. P. Aruna Professor Dept of CSE
  • 2. 2 Annamalai University CYCLE-I JAVA PROGRAMMING Ex.no Name of the Exercises 1. Classes and Objects 2. Command Line Argument 3. Bitwise Operators 4. Method Overloading 5. Packages 6. Interface 7. Inheritance
  • 3. 3 8. Exception Handling 9. User Defined Exception Handling 10. Multithreading:join() and isAlive() 11. Multithreading:Inter thread communications 12. Addition of Two Numbers using Applet
  • 4. 4 CYCLE-II UNIX PROGRAMMING Ex.no Name of the Exercises 1. Job scheduling techniques 2. Disk scheduling techniques 3. Memory allocation techniques 4. Memory management techniques 5. Page replacement techniques 6. Producer consumer problem 7. Bankers algorithm 8. Dining Philosophers problem
  • 5. 5 Ex.No: 1 CLASSES AND OBJECTS Aim: To write a java program to work with the creation of objects for the class with overloaded constructor and user defined methods returning a value. Algorithm:  Start  Create an object called room.  Create an object with overloaded constructor and get length and breadth.  Create a function room where only length is passed and breadth remains constant.  Create a function getdata() to return the area.  Create another class ex1 that includes the main function.  Declare variable int l=0,b=0,float area.  Get the dynamic input using exceptional try and catch.  Pass the input values to the constructor.  Calculate the input values to the getdata().  Display the result. Source code: import java.io.*; import java.io.DataInputStream; class Room { float length,breadth; Room(int a,int b) { length=a; breadth =b; } Room(int a) {
  • 6. 6 length =a; breadth=100; } float getdata() { Return(length*breadth); } } class ex1 { public static void main(String args[]) { float area; int l=0,b=0; DataInputStream in=new DataInputStream(System.in); try { System.out.println(“n enter the value for Room length:”); l=Integer.parseInt(in.readLine()); System.out.println(“n enter the value for Room breadth:”); b=Integer.parseInt(in.readLine()); } Catch(Exception e) {} Room room1=new Room(l,b); area=room1.getdata(); System.out.println(“n length=”+room1.length); System.out.println(“n breadth=”+room1.breadth); System.out.println(“n Area=”+area);
  • 7. 7 System.out.println(“n passing only length of the room with breadth=100”); Room room2=new Room(l); area =room2,getdata(); System.out.println(“n length=”+room2.length); System.out.println(“n breadth=”+room2.breadth); System.out.println(“n Area=”+area); } } Sample input and output: Enter the value for Room length:100 Enter the value for Room breadth:200 Length =100.0 Breadth=200.0 Area=20000.0 Passing only length of the room with breadth=100 Length=100.0 Breadth=100.0 Area=10000.0 Result: Thus the java program was executed successfully and the output was verified.
  • 8. 8 ExNo: 2 COMMAND LINE ARGUMENT Aim: To write a java program to get and sort names by command line argument. Algorithm:  Create a class name ex2 and declare the variables int n and string s[]  Allocate the memory of names for variable s.  Get total number of names to be entered in the variable n.  Using compareTo function sort the names in alphabetical order.  Use forloop to sort the name.  Print the sorted name list. Source code: import java.io.*; import java.lang.*; public static void main(String args[])throws IOException { String t; int n=args.length; int i,j; System.out.println(“n you have entered”+n+”names to sort it in ascendingorder”); for(i=0;i<n-1;i++) { for(j=i+1;j<n;j++) { if(args[i].compareTo(args[j])>0) { t=args[i]; args[i]=args[j]; args[j]=t;
  • 9. 9 } } } System.out.println(“n sorted name list is…n); for (i=0;i<n;i++) { System.out.println(args[i]); } } } Sample input and output: E:>java ex2 one two three four five six seven eight nine ten eleven twelve You have entered 12 names to sort it in ascending order Sorted name list is… Eight Eleven Five Four Nine One Seven Six Ten Three Twelve two Result: Thus the java program was executed successfully and the output was verified
  • 10. 10 ExNo: 3 BITWISE OPERATOR Aim: To write a java program to understand the concept of functionalities of different Bitwise operators. Algorithm:  Create a class called ex3.  Use DataInputStream to get stream of data.  Display the menu and get choice from the user.  Now,call the appropriate care.  Display the output. Source code: import java.io.*; public class ex3 { public static void main(String args[])throws IOException { DataInputStream d=new DataInputStream(System.in); System.out.println(“n enter value for x:”); int x=Integer.parseInt(d.readLine()); System.out.println(“n enter value for y:”); int y= Integer.parseInt(d.readLine()); int c; do { System.out.println(“n BITWISE OPERATORn”); System.out.println(“1.AND”); System.out.println(“2.OR”); System.out.println(“3.XOR”);
  • 11. 11 System.out.println(“ 4.LEFT SHIFT”); System.out.println(“ 5.RIGHT SHIFT”); System.out.println(“ 6.NOT”); System.out.println(“ 7.EXITn”); System.out.println(“ n enter your choice:”); c=Integer.parseInt(d.readLine()); switch(c) { case 1: System.out.println(“AND OPERATION:”+(x+y)); break; case 2: System.out.println(“OR OPERATION:”+(x|y)); break; case 3: System.out.println(“XOR OPERATION:”+(x^y)); break; case 4: System.out.println(“LEFT SHIFT:”+(x<<y)); break; case 5: System.out.println(“RIGHT SHIFT:”+(x>>y)); break; case 6: System.out.println(“NOT of x :”+(~x)); System.out.println(“NOT of y :”+(~y)); break; case 7: System.exit(1);
  • 12. 12 break; default: System.out.println(“n enter only 1 to 7”); break; } }while(c!=7); } } Sample input and output: Enter value for x:10 Enter value for y:6 BITWISE OPERATOR 1.AND 2.OR 3.XOR 4.LEFT SHIFT 5.RIGHT SHIFT 6.NOT 7.EXIT Enter your choice:1 AND OPERATION:2 BITWISE OPERATOR 1.AND 2.OR 3.XOR 4.LEFT SHIFT 5.RIGHT SHIFT 6.NOT 7.EXIT
  • 13. 13 Enter your choice:2 OR OPERATION:14 BITWISE OPERATOR 1.AND 2.OR 3.XOR 4.LEFT SHIFT 5.RIGHT SHIFT 6.NOT 7.EXIT Enter your choice:3 XOR OPERATION:12 BITWISE OPERATOR 1.AND 2.OR 3.XOR 4.LEFT SHIFT 5.RIGHT SHIFT 6.NOT 7.EXIT Enter your choice:4 LEFT SHIFT OPERATION:640 BITWISE OPERATOR 1.AND 2.OR 3.XOR 4.LEFT SHIFT 5.RIGHT SHIFT 6.NOT
  • 14. 14 7.EXIT Enter your choice:5 RIGHT SHIFT OPERATION:0 BITWISE OPERATOR 1.AND 2.OR 3.XOR 4.LEFT SHIFT 5.RIGHT SHIFT 6.NOT 7.EXIT Enter your choice:6 NOT of x :-11 NOT of y :-7 BITWISE OPERATOR 1.AND 2.OR 3.XOR 4.LEFT SHIFT 5.RIGHT SHIFT 6.NOT 7.EXIT Enter your choice:7 Result: Thus,the java program has been written to understand the concept of functionalities of different bitwise operators and output were verified.
  • 15. 15 ExNo: 4 METHOD OVERRIDING Aim: To write a java program to understand the concept of Method Overriding. Algorithm:  Create a base class “vehicle” and declare the variable reg_no as string and model as integer.  Create a function read()inside the class to read data for the variables.  Create a derived class”two-wheeler” and declare the variable no_gear,power as integer.  Create another deriver class”scooter” and declare variable manufacturer,owner as string.  Create a function read()to get the data for no_gear.  Create another function print that prints the values of the reg_no,model,power,no_gear Source code: import java.io.*; class vehicle { String reg_no; int model; void read()throws IOException { DataInputStream d=new DataInputStream(System.in); System.out.println(“n enter reg_no and model :”); reg_no=d.readLine(); model=Integer.parseInt(d.readLine()); } } class two-wheeler extends vehicle
  • 16. 16 { int no_gear,power; void read()throws IOException { super.read(); DataInputStream d=new DataInputStream(System.in); System.out.println(“n enter no_gear and power :”); no_gear=Integer.parseInt(d.readLine()); power= Integer.parseInt(d.readLine()); } } class scooter extends two-wheeler { String manufacturer,owner; void read()throws IOException { super.read(); DataInputStream d=new DataInputStream(System.in); System.out.println(“n enter manufacturer and owner :”); manufacturer=d.readLine(); owner= d.readLine(); } void print() { System.out.println(“n”); System.out.println(“n Reg_no :”+reg_no); System.out.println(“n Model :”+model); System.out.println(“n No_gear :”+no_gear); System.out.println(“n Power :”+power);
  • 17. 17 System.out.println(“n Manufacturer :”+manufacturer); System.out.println(“n Owner :”+owner); } } class overriding { public static void main(String args[])throws IOException { scooter s=new scooter(); s.read(); s.print(); } } Sample input and output: Enter reg_no and model:TN31AD1224 2010 Enter no_gear and power:5 798 Enter manufacturer and owner : Maruthi Sauresh.A Reg_no : TN31AD1224 Model : 2010 No_gear : 5 Power : 798 Manufacturer : Maruthi Owner : Sauresh.A Result: Thus, the java program has been written to understand the concept of Method Overriding and output was verified.
  • 18. 18 ExNo: 5 PACKAGES Aim: To write a java program to understand the steps in the creation of packages. Algorithm:  Include the package complex.  Create a class arith and declare rp,ip as integer.  Define the function arith(),set rp and ip to 0  Another function arith(int rp,int ip) set this.rp=rp and this.ip=ip.  Create a function add() pass arguments with arith a1 and arith a2.  Add a1.rp and a2.rp store in rp.  Similarly add a1.ip and a2.ip and store in ip.  Create a function sub(arith a1,arith a2)  Subtract a1.rp and a2.rp store it in rp  Subtract a1.ip and a2.ip store it in ip Source code: Package creation code: package pkg; public class arith { public int rp,ip; public arith() { rp=0; ip=0; } public arith(int rp,in rip) { this.rp=rp; this.ip=ip;
  • 19. 19 } public void add(arith a1,arith a2) { rp=a1.rp + a2.rp; ip=a1.ip +a2.ip; } public void sub (arith a1,arith a2) { rp=a1.rp - a2.rp; ip=a1.ip -a2.ip; } } Main code: import pkg.arith; import java.io.*; class package1 { public static void main(String args[])throws IOException { int rp,ip; DataInputStream d=new DataInputStream(System.in); System.out.println(“n enter real part and imaginary part of 1st complex no :”); rp=Integer.parseInt(d.readLine()); ip= Integer.parseInt(d.readLine()); arith a1=new arith(rp,ip); System.out.println(“n enter real part and imaginary part of 2nd complex no :”); rp=Integer.parseInt(d.readLine()); ip= Integer.parseInt(d.readLine()); arith a2=new arith(rp,ip);
  • 20. 20 arith a3=new arith(); System.out.println(“n a1=”+a1.rp+ “+” +a1.ip+ “i”); System.out.println(“n a2=”+a2.rp+ “+” +a2.ip+ “i”); a3.add(a1,a2); System.out.println(“n Added value:” +a3.rp+ “+” +a3.ip+ “i”); a3.sub(a1,a2); System.out.println(“n Subtacted value :” +a3.rp+ “-“ a3.ip + “i”); } } Sample input and output: Enter real part and imaginary part of 1st complex no : 10 5 Enter real part and imaginary part of 2nd complex no : 3 6 a1= 10 + 5i a2= 3 +6i Added value : 13 +11i Subtracted value : 7 – 1i Result: Thus, the java program has been written to create a package and output were verified by importing it in another program
  • 21. 21 Ex.No : 6 INTERFACE Aim: To write java program to implement the concept of interface. Algorithm:  Create a class income,declare iamount as integer.  Create a function get() to get the values for the variable.  Create a class expenditure and declare the function get1().  Create a derived class net_income that extends income and implements expenditure.  Declare variables eamount,namount as float.  Create a function print() to print the values.  Create a main class and create an object for net_income.  Now,get the values using n.print().  End. Source code: import java.io.*; class income { float iamount; void get()throws IOException { DataInputStream d=new DataInputStream(System.in); System.out.println(“n enter the income :”); iamount=Float.pareseFloat(d.readLine()); } } interface expenditure {
  • 22. 22 public void get1(); } class net_income extends income implements expenditure { float eamount,namount; public void get1() { try { DataInputStream d=new DataInputStream(System.in); System.out.println(“n enter expenditure:”); eamount=Float.parseFloat(d.readLine()); } Catch(IOException e) {} } void print() { System.out.println(“n income :” +iamount); System.out.println(“n expenditure :” +eamount); System.out.println(“n net income :” +(iamount-eamount)); } } class interface6 { public static void main(String args[])throws IOException {
  • 23. 23 net_income n=new net_income(); n.get(); n.get1(); n.print(); } } Sample input and output: Enter income : 1000 Enter expenditure : 200 Income : 1000.0 Expenditure : 200.0 Net income : 800.0 Result: Thus, the java program was created and executed successfully and the output is verified.
  • 24. 24 ExNo : 7 INHERITANCE Aim: To write a java program to handle the situation of exception multi inheritance. Algorithm:  Create a class student and declare variable rollno.  Create function getnumber() and display().  Create another class test which inherit student.  Create function display().  Create another interface sports with variable sport and function putsp().  Create variable total and function putsp(),display().  Create another class result which extends the test and sport.  Create main class inhetitance7 and which has the student as object of class result. Source code: import java.io.*; class student { int roll_no; void getnumber(int n) { roll_no=n; } void display()
  • 25. 25 { System.out.println(“n Rollno:’ +roll_no); } } class test extends student { int m1,m2; void getmarks(int p,int q) { m1=p; m2=q; } void display() { System.out.println(“n Rollno:’ +roll_no); System.out.println(“n Marks Achieved”); System.out.println(“n Mark1 :” +m1); System.out.println(“n Mark2 :” +m2); } } interface sports { float sport=6.0f;
  • 26. 26 void putsp(); } class results extends test implements sports { float total; public void putsp() { System.out.println(“n sports result =”+sport); } void display() { total=m1+m2+sport; display(); putsp(); System.out.println(“n total score =” +total); } } class inheritance7 { public static void main(String args[]) { result student1 = new results(); student1.getnumber(1256);
  • 27. 27 student1.getmarks(30,40); student1.display(); } } Sample input and output: Rollno :1256 Marks Achieved Marks1 = 30 Marks2 =40 Sports result =6.0 Total score = 76.0 Result: Thus, the java program was created and executed successfully and output is verified.
  • 28. 28 ExNo : 8 EXCEPTION HANDLING Aim: To write a java program to implement the concept of exception handling. Algorithm:  Create a class exception8  Declare the integer a,b,c inside the class.  Store length of the argument in a and get the variable for b.  Calculate c=b/a.  Print the value of a,b,c.  Declare variable d[] = new int [a-2].  End. Source code: import java.io.*; class exception8 { public static void main(String args[])throws IOException { DataInputStream din= new DataInputStream(System.in); int a,b,c; try { a=args.length; System.out.println(“n enter b value :”); b= Integer.pareseInt(din.readLine());
  • 29. 29 c=b/a; System.out.println(“n a=”+a); System.out.println(“n b=” +b); System.out.println(“n b/a =” +c); int d[] = new int[a-2]; d[42]=99; } catch(ArithmeticException e3) { System.out.println(e3); } catch(NegativeArraySizeException e2) { System.out.println(e2); } catch(ArrayIndexOutOfBoundsException e1) { System.out.println(e1); } catch(NumberFormatException e) { System.out.println(e); }
  • 30. 30 Sample input and output: C:>java exception8 Enter b value: 1 java.lang. ArithmeticException:/by zero C:>java exception8 3 Enter b value: 4 a = 1 b = 4 b/a = 4 java.lang. NegativeArraySizeException C:>java exception8 3 5 Enter b value: 5 a = 2 b = 5 b/a =2 java.lang. ArrayIndexOutOfBoundsException: 42 C:>java exception8 3 5 Enter b value: t java.lang. NumberFormatException: for input string : “t”. Result: Thus, the java program was created and executed successfully and output is verified.
  • 31. 31 ExNo : 9 USER DEFINED EXCEPTION HANDLING Aim: To write a java program to implement the concept of user defined exception. Algorithm:  Create a class myexception that extends exception ,create variable and function to read and return a message.  Create another class exception , create variable eno ,ename ,job ,count ,as static int and string.  Create a function display() to display the employee details.  The main function call the get() and display() function to red and print the values. Source code: import java.io.*; import java.lang.*; class MyException extends Exception { String msg; public MyException(String message) { msg = message; } public StringtoString() { return msg;
  • 32. 32 } } class exception9 { static int eno[] = new int[]; static String ename[] = new String[3]; static String job[] = new String[3]; static int sal[] =new int[3]; static int count = 0; static void get()throws IOException { int i; DataInputStream d = new DataInputStream(System.in); try { for(i=count;i<3;i++) { System.out.println(“n enter “ +(i+1)+” employee detail :”); System.out.println(“n enter employee no and name :”); eno[i] = Integer.parseInt(d.readLine()); if(eno[i]<=0) throw new MyEception(“ enter valid number”); ename[i] = d.readLine();
  • 33. 33 System.out.println(“n enter job and salary :”); job[i] = d.readLine(); sal[i] = Integer.parseInt(d.readLine()); if(sal[i]<0) throw new MyEception(“ enter valid salary”); count++; } } catch(MyException e) { System.out.println(“ Exception caught :” +e); get(); } } static void disp() { for(int i=0;i<3;i++) { System.out.println(eno[i]+ “tt” +ename[i]+ “tt” +job[i]+ “tt”+ sal[i]); } } public static void main(String args[])throws IOException {
  • 34. 34 get(); System.out.println(“n ENOtt ENAMEtt JOBtt SALARYn”); disp(); } } Sample input and output: Enter 1 employee details: Enter employee no and name : -5554 Exception caught : enter valid number Enter 1 employee detail : Enter employee no and name : 3001 R.Haricharan Enter job and salary : lecturer 25000 Enter 2 employee detail : Enter employee no and name : 5001 S.Kalaiselvan Enter job and salary : reader 20000 Enter 3 employee detail : Enter employee no and name : 7801 S.Rajadurai Enter job and salary : director 23000
  • 35. 35 ENO ENAME JOB SALARY 3001 R.Haricharan lecturer 25000 5001 S.Kaliselvan reader 20000 7801 S.Rajadurai director 23000 Result: Thus, the java program was created and executed successfully and output is verified.
  • 36. 36 ExNo : 10 MULTI THREADING – join() and isAlive() Aim: To create a java program in a multithread environment and implement join() and isAlive() functions. Algorithm:  Create a class table that is derived from Thread.  Declare name as string.  Create a constructor table , pass thread name.  Call super(threadname) , start() , start the thread.  Create a function run() , print the multiples of 5.  Create another class fseries that extends thread.  Declare name as string and t1,t2,t3 as int and set f1=-1,f2=1.  Create a constructor fseries pass thread name call super thread name()  In the run() function display the Fibonacci series.  Create a class multi in the main function , create object f for table.  f.join() waits for thread to find  create object f for fseries and do f.join(). Source code: import java.io.*; class table extends Thread { String name; table(String threadname) { super(threadname);
  • 37. 37 name = threadname; System.out.println(“n New thread :’ +this); start(); } public void run() { System.out.println(“n Five Table”); for(int i=0;i<=10;i++) { System.out.println(“n i+ “*5=” +(i*5)); } } } class fseries extends Thread { String name; int f1 = -1 , f2 = 1 , f3; fseries(String threadname) { super(threadname); name = threadname; System.out.println(“n New thread :” + this); start();
  • 38. 38 } public void run() { System.out.println(“n Fibonacci Series”); for(int i= 1;i<=5 ;i++) { f3 = f1 +f2; f1 = f2; f2 = f3; System.out.println( f3); } } } class multi { public static void main(String args[]) { try { table t= new table(“Five Table”); System.out.println(“n First thread is alive :’ +t.isAlive()); t.join(); System.out.println(“n First thread is alive :’ +t.isAlive());
  • 39. 39 fseries f = new fseries(“Fibonacci Series”); System.out.println(“n Second thread is alive :” +f.isAlive()); } catch(InterruptedException e) { System.out.println(“n Main thread is interrupted”); } System.out.println(“n Main thread is exiting”); } } Sample input and output: New thread : Thread[Five Table , 5, main] First thread is alive : true Five Table 1*5=5 2*5=10 3*5=15 4*5=20 5*5=25 6*5=30 7*5=35 8*5=40 9*5=45
  • 40. 40 10*5=50 First thread is alive : false New thread [Fibonacci Series , 5, main] Fibonacci series Second thread is alive : true 0 1 1 2 3 Second thread is alive : false Main thread is exiting. Result: Thus, the java program was created and executed successfully and output is verified.
  • 41. 41 ExNo : 11 MULTI THREADING : INTER-THREAD COMMUNICATON Aim: To write a java program to implement the concept of inter-thread communication. Algorithm:  creating a class q and declare variable n as int and declare value set(Boolean) as false.  Create synchronized method in get().  Create another synchronized method void put(int n).  If (value set) then go to try and catch . inside catch call notify() this tells produces that it away put more about in the queue.  Create a class producer , that implements runnable.  Create object q. create a constructor producer where object is passed.  Create a function run() , initialize and declare i= 0.  Create a class consumer that implements runnable.  Create constructor consumer , pass the object and create a function run().  Create a class multi2 inside the main function and create object q. Source code: import java.io.*; class consumer implements Runnable { Stock c; Thread t; Consumer(Stock c) { this.c=c;
  • 42. 42 t = new Thread(this , “producer thread”); t.start(); } public void run() { while(true) { try { t.sleep(750); } catch(InterrupedException e) {} c.getstock((int) (Math.random() * 100); } } void stop() { t.stop(); } } class producer implements Runnable {
  • 43. 43 Stock s; Thread t; producer(Stock s) { this.s=s; t= new Thread(this , “producer thread”); t.start(); } public void run() { while(true) { try { t.sleep(750); } catch(InterrupedException e) {} c.getstock((int) (Math.random() * 100); } } void stop() {
  • 44. 44 t.stop(); } } class stock { int goods = 0; public synchronized void addstock(int i) { goods = goods +i ; System.out.println(“n stock added :” +i); System.out.println(“n present stock :’ +goods); notify(); } public synchronized int getstock(int j) { while(true) { if(goods>=j) { goods = goods-j; System.out.println(“n stock taken away :” +j); System.out.println(“n present stock :” +goods); break;
  • 45. 45 } else { System.out.println(“n stock not enough…”); System.out.println(“n waiting for stock to come..”); try { wait(); } catch(InterrupedException e) {} } } return goods; } public static void main(String args[]) { stock j = new stock(); producer p = new producer (j); consumer c =new consumer (j); try { Thread.sleep(20000);
  • 46. 46 p.stop(); c.stop();p.t.join();c.t.join(); System.out.println(“n Thread stopped”); } catch(InterrupedException e) {} System.exit(0); } } Sample input and output: Stock added : 58 Present stock : 58 Stock taken away : 32 Present stock : 26 Stock not enough.. Waiting for stock to come.. Stock added : 15 Present stock : 41 Stock not enough … Waiting for stock to come .. Thread stopped. Result: Thus, the java program was created and executed successfully and output is verified.
  • 47. 47 Ex.No:12 ADDITION OF TWO NUMBERS USING APPLET Aim: To write a java program to implement applet concept. Algorithm: 1. Start 2. Create a object for input stream class 3. Compile the program in java 4. Run the program using applet viewer 5. Enter the values 6. End. Source Code: import java.awt.*; import java.applet.*; public class userin extends applet { TextField text1,text2; public void init() { text1=new TextField(8); text2=new TextField(8); add(text1); add(text2);
  • 48. 48 text1.setText("0"); text2.setText("0"); } public void paint(Graphics g) { int x=0,y=0,z=0; String s1,s2,s; g.drawString("input a number in each box",10,50); try { s1=text1.getText(); x=Integer.parsseInt(s1); s2=text2.getText(); y=Integer.parseInt(s2); } catch(Exception ex) {} z=x+y; s=String.valueOf(z); g.drawString("the sum is:",10,75); g.drawString(s,100,75); } public boolean action(Event event,Object object)
  • 49. 49 { repaint(); return true; } /*<applet code="userin" width=300 height=200> </applet>*/ } Execution Method: C:j2sdk1.4.1_06bin>javac userin.java Note:userin.java uses or overrides a deprecated API Note:recpmpile with-deprecation for details C:j2sdk1.4.1_06bin>appletviewer userin.java Result: Thus the java program to add two numbers using applet was created and executed successfully and the output was verified.
  • 50. 50 Ex.No:13 JOB SCHEDULING TECHNIQUES Aim: To write a java program to implement the concept of different job scheduling techniques like, a) First Come First Served[FCFS] b) Shortest Job First[SJF] c) Round Robin d) Priority Scheduling Algorithm: a) First Come First Served: 1. Get the number by jobs to be scheduled 2. Get the arrival time and service time of each and every job 3. Get the job according time as zero for each jobs 4. Initialize the waiting time as zero for each jobs 5. Compute each job and find the average waiting by dividing total compute each job and find number of jobs b) Shortest Job First: 1. Get the number of jobs to be scheduled 2. Get the arrival time and service time of each job 3. sort the job according to its service time 4. Intialize the waiting time as zero for each job c) Round Robin:
  • 51. 51 1. Get the number of jobs to be scheduled 2. Get the arrival time ,service time and timeslice of each job 3. Sort the job according to its time of the arrival 4. Repeat the above steps intill all the jobs are completely serviced d) Priority scheduling: 1. Get the number of jobs to be scheduled 2.Get the arrival time, service time and priority of every jobs 3. Initialize the waiting time as zero for each jobs 4. While processing the jobs according to the started time and the service time of the jobs being processed currently to the waiting time for each job 5. Compute the total waiting time by adding individual waiting time of the each job and find the arrange time of job Source Code for FCFS: import java.io.*; class schedule { int hr,min,sec,ser,wait; String name; DataInputStream d=new DataInputStream(System.in); void get()throws IOException {
  • 52. 52 System.out.println("ENTER PROCESS NAME:"); name=d.readLine(); System.out.println("ENTER THE HOUR:"); hr=Integer.parseInt(d.readLine()); if(hr<=24) { System.out.println("ENTER THE MINUTES:"); min=Integer.parseInt(d.readLine()); if(min<=60) { System.out.println("ENTER THE SECONDS:"); sec=Integer.parseInt(d.readLine()); if(sec<=60) { System.out.println("ENTER THE SERVICE TIME:"); ser=Integer.parseInt(d.readLine()); } else { System.out.println("ENTER THE SECONDS<=60"); sec=Integer.parseInt(d.readLine()); } }
  • 53. 53 else { System.out.println("ENTER THE MINUTES<=60"); min=Integer.parseInt(d.readLine()); } } else { System.out.println("ENTER THE HOURS<=24"); hr=Integer.parseInt(d.readLine()); } } void put() { System.out.println(" "+name"tt"+hr":"+min+":"+sec+"ttt"+ser+"ttt"+wait); } } class fcfs { public static void main(String args[])throws IOException { int i,j; float total=0.0f;
  • 54. 54 schedule s[],t; DataInputStream d=new DataInputStream(System.in); System.out.println("ENTER THE NUMBER OF PROCESSES:"); int n=Integer.parseInt(d.readLine(); s=new schedule[10]; t=new schedule(); for(i=0;i<n;i++) { s[i]=new schedule(); s[i].get(); } for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(s[i].hr>s[j].hr) { t=s[i]; s[i]=s[j]; s[j]=t; } else if(s[i].hr==s[j].hr&&s[i].min>s[j].min&&s[i].sec>s[j].sec) {
  • 55. 55 t=s[i]; s[i]=s[j]; s[j]=t; } else if(s[i].hr==s[j].hr&&s[i].min>s[j].min&&s[i].sec>s[j].sec) { t=s[i]; s[i]=s[j]; s[j]=t; } } } System.out.println("nPROCESStSTARTING TIMEt SERVICE TIMEtWAITING TIMEn"); for(i=0;i<n;i++) { if(i==0) s[i].wait=0; else s[i].wait=s[i-1].wait+s[i-1].ser; total+=s[i].wait; s[i].put(); }
  • 56. 56 System.out.println("nTOTAL WAITING TIME""+total); System.out.println("nAVERAGE WAITING TIME:"+(total/n)); } } Source Code for SJF: import java.io.*; class schedule { int hr,min,sec,ser,wait; int tot; String name; DataInputStream d=new DataInputStream(System.in); void get()throws IOException { System.out.println("ENTER PROCESS NAME:"); name=d.readLine(); System.out.println("ENTER THE HOUR:"); hr=Integer.parseInt(d.readLine()); if(hr<=24) { System.out.println("ENTER THE MINUTES:"); min=Integer.parseInt(d.readLine()); if(min<=60)
  • 57. 57 { System.out.println("ENTER THE SECONDS:"); sec=Integer.parseInt(d.readLine()); if(sec<=60) { System.out.println("ENTER THE SERVICE TIME:"); ser=Integer.parseInt(d.readLine()); } else { System.out.println("ENTER THE SECONDS<=60"); sec=Integer.parseInt(d.readLine()); } } else { System.out.println("ENTER THE MINUTES<=60"); min=Integer.parseInt(d.readLine()); } } else { System.out.println("ENTER THE HOURS<=24");
  • 58. 58 hr=Integer.parseInt(d.readLine()); } tot=hr+min+sec; } void put() { System.out.println(name+"t"+hr+":"+min+":"+sec+"ttt"+ser+"ttt"+wait); } } class sjf { public static void main(String args[])throws IOException { int i,j; float total=0.0f; schedule s[],t; DataInputStream d=new DataInputStream(System.in); System.out.println("ENTER THE NUMBER OF PROCESSES:"): int n=Integer.parseInt(d.readLine()); s=new schedule[10]; t=new schedule(); for(i=0;i<n;i++) {
  • 60. 60 total+=s[i].wait; s[i].put(); } System.out.println("nTOTAL WAITING TIME:"+total); System.out.println("nAVERAGE WAITING TIME:"+(total/n)); } } Source Code for Round Robin: import java.io.*; class schedule { int hr,min,sec,ser,wait; String name; DataInputStream d=new DataInputStream(System.in); void get()throws IOException { System.out.println("ENTER PROCESS NAME:"); name=d.readLine(); System.out.println("ENTER THE HOUR:"); hr=Integer.parseInt(d.readLine()); if(hr<=24) { System.out.println("ENTER THE MINUTES:");
  • 61. 61 min=Integer.parseInt(d.readLine()); if(min<=60) { System.out.println("ENTER THE SECONDS:"); sec=Integer.parseInt(d.readLine()); if(sec<=60) { System.out.println("ENTER THE SERVICE TIME:"); ser=Integer.parseInt(d.readLine()); } else { System.out.println("ENTER THE SECONDS<=60"); sec=Integer.parseInt(d.readLine()); } } else { System.out.println("ENTER THE MINUTES<=60"); min=Integer.parseInt(d.readLine()); } } else
  • 62. 62 { System.out.println("ENTER THE HOURS<=24"); hr=Integer.parseInt(d.readLine()); } } void put() { System.out.println(name+"t"+hr+":"+min+":"+sec+"ttt"+ser+"ttt"+wait); } } class round { public static void main(String args[])throws IOException { int i,j,k,round,max,ts,ml,w; int mod[][]=new int[20][20]; int tser[]=new int[20]; float total=0.0f; schedule s[],t; DataInputStream d=new DataInputStream(System.in); System.out.println("ENTER THE NUMBER OF PROCESSES:"): int n=Integer.parseInt(d.readLine()); s=new schedule[10];
  • 63. 63 t=new schedule(); for(i=0;i<n;i++) { s[i]=new schedule(); s[i].get(); } for(i=0;i<n-1;i++) { for(j=i+1;j<n;j++) { if(s[i].hr>s[j].hr) { t=s[i]; s[i]=s[j]; s[j]=t; } else if(s[i].hr==s[j].hr&&s[i].min>s[j].min) { t=s[i]; s[i]=s[j]; s[j]=t; } else if(s[i].hr==s[j].hr&&s[i].min>s[j].min&&s[i].sec>s[j].sec)
  • 64. 64 { t=s[i]; s[i]=s[j]; s[j]=t; } } } System.out.println("enter the time slice:"); ts=Integer.parseInt(d.readLine()); max=0; for(i=0;i<n;i++) { tser[i]=s[i].ser; if(max<tser[i]) max=tser[i]; } round=max/ts+1; for(i=1;i<round;i++) { for(j=0;j<n;j++) { if(tser[j]!=0) {
  • 67. 67 } } Source Code for priority scheduling: import java.io.*; class schedule { int hr,min,sec,ser,wait,pr; int tot; String name; DataInputStream d=new DataInputStream(System.in); void get()throws IOException { System.out.println("ENTER PROCESS NAME:"); name=d.readLine(); System.out.println("ENTER THE HOUR:"); hr=Integer.parseInt(d.readLine()); if(hr<=24) { System.out.println("ENTER THE MINUTES:"); min=Integer.parseInt(d.readLine()); if(min<=60) { System.out.println("ENTER THE SECONDS:");
  • 68. 68 sec=Integer.parseInt(d.readLine()); if(sec<=60) { System.out.println("ENTER THE SERVICE TIME:"); ser=Integer.parseInt(d.readLine()); System.out.println("ENTER THE PRIORITY:"); pr=Integer.parseInt(d.readLine()); } else { System.out.println("ENTER THE SECONDS<=60"); sec=Integer.parseInt(d.readLine()); } } else { System.out.println("ENTER THE MINUTES<=60"); min=Integer.parseInt(d.readLine()); } } else { System.out.println("ENTER THE HOURS<=24");
  • 69. 69 hr=Integer.parseInt(d.readLine()); } tot=hr+min+sec; } void put() { System.out.println(name+"t"+hr+":"+min+":"+sec+"ttt"+ser+"ttt"+wait); } } class pri { public static void main(String args[])throws IOException { int i,j; float total=0.0f; schedule s[],t; DataInputStream d=new DataInputStream(System.in); System.out.println("ENTER THE NUMBER OF PROCESSES:"): int n=Integer.parseInt(d.readLine()); s=new schedule[10]; t=new schedule(); for(i=0;i<n;i++) {
  • 71. 71 total+=s[i].wait; s[i].put(); } System.out.println("nTOTAL WAITING TIME:"+total); System.out.println("nAVERAGE WAITING TIME:"+(total/n)); } } Sample Input and Output: FCFS: ENTER THE NUMBER OF PROCESSES: 4 ENTER PROCESS NAME: P1 ENTER THE HOUR: 2 ENTER THE MINUTES: 5 ENTER THE SECONDS: 3 ENTER THE SERVICE TIME: 1 ENTER THE PROCESS NAME: P2
  • 72. 72 ENTER THE HOUR: 4 ENTER THE MINUTES: 6 ENTER THE SECONDS: 3 ENTER THE SERVICE TIME: 4 ENTER PROCESS NAME: P3 ENTER THE HOUR: 8 ENTER THE MINUTES: 3 ENTER THE SECONDS: 2 ENTER THE SERVICE TIME: 5 ENTER PROCESS NAME: P4 ENTER THE HOUR: 6 ENTER THE MINUTES:
  • 73. 73 3 ENTER THE SECONDS: 1 ENTER THE SERVICE TIME: 6 PROCESS STARTING TIME SERVICE TIME WAITING TIME P1 2:5:3 1 0 P2 4:6:3 4 1 P4 6:3:1 6 5 P3 8:3:2 5 11 TOTAL WAITING TIME:17.0 AVERAGE WAITING TIME:4.25 SJF: ENTER THE NUMBER OF PROCESSES: 4 ENTER PROCESS NAME: P1 ENTER THE HOUR: 4 ENTER THE MINUTES: 5 ENTER THE SECONDS: 3
  • 74. 74 ENTER THE SERVICE TIME: 2 ENTER THE PROCESS NAME: P2 ENTER THE HOUR: 2 ENTER THE MINUTES: 1 ENTER THE SECONDS: 0 ENTER THE SERVICE TIME: 4 ENTER PROCESS NAME: P3 ENTER THE HOUR: 3 ENTER THE MINUTES: 5 ENTER THE SECONDS: 2 ENTER THE SERVICE TIME: 7 ENTER PROCESS NAME:
  • 75. 75 P4 ENTER THE HOUR: 5 ENTER THE MINUTES: 2 ENTER THE SECONDS: 1 ENTER THE SERVICE TIME: 4 PROCESS STARTING TIME SERVICE TIME WAITING TIME P1 4:5:3 2 0 P2 2:1:0 4 2 P4 5:2:1 4 6 P3 3:5:2 7 10 TOTAL WAITING TIME:18.0 AVERAGE WAITING TIME:4.5 Round Robin: ENTER THE NUMBER OF PROCESSES: 4 ENTER PROCESS NAME: P1 ENTER THE HOUR: 1
  • 76. 76 ENTER THE MINUTES: 1 ENTER THE SECONDS: 1 ENTER THE SERVICE TIME: 1 ENTER THE PROCESS NAME: P2 ENTER THE HOUR: 2 ENTER THE MINUTES: 2 ENTER THE SECONDS: 2 ENTER THE SERVICE TIME: 2 ENTER PROCESS NAME: P3 ENTER THE HOUR: 3 ENTER THE MINUTES: 3 ENTER THE SECONDS:
  • 77. 77 3 ENTER THE SERVICE TIME: 3 ENTER PROCESS NAME: P4 ENTER THE HOUR: 4 ENTER THE MINUTES: 4 ENTER THE SECONDS: 4 ENTER THE SERVICE TIME: 4 Enter the time slice: 3 PROCESS STARTING TIME SERVICE TIME WAITING TIME P1 1:1:1 1 0 P2 2:2:2 2 1 P3 3:3:3 3 6 P4 4:4:4 4 6 TOTAL WAITING TIME:13.0 AVERAGE WAITING TIME:3.25
  • 78. 78 Priority Scheduling: ENTER THE NUMBER OF PROCESSES: 4 ENTER PROCESS NAME: P1 ENTER THE HOUR: 1 ENTER THE MINUTES: 2 ENTER THE SECONDS: 3 ENTER THE SERVICE TIME: 4 ENTER THE PRIORITY: 3 ENTER THE PROCESS NAME: P2 ENTER THE HOUR: 2 ENTER THE MINUTES: 5 ENTER THE SECONDS: 6
  • 79. 79 ENTER THE SERVICE TIME: 3 ENTER THE PRIORITY: 2 ENTER PROCESS NAME: P3 ENTER THE HOUR: 6 ENTER THE MINUTES: 2 ENTER THE SECONDS: 1 ENTER THE SERVICE TIME: 6 ENTER THE PRIORITY: 1 ENTER PROCESS NAME: P4 ENTER THE HOUR: 7 ENTER THE MINUTES: 3 ENTER THE SECONDS:
  • 80. 80 1 ENTER THE SERVICE TIME: 5 ENTER THE PRIORITY: 4 PROCESS STARTINGTIME SERVICETIME WAITINGTIME PRIORITY P3 6:2:1 6 0 1 P2 2:5:6 3 6 2 P1 1:2:3 4 9 3 P4 7:3:1 5 13 4 TOTAL WAITING TIME:28.0 AVERAGE WAITING TIME:7.0 Result: Thus the java program to implement the job scheduling techniques was created,executed successfully and the output was verified.
  • 81. 81 Ex.No:14 DISK SCHEDULING TECHNIQUES Aim: To write a java program to implement the concept of different disk scheduling techniques like, a)First Come First Server[FCFS] b)Shortest Seek Time First[SSTF] c)Scan d)C-Scan e)Look f)C-Look Algorithm: a) First Come First Serverd: Move the head according to the request b) Shortest Seek Time First: Move the disk arm to the request position from the current position inward or outward that maintain minimizes arm movements c) Scan: 1.Move the disk arm to the requested position in the path 2.Change the direction when there are no more request to service in the count direction d) C-Scan: Move the disk arm to the requested position which moving towards inward and direction
  • 82. 82 e) Look: The arm goes only as far as the final request in each direction then it reverse it direction f) C-Look: 1. Move head from current position 2. Process the request untill the condition is satisfied Source Code for FCFS: import java.io.*; import java.lang.*; class disk_fcfs { public static void main(String args[])throws IOException { int i,sum=0,n,st; int b[],dd[],a[]; a=new int[20]; b=new int[20]; dd=new int[20]; DataInputStream d=new DataInputStream(System.in); do { System.out.println("Enter the block number between 0 and 200:"); st=Integer.parseInt(d.readLine());
  • 83. 83 }while((st>=200)||(st<0)); System.out.println("nOur disk head is on the"+st+"th block"); a[0]=st; System.out.println("nEnter the no.of request:"); n=Integer.parseInt(d.readLine()); System.out.println("nEnter request:n"); for(i=1;i<=n;i++) { do { System.out.println("Enter "+i+"Request:"); a[i]=Integer.parseInt(d.readLine()); if((a[i]>200)||(a[i]<0)) { System.out.println("nBlock number must be between 0 and 200!n"); } }while((a[i]>200)||(a[i]<0)); } for(i=0;i<=n;i++) dd[i]=a[i]; System.out.println("nnttFIRST COME FIRST SERVE"); System.out.println("nDISK QUEUE:"); for(i=0;i<=n;i++)
  • 84. 84 { System.out.println("t"+a[i]); System.out.println("nnACCESS ORDER:"); for(i=0;i<=n;i++) { System.out.println("t"+dd[i]); if(i!=n) sum+=Math.abs(dd[i]-dd[i+1]); } System.out.println("nnTotal no.of head Movements:"+sum); } } Source Code for SSTF: import java.io.*; import java.lang.*; class disk_sstf { public static void main(String args[])throws IOException { int i,j,z,c=0,sum=0,n,n1,min,st; int b[],dd[],a[]; a=new int[20]; b=new int[20];
  • 85. 85 dd=new int[20]; DataInputStream d=new DataInputStream(System.in); do { System.out.println("Enter the block number between 0 and 200:"); st=Integer.parseInt(d.readLine()); }while((st>=200)||(st<0)); System.out.println("nOur disk head is on the"+st+"th block"); a[0]=st; System.out.println("nEnter the no.of request:"); n=Integer.parseInt(d.readLine()); System.out.println("nEnter request:n"); for(i=1;i<=n;i++) { do { System.out.println("Enter "+i+"Request:"); a[i]=Integer.parseInt(d.readLine()); if((a[i]>200)||(a[i]<0)) { System.out.println("nBlock number must be between 0 and 200!n"); } }while((a[i]>200)||(a[i]<0));
  • 87. 87 for(z=j;z<n1+1;z++) dd[z]=dd[z+1]; dd[z]='0'; } System.out.println("nnttSHORTEST SEEK TIME FIRST:"); System.out.println("nDISK QUEUE:"); for(i=0;i<=n;i++) System.out.println("t"+a[i]); System.out.println("nnACCESS ORDER:"); for(i=0;i<=c;i++) { System.out.println("t"+b[i]); if(i!=c) sum+=Math.abs(b[i]-b[i+1]); } System.out.println("nn Total no.of head movements:"+sum); } } Source Code for Scan: import java.io.*; import java.lang.*; class disk_scan {
  • 88. 88 public static void main(String args[])throws IOException { int i,j,c=0,sum=0,n,st,temp,t; int b[],dd[],a[]; a=new int[20]; b=new int[20]; dd=new int[20]; DataInputStream d=new DataInputStream(System.in); do { System.out.println("Enter the block number between 0 and 200:"); st=Integer.parseInt(d.readLine()); }while((st>=200)||(st<0)); System.out.println("nOur disk head is on the"+st+"th block"); a[0]=st; System.out.println("nEnter the no.of request:"); n=Integer.parseInt(d.readLine()); System.out.println("nEnter request:n"); for(i=1;i<=n;i++) { do { System.out.println("Enter "+i+"Request:");
  • 89. 89 a[i]=Integer.parseInt(d.readLine()); if((a[i]>200)||(a[i]<0)) { System.out.println("nBlock number must be between 0 and 200!n"); } }while((a[i]>200)||(a[i]<0)); } for(i=0;i<=n;i++) dd[i]=a[i]; for(i=0;i<=n;i++) for(j=i+1;j<=n;j++) if(dd[i]>dd[j]) { temp=dd[i]; dd[i]=dd[j]; dd[j]=temp; } for(i=0;i<=n;i++) { if(st==dd[i]) { t=i+1; b[c]=st;
  • 90. 90 for(j=i-1;j>=0;j--) b[++c]=dd[j]; b[++c]=0; for(j=t;j<=n;j++) b[++c]=dd[j]; } } System.out.println("nnttSCAN TECHNIQUE:"); System.out.println("nDISK QUEUE:"); for(i=0;i<=n;i++) System.out.println("t"+a[i]); System.out.println("nnACCESS ORDER:"); for(i=0;i<=c;i++) { System.out.println("t"+b[i]); if(i!=c) sum+=Math.abs(b[i]-b[i+1]); } System.out.println("nn Total no.of head movements:"+sum); } }
  • 91. 91 Source Code for C-Scan: import java.io.*; import java.lang.*; class disk_c_scan { public static void main(String args[])throws IOException { int i,j,sum=0,n,st,temp,t,c=0; int b[],dd[],a[]; a=new int[20]; b=new int[20]; dd=new int[20]; DataInputStream d=new DataInputStream(System.in); do { System.out.println("Enter the block number between 0 and 200:"); st=Integer.parseInt(d.readLine()); }while((st>=200)||(st<0)); System.out.println("nOur disk head is on the"+st+"th block"); a[0]=st; System.out.println("nEnter the no.of request:"); n=Integer.parseInt(d.readLine()); System.out.println("nEnter request:n");
  • 92. 92 for(i=1;i<=n;i++) { do { System.out.println("Enter "+i+"Request:"); a[i]=Integer.parseInt(d.readLine()); if((a[i]>200)||(a[i]<0)) { System.out.println("nBlock number must be between 0 and 200!n"); } }while((a[i]>200)||(a[i]<0)); } for(i=0;i<=n;i++) dd[i]=a[i]; for(i=0;i<=n;i++) for(j=i+1;j<=n;j++) if(dd[i]>dd[j]) { temp=dd[i]; dd[i]=dd[j]; dd[j]=temp; } for(i=0;i<=n;i++)
  • 94. 94 } System.out.println("nn Total no.of head movements:"+sum); } } Source Code for Look: import java.io.*; import java.lang.*; class disk_look { public static void main(String args[])throws IOException { int i,j,c=0,sum=0,n,st,temp,t,s; int b[],dd[],a[]; a=new int[20]; b=new int[20]; dd=new int[20]; DataInputStream d=new DataInputStream(System.in); do { System.out.println("Enter the block number between 0 and 200:"); st=Integer.parseInt(d.readLine()); }while((st>=200)||(st<0)); System.out.println("nOur disk head is on the"+st+"th block");
  • 95. 95 a[0]=st; System.out.println("nEnter the no.of request:"); n=Integer.parseInt(d.readLine()); System.out.println("nEnter request:n"); for(i=1;i<=n;i++) { do { System.out.println("Enter "+i+"Request:"); a[i]=Integer.parseInt(d.readLine()); if((a[i]>200)||(a[i]<0)) { System.out.println("nBlock number must be between 0 and 200!n"); } }while((a[i]>200)||(a[i]<0)); } for(i=0;i<=n;i++) dd[i]=a[i]; s=a[0]; for(i=0;i<=n;i++) for(j=i+1;j<=n;j++) if(dd[i]>dd[j]) {
  • 97. 97 System.out.println("t"+b[i]); if(i!=c) sum+=Math.abs(b[i]-b[i+1]); } System.out.println("nn Total no.of head movements:"+sum); } } Source Code for C-Look: import java.io.*; import java.lang.*; class disk_c_look { public static void main(String args[])throws IOException { int i,j,c=0,sum=0,n,st,temp,t,s; int b[],dd[],a[]; a=new int[20]; b=new int[20]; dd=new int[20]; DataInputStream d=new DataInputStream(System.in); do { System.out.println("Enter the block number between 0 and 200:");
  • 98. 98 st=Integer.parseInt(d.readLine()); }while((st>=200)||(st<0)); System.out.println("nOur disk head is on the"+st+"th block"); a[0]=st; System.out.println("nEnter the no.of request:"); n=Integer.parseInt(d.readLine()); System.out.println("nEnter request:n"); for(i=1;i<=n;i++) { do { System.out.println("Enter "+i+"Request:"); a[i]=Integer.parseInt(d.readLine()); if((a[i]>200)||(a[i]<0)) { System.out.println("nBlock number must be between 0 and 200!n"); } }while((a[i]>200)||(a[i]<0)); } for(i=0;i<=n;i++) dd[i]=a[i]; s=a[0]; for(i=0;i<=n;i++)
  • 100. 100 System.out.println("nnACCESS ORDER:"); for(i=0;i<=c;i++) { System.out.println("t"+b[i]); if(i!=c) sum+=Math.abs(b[i]-b[i+1]); } System.out.println("nn Total no.of head movements:"+sum); } } Sample Input and Output: FCFS: Enter the block number between 0 and 200:53 Our disk head is on the 53th block Enter the no.of request:5 Enter Request: Enter 1 Request:123 Enter 2 Request:45 Enter 3 Request:20 Enter 4 Request:100 Enter 5 Request:199 FIRST COME FIRST SERVE DISK QUEUE : 53 123 45 20 100 199
  • 101. 101 ACCESS ORDER : 53 123 45 20 100 199 Total no.of head movements : 352 SSTF: Enter the block number between 0 and 200:53 Our disk head is on the 53th block Enter the no.of request:5 Enter Request: Enter 1 Request:123 Enter 2 Request:45 Enter 3 Request:20 Enter 4 Request:100 Enter 5 Request:199 SHORTEST SEEK TIME FIRST DISK QUEUE : 53 123 45 20 100 199 ACCESS ORDER : 53 45 20 100 123 199 Total no.of head movements : 212 SCAN: Enter the block number between 0 and 200:53 Our disk head is on the 53th block Enter the no.of request:5 Enter Request: Enter 1 Request:45 Enter 2 Request:20
  • 102. 102 Enter 3 Request:123 Enter 4 Request:100 Enter 5 Request:199 SCAN TECHNIQUE: DISK QUEUE : 53 45 20 123 100 199 ACCESS ORDER : 53 45 20 0 100 123 199 Total no.of head movements : 252 C-SCAN: Enter the block number between 0 and 200:53 Our disk head is on the 53th block Enter the no.of request:5 Enter Request: Enter 1 Request:123 Enter 2 Request:45 Enter 3 Request:20 Enter 4 Request:100 Enter 5 Request:199 C-SCAN TECHNIQUE: DISK QUEUE : 53 123 45 20 100 199 ACCESS ORDER : 53 100 123 199 199 0 20 45 Total no.of head movements : 390 LOOK: Enter the block number between 0 and 200:53
  • 103. 103 Our disk head is on the 53th block Enter the no.of request:5 Enter Request: Enter 1 Request:123 Enter 2 Request:45 Enter 3 Request:20 Enter 4 Request:100 Enter 5 Request:199 LOOK TECHNIQUE: DISK QUEUE : 53 123 45 20 100 199 ACCESS ORDER : 53 45 20 200 100 123 100 Total no.of head movements : 313 C-LOOK: Enter the block number between 0 and 200:53 Our disk head is on the 53th block Enter the no.of request:5 Enter Request: Enter 1 Request:123 Enter 2 Request:45 Enter 3 Request:20 Enter 4 Request:100 Enter 5 Request:199
  • 104. 104 C-LOOK TECHNIQUE: DISK QUEUE : 53 123 45 20 100 199 ACCESS ORDER : 53 100 123 199 20 45 Total no.of head movements : 350 Results: Thus the java program to implement the disk scheduling techniques was created, executed successfully and the output was verified.
  • 105. 105 Ex.No:15 MEMORY ALLOCATION TECHNIQUES Aim: To write a java program to implement the concept of different memory allocation techniques like, a) First Fit b) Best Fit c) Worst Fit d) Next Fit Algorithm: a) First Fit 1. Get thenumber of process to be allocated 2. Get the number of free blocks available and its size 3. Find the first free block from the starting, so that the new process can allocated fully in that block b) Best Fit 1. Get the number of process to be allocated 2. Get the number of free blocks available and its size 3. Repeat the above steps, so that all the process can be allocated c) Worst Fit 1. Get the number of process to be allocated 2. Get the number of free blocks available and size 3. Get the memory size of the process to be allocated
  • 106. 106 4. Repeat the above steps, so that all the process can be allocated d) Next Fit 1. Get the number of process to be allocated 2. Get the memory of free blocks available and its size 3. Get the memory size of the process to be allocated 4. Find the first free block from the starting, so that the new process can be allocated in that block. Source Code: import java.lang.*; import java.io.*; class MALLOCATION { static int f1,p,next,c,l; static int bsize[]=new int[30]; static int fsize[]=new int[30]; static int f1size[]=new int[30]; static int asize[]=new int[30]; static void firstFit(int n) { int k=0,i=1; for(i=0;i<f1;i++) { if(fsize[i]>=n)
  • 107. 107 { asize[i]=asize[i]+n; next=i+1; System.out.println("nMEMORY ALLOCATION IN BLOCK:"+i); int s1=50; for(l=0;l<i;l++) s1=s1+fsize[l]+asize[l]; System.out.println("nMemory allocated for process:"+asize[l]); fsize[i]=-n; k=1; break; } } if(k==0) System.out.println("nNo matching block for:"+n); System.out.println("n"); } static void bestFit(int n) { int l,s,k=0; int min1=10000; for(int i=0;i<f1;i++) {
  • 108. 108 if((fsize[i]-n)>=0) { s=fsize[i]-n; if(s<min1) { min1=s; k=i+1; { int l,k=0; for(int i=next;i<f1;i++) { if((fsize[i]-n)>=n) { next=i+1; fsize[i]=fsize[i]-n; asize[i]=asize[i]+n; int s1=50; for(l=0;l<i;l++) s1=s1+fsize[l]+asize[l]; System.out.println("n Memory allocated for process:"+asize[l]); System.out.println("n Memory allocated in block:"+(k-1)); k=1; break;
  • 109. 109 } } if(k==0) System.out.println("n No matching block for:"+n); System.out.println(); } public static void main(String args[]) { try { BufferedReader ob=new BufferedReader(new InputStreamReader(System.in)); char ch; int var=1; int b1size,i; next=0; System.out.println("nttMEMORY ALLOCATION TECHNIQUES"); System.out.println("ntt*************************************"); System.out.println("Output for memory allocation techniques"); System.out.println("nEnter the number of free block:"); f1=Integer.parseInt(ob.readLine()); int sum=50; System.out.println("Enter within the width 480"); System.out.println(Enter width within the limit");
  • 110. 110 for(i-0;i<f1;i++) { System.out.println("nEnter the size of the block"+i+":"); fsize[i]=Integer.parseInt(ob.readLine()); if(fsize[i]>481) { System.out.println("nExecuting the limit, re-enter the value!"); System.out.println(); continue; } } } if(k!=0) { next=k; fsize[k-1]=min1; asize[k-1]+=n; int s1=50; for(l=0;l<k-1;l++) s1=s1+fsize[l]+asize[l]; System.out.println("n Memory allocated for process:"+asize[l]); System.out.println("n Memory allocated in block:"+(k-1)); }
  • 111. 111 else System.out.println("n No matching block for:"+n); } static void worstFit(int n) { int l,s,k-0; int max1=0; for(int i=0;i<f1;i++) { if((fsize[i]-n)>0) { s=fsize[i]-n; if(s>=max1) { max1=s; k=i+1; } } } if(k!=0) { next=k; fsize[k-1]=max1;
  • 112. 112 fsize[k-1]=asize[k-1]+n; int s1=50; for(l=0;l<k-1;l++) s1+=fsize[l]+asize[l]; System.out.println("n Memory allocated for process:"+asize[l]); System.out.println("n Memory allocated in block:"+(k-1)); } else System.out.println("n No matching block for:"+n); } static void nextFit(int n) { f1size[i]=fsize[i]; asize[i]=0; sum=sum+fsize[i]; } System.out.println("nHow many no.of process:"); p=Integer.parseInt(ob.readLine()); for(i=0;i<p;i++) { System.out.println("n Enter the size of allocated memory process"+i+":"); bsize[i]=Integer.parseInt(ob.readLine()); }
  • 113. 113 while(var!=0) { System.out.println("nttMEMORY ALLOCATION TECHNIQUES"); System.out.println("ntt*************************************"); System.out.println("n1.FIRST FITn2.BEST FITn3.WORST FITn4.NEXT FITn5.EXIT"): System.out.println("nEnter your choice:"); c=Integer.parseInt(ob.readLine()); switch(c) { case 1: for(i=0;i<p;i++) firstFit(bsize[i]); break; case 2: for(i=0;i<p;i++) bestFit(bsize[i]); break; case 3: for(i=0;i<p;i++) worstFit(bsize[i]); break; case 4:
  • 114. 114 for(i=0;i<p;i++) nextFit(bsize[i]); break; case 5: System.exit(0); default: System.out.println("nENTERED WRONG CHOICE:"+c); System.out.flush(); System.exit(0); } System.out.println("nDo you want to continue:"); ch=(char)ob.readLine().charAt(0); if(ch=='n'||ch=='N') System.exit(0); sum=50; for(i=0;i<f1;i++) { asize[i]=0; sum=sum+f1size[i]; fsize[i]=f1size[i]; } } }
  • 115. 115 catch(IOException e) { System.out.println("n Exception Raised"); } catch(Exception e) { } } } Sample Input and Output: MEMORY ALLOCATION TECHNIQUES ************************************* Output for memory allocation techniques Enter the number of free block:3 Enter within the width 480 Enter width within the limit Enter the size of the block 0:100 Enter the size of the block 1:50 Enter the size of the block 2:200 How many no.of process: 3 Enter the size of allocated memory process 0:200 Enter the size of allocated memory process 1:250
  • 116. 116 Enter the size of allocated memory process 2:100 MEMORY ALLOCATION TECHNIQUES ************************************* 1.FIRST FIT 2.BEST FIT 3.WORST FIT 4.NEXT FIT 5.EXIT Enter your choice:1 MEMORY ALLOCATION IN BLOCK : 2 Memory allocated for process : 200 No matching block for : 250 MEMORY ALLOCATION IN BLOCK : 0 Memory allocated for process : 100 Do you want to continue : Y MEMORY ALLOCATION TECHNIQUES ************************************* 1.FIRST FIT 2.BEST FIT 3.WORST FIT 4.NEXT FIT 5.EXIT Enter your choice : 2
  • 117. 117 Memory allocated for process : 200 Memory allocated in block : 2 No matching block for : 250 Memory allocated for process : 100 Memory allocated in block : 0 Do you want to continue : Y MEMORY ALLOCATION TECHNIQUES ************************************* 1.FIRST FIT 2.BEST FIT 3.WORST FIT 4.NEXT FIT 5.EXIT Enter your choice : 3 No matching block for : 200 No matching block for : 250 Memory allocated for process : 0 Memory allocated in block : 2 Do you want to continue : Y MEMORY ALLOCATION TECHNIQUES ************************************* 1.FIRST FIT 2.BEST FIT
  • 118. 118 3.WORST FIT 4.NEXT FIT 5.EXIT Enter your choice : 4 No matching block for : 200 No matching block for : 250 No matching block for : 100 Do you want to continue : Y MEMORY ALLOCATION TECHNIQUES ************************************* 1.FIRST FIT 2.BEST FIT 3.WORST FIT 4.NEXT FIT 5.EXIT Enter your choice : 5 Result: Thus the java program to implement the memory allocation techniques was created, executed successfully and the output was verified.
  • 119. 119 Ex.No:16 MEMORY MANAGEMENT TECHNIQUES Aim: To write a java program to implement the concept of different memory management techniques like, 1.Paging 2.Demand paging Algorithm: 1.Paging i)Display option a)store b)Retrieve c)Exit ii)Read ch iii)if ch=’a’ then get page size and process size iv)allocate process in pages v)if ch=’2’ then get logical address to the retrieve 2.Page demand i)Display option a)Store b)Retrieve c)Exit ii)Read ch iii)allocate the content to the page iv)Enter the page number Source code for paging: import java.io.*; class pagemanagementsub {
  • 120. 120 String name; class pagemanagementsub { String content; } pagemanagementsub page[]=new pagemanagementsub[10]; public pagemanagement() { for(int i=0;i<10;i++) { page[i]=new pagemanagementsub(); } } } class mem_management { int pagememsize,pageprocesssize,ppage,ptotalpage; int pframe[]=new int[10]; pagemanagement p[]=new pagemanagement[10]; public mem_management() { for(int i=0;i<10;i++) { p[i]=new pagemanagement(); } } void pagestore()throws IOException { DataInputStream d=new DataInputStream(System.in);
  • 121. 121 int i=0,j=0,e=0,t; do { System.out.println(“nEnter the logical memory size(power of 2):”); pagememsize=Integer.parseInt(d.readLine()); } while(ispow2(pagememsize)!=0); do { System.out.println(“nEnter the process size:”); pageprocesssize=Integer.parseInt(d.readLine()); if(pageprocesssize>pagememsize) System.out.println(“nError:process size should not exceed logical memory size!”); }while(pageprocesssize>pagememsize); do { System.out.println(“Enter the page size(power of 2):”); ppage=Integer.parseInt(d.readLine()); } while(ispow2(ppage)!=0); ptotalpage=pageprocesssize/ppage; if((pageprocesssize%ppage)!=0) ptotalpage++; for(i=0;i<ptotalpage;i++) { System.out.println(“Enter the content of page[“+i+”]:”); for(j=0;j<ppage;j++) { System.out.println(“Enter the content[“+j+”]:”);
  • 122. 122 p[i].page[j].content=d.readLine(); e++; if(e==pageprocessize) break; } } System.out.println(“Page Not Frame No”); for(i=0;i<ptotalpage;i++) { System.out.println(“ “+i+”tt”); pframe[i]=Integer.parseInt(d.readLine()); } System.out.println(“ntPhysical memoryn”); e=0; for(i=0;i<ptotalpage;i++) { System.out.println(“nContent of page[“+i+”]:”); for(i=0;i<ppage;i++) { t=(pframe[i]*ppage)+j; System.out.println(“Content[“+t+”]:”); System.out.println(p[i].page[j].content); e++; if(e==pageprocesssize) break; } } if((pageprocesssize%ppage)!=0) Syatem.out.println(“nThe page has internal fragmentation”);
  • 123. 123 } int ispow(int no) { float n=(float)no; for(;n>2;) n/=2; if(n==2.0) return 0; else return 1; } void pageretreive()throws IOException { DataInputStream d=new DataInputStream(System.in); int offset=0,physical_addr=0,logical_addr; int pageno,frameno; System.out.println (“nEnter logical address to retrieve:”); logical_addr=Integer.parseInt(d.readLine()); if(logical_addr>=pageprocesssize||logical_addr<0) { System.out.println(“Logical address exceeds process size!”); return; } pageno=logical_addr/ppage; frameno=pframe[pageno]; offset=logical_addr%ppage; physical_addr=offset+(frameno*ppage); System.out.println(“nPage no:”+pageno); System.out.println(“nFrame no:”+frameno);
  • 124. 124 System.out.println(“nOffset value:”+offset); System.out.println(“nPhysical address:”+physical_addr); System.out.println(“nContent:”+p[pageno].page[offset].content); } } class mem_paging { public static void main(String args[])throws IOException { mem_management m=new mem_management(); int ch; DataInputStream d=new DataInputStream(System.in); System.out.println(“nMEMORY MANAGEMENT TECHNIQUE:”); System.out.println(“PAGING:”); do { System.out.println(“n1.Store”); System.out.println(“n2.Retreive”); System.out.println(“n3.Exit”); System.out.println(“nEnter your choice:”); ch=Integr.parseInt(d.readLine()); switch(ch) { case 1: m.pagestore(); break; case 2: m.pageretreive(); break;
  • 125. 125 case 3: System.exit(0); break; default: continue; } } while(true); } } Source code for Demand Paging: import java.io.*; class demand_paging { int prs,t; int pmt[]=new int[20]; int limit[]=new int[20]; int base[]=new int[20]; String frame[]=new String[50]; String val[]=new String[50]; String cont=”y”; void demandstore()throws IOException { int i,j,k=0; DataInputStream d=new DataInputStream(System.in); System.out.println(“nDemand Paging Storing”); System.out.println(“nEnter the logical memory size:”); prs=Integer.parseInt(d.readLine()); System.out.println(“nLogical memory contents:”);
  • 126. 126 for(i=0;i<prs;<i++) { System.out.println(“Enter the value[“+i+”]:”); val[i]=d.readLine(); } System.out.println(“nFrame Details:”); for(i=0;i<prs;i++) { System.out.println(“Enter the frame no to store”’+val[i]+’”:”); k=Integer.parseInt(d.readLine()); pmt[i]=k; frame[i]=val[i]; } t=prs; System.out.println(); for(i=0;i<t;i++) { System.out.println(“Store”’+val[i]+’”in frame”+pmt[i]+”[Y/N]:”); cont=d.readLine(); if(cont.equalsIgnoreCase(“y”)) { base[i]=1; j=0; while(true) { if(val[i].compareTo(frame[j])==0) { limit[i]=pmt[i]; break;
  • 127. 127 } else j++; } } else { limit[i]=-1; base[i]=-1; } } System.out.println(“nPage map table:”); System.out.println(“PAGE NOtFRAME NOtCONTENT”); for(i=0;i<t;i++) { System.out.println(“ “+i+”tt”+limit[i]+”tt”+val[i]); } System.out.println(“n(-1)represents frame number which is not loaded”); } void demandretreive()throws IOException { int I,j,k=0; DataInputStream d=new DataInputStream(System.in); System.out.println(“nDemand page retrieval:”); System.out.print(“Enter the page no to retrieve [0-“+(prs-1)+”]:”); i=Integer.parseInt(d.readLine()); while(i<prs) { if(base[i]==1)
  • 128. 128 { System.out.println(“nThe page is loaded to frame”+limit[i]+”and content”val[i]); break; } else { k=0; while(true) { if(val[i].compareTo(frame[k])==0) { limit[i]=pmt[i]; base[i]=1; break; } else k++; } } } System.out.println(“nPage map table:”); System.out.println(“PAGE NOtFRAME NOtCONTENT”); for(i=0;i<t;i++) { System.out.println(“ “+i+”tt”+limit[i]+”tt”+val[i]); } System.out.println(“n(-1)represents frame no which is not loaded”); } }
  • 129. 129 class mem_demand { public static void main(String args[])throws IOException { demand_paging dp=new demand_paging(); int c; DataInputStream d=new DataInputStream(System.in); System.out.println(“nMEMORY MANAGEMENT TECHNIQUE”); System.out.println(DEMAND Paging:”); do { System.out.println(“n1.Store”); System.out.println(“2.Retreive”); System.out.println(“3.Exit”); System.out.println(“nEnter your choice:”); c=Integer.parseInt(d.readLine()); switch (c) { case 1: dp.demandstore(); break; case 2: dp.demandretreive(); break; case 3: System.exit(0); break; default: continue;
  • 130. 130 } } while(true); } } Sample Input and Output: Paging MEMORY MANAGEMENT TECHNIQUE: PAGING: 1.Store 2.Retreive 3.Exit Enter your choice:1 Enter the logical memory size(power of 2):16 Enter the process size:10 Enter the page size(power of 2):4 Enter the content of page[0]: Enter the content[0]:00 Enter the content[1]:01 Enter the content[2]:02 Enter the content[3]:03 Enter the content of page[1]: Enter the content[0]:10 Enter the content[1]:11 Enter the content[2]:12 Enter the content[3]:13 Enter the content of page[2]: Enter the content[0]:20 Enter the content[1]:21
  • 131. 131 Page No Frame No 0 1 1 3 2 0 Physical memory Content of page[0]: Content[4]:00 Content[5]:01 Content[6]:02 Content[7]:03 Content of page[1]: Content[12]:10 Content[13]:11 Content[14]:12 Content[15]:13 Content of page[2]: Content[0]:20 Content[1]:21 The page has internal fragmentation 1.Store 2.Retreive 3.Exit Enter your choice:2 Enter logical address to retrieve:2 Page no:0 Frame no:1 Offset value:2 Physical address:6 Content:02
  • 132. 132 1.Store 2.Retreive 3.Exit Enter your choice:3 Demand Paging MEMORY MANAGEMENT TECHNIQUE: DEMAND PAGING: 1.Store 2.Retreive 3.Exit Enter your choice:1 Demand Paging Storing Enter the logical memory size:10 Logical memory contents: Enter the value[0]:one Enter the value[1]:Two Enter the value[2]:Three Enter the value[3]:Four Enter the value[4]:Five Enter the value[5]:Six Enter the value[6]:Seven Enter the value[7]:Eight Enter the value[8]:Nine Enter the value[9]:Ten Frame Details: Enter the frame no to store ‘One’:11 Enter the frame no to store ‘Two’:22 Enter the frame no to store ‘Three’:33
  • 133. 133 Enter the frame no to store ‘Four’:44 Enter the frame no to store ‘Five’:55 Enter the frame no to store ‘Six’:66 Enter the frame no to store ‘Seven’:77 Enter the frame no to store ‘Eight’:88 Enter the frame no to store ‘Nine’:99 Enter the frame no to store ‘Ten’:100 Store ‘One’in frame 11[Y/N]:Y Store ‘Two’in frame 22[Y/N]:Y Store ‘Three’in frame 33[Y/N]:Y Store ‘Four’in frame 44[Y/N]:Y Store ‘Five’in frame 55[Y/N]:Y Store ‘Six’in frame 66[Y/N]:N Store ‘Seven’in frame 77[Y/N]:Y Store ‘Eight’in frame 88[Y/N]:Y Store ‘Nine’in frame 99[Y/N]:Y Store ‘Ten’in frame 100[Y/N]:N Page map table: PAGE NO FRAME NO CONTENT 0 11 One 1 22 Two 2 33 Three 3 44 Four 4 55 Five 5 -1 Six 6 77 Seven 7 88 Eight 8 99 Nine 9 -1 Ten
  • 134. 134 (-1) represents frame number which is not loaded 1.Store 2.Retreive 3.Exit Enter your choice:2 Demand page retrieval: Enter the page no to retrieve[0-9]:1 The page is loaded to frame 22 and content Two Page map table: PAGE NO FRAME NO CONTENT 0 11 One 1 22 Two 2 33 Three 3 44 Four 4 55 Five 5 -1 Six 6 77 Seven 7 88 Eight 8 99 Nine 9 -1 Ten (-1) represents frame number which is not loaded 1.Store 2.Retreive 3.Exit Enter your choice:3 Result: Thus the java program to implement the memory management techniques was created, executed successfully and the output was verified
  • 135. 135 Ex.No:17 PAGE REPLACEMENT TECHNIQUES Aim: To write a java program to implement the concept of different page replacement techniques. Algorithm: 1.Start the program execution 2.enter the number of pages and frames 3.enter the value into pages 4.display menu 5.if ch=1,the FIFO 6.if ch=2,then LRU 7.if ch=3,then exit 8.if any page fault then print page fault occurs 9.Stop the execution Source code: import java.io.*; class page_r { int page[][]=new int[50][50]; int p[]=new int[50]; int ht[]=new int[10]; int n,fr; void get()throws IOException { int i; DataInputStream d=new DataInputStream(System.in); System.out.print(“nEnter the no.of page:”); n=Integer.parseInt(d.readLine());
  • 136. 136 System.out.print(“nEnter the no.of frame:”); fr=Integer.parseInt(d.readLine()); System.out.println(“nEnter the content:”); for(i=0;i<n;i++) p[i]=Integer.parseInt(d.readLine()); } void fifo() { int i,j,k,l,c,t; int flg,nw,pf; c=0; for(i=0;i<fr;i++) page[i][c]=-1; page[0][0]=p[0]; pf=1; nw=1; i=1; while(i<n) { t=p[i]; flg=0; for(k=0;k<fr;k++) { if(page[k][c]==t) flg=1; } if(flg==0) { c++;
  • 138. 138 System.out.println(); } System.out.println(“nTotal no.of page fault:”+pf); } void lru { int page1[][]=new int[fr][n]; int frame[]=new int[fr]; int count[]=new int[fr]; int I,j,k,ts,flg,pf=0,min,c=0; ts=0; for(i=0;i<fr;i++) { frame[i]=-1; page1[i][c]=-1; count[i]=0; } for(i=0;i<n;i++) { flg=0; for(j=0;j<fr;j++) { if(frame[j]==-1) { if(flg==0) { page1[j][c]=p[i]; frame[j]=p[i]; ts++;
  • 141. 141 { for(i=0;i<c;i++) if(page1[k][i]==-1) System.out.print(“-“); else System.out.print(page1[k][i]+” “); } System.out.println(“nTotal no.of page fault:”+c); } void hitcount(int pos) { int i; for(i=0;i<fr;i++) if(i==pos) ht[i]=1; else if(ht[i]!=0) ht[i]++; } } class pagereplace { public static void main(String args[])throws IOException { DataInputStream d=new DataInputStream(System.in); int ch; page_r p=new page_r(); p.get(); do {
  • 142. 142 System.out.println(“nn1.FIFO”); System.out.println(“2.LRU”); System.out.println(“3.Exit”); System.out.print(“nEnter your choice:”); ch=Integer.parseInt(d.readLine()); switch(ch) { case 1: p.fifo(); break; case 2: p.lru(); break; case 3: System.out.println(“you are exiting”); default: System.out.println(“Invalid choice!!”); } } while(ch!=3); } } Sample Input and Output: Enter the no.of page:5 Enter the no.frame:5 Enter the content: 2 3 4
  • 143. 143 5 6 1.FIFO 2.LRU 3.Exit Enter your choice:1 FIFO page number: 2 3 4 5 6 Page table: 2 2 2 2 2 - 3 3 3 3 - - 4 4 4 - - - 5 5 - - - - 6 Total no. of page fault:5 1.FIFO 2.LRU 3.Exit Enter your choice:2 LRU Page number: 2 3 4 5 6 Page table: 2 2 2 2 2 - 3 3 3 3 - - 4 4 4
  • 144. 144 - - - 5 5 - - - - 6 Total no. of page fault:5 1.FIFO 2.LRU 3.Exit Enter your choice:3 you are exiting Result: Thus the java program to implement the different page replacement techniques was created, executed successfully and the output was verified.
  • 145. 145 Ex.No:18 PRODUCER CONSUMER PROBLEM Aim: To write a java program to implement the concept of the producer consumer problem. Algorithm: a)Display the menu Read the choice 1.Produce a problem 2.consume a problem 3.display 4.exit b)if choice=1 then do 1.get the process to be proceed 2.check whether process already existing if(yes) display 3.check whether process already existing if(yes)then consume the process 4.display all the process to be consumed i)get the process to be consumed ii)check the process is already produced, if yes then consume. Source code: import java.io.*; class semaphore { int s=0,z=0; String wait[]=new String[50]; String produce[]=new String[50]; void producer()throws IOException { int i,j=0,check=0; String ch=”y”;
  • 146. 146 do { DataInputStream d=new DataInputStream(System.in); System.out.println(“nenter the process name to produce:”); ++s; produce[s]=d.readLine(); for(i=1;i<s;i++) { if(produce[i].compareTo(produce[s])==0) { System.out.println(“nprocess already exists!!”); --s; break; } } for(i=1;i<=z;i++) { if(produce[s].compareTo(wait[i])==0) { System.out.println(“Waiting process”); System.out.println(produce[s]+”is now consumed”); j=1; --s; check=1; break; } } if(check==1) {
  • 147. 147 for(i=j;i<z;i++) wait[i]=wait[i+1]; z--; } if(check==0) { System.out.println(“nProduced process”); for(i=1;i<=s;i++) System.out.println(produce[i]); } System.out.println(“nnDo you want to continue?”); ch=d.readLine(); } while(ch.equalsIgnoreCase(“y”)); } void consumer()throws IOException { DataInputStream d=new DataInputStream(System.in); String consume,ch; int i,j=0,flag; if(s==0) { System.out.println(“nNo process produced please wait”); return; } System.out.println(“nnConsume a process”); do { flag=0;
  • 148. 148 System.out.println(“nEnter the consume process”); consume=d.readLine(); for(i=1;i<=s;i++) { if(produce[i].compareTo(consume)==0) { flag=1; j=i; break; } } for(i=1;i<=z;i++) { if(wait[i].compareTo(consume)==0) { flag=2; break; } } if(flag==1) { System.out.println(“nprocess”+consume+” is now consumed”); for(i=j;i<s;i++) produce[i]=produce[i+1]; --s; } else if(flag==2) System.out.println(“nprocess already exists”); else
  • 149. 149 { System.out.println(“nprocess”+consume+”has to be produced”); System.out.println(“nIt has to wait”); wait[++z]=consume; } if(z==0) System.out.println(“nNo waiting process”); else { System.out.println(“nWaiting process”); for(i=1;i<=z;i++) System.out.println(wait[i]); } System.out.print(“nDo you want to continue?”); ch=d.readLine(); } while(ch.equalsIgnoreCase(“y”)); } void display() { int i; System.out.println(“nnPRODUCED PROCESS”); for(i=1;i<=s;i++) System.out.println(produce[i]); System.out.println(“nnWAITING PROCESS”); for(i=1;i<=z;i++) System.out.println(wait[i]); } }
  • 150. 150 class prod_cons { public static void main(String args[])throws IOException { DataInputStream d=new DataInputStream(System.in); semaphore se=new semaphore(); int c; do { System.out.println(“nnProducer--> Consumer problem”); System.out.println(“n1.produce a process”); System.out.println(“2.Consume a process”); System.out.println(“3.Display”); System.out.println(“4.Exit”); System.out.println(“nEnter your choice:”); c=Integer.parseInt(d.readLine()); switch(c) { case 1: se.producer(); break; case 2: se.consumer(); break; case 3: se.display(); break; case 4: System.exit(0);
  • 151. 151 default: System.out.println(“Option not valid”); }} while(true); }} Sample Input and Output: Producer- ->Consumer problem 1.Produce a process 2.Consume a process 3.Display 4.Exit Enter your choice:1 Enter the process name to produce: P1 Produced process P1 Do you want to continue?Y Enter the process name to produce: P2 Produced process P1 P2 Do you want to continue?N Producer- ->Consumer problem 1.Produce a process 2.Consume a process 3.Display 4.Exit Enter your choice:2
  • 152. 152 Consume a process Enter the consume process P3 Process P3 has to be produced It has to wait Waiting process P3 Do you want to continue?N Producer- ->Consumer problem 1.Produce a process 2.Consume a process 3.Display 4.Exit Enter your choice:3 PRODUCED PROCESS P1 P2 WAITING PROCESS P3 Producer- ->Consumer problem 1.Produce a process 2.Consume a process 3.Display 4.Exit Enter your choice:4 Result: Thus the java program to implement the producer consumer problem was created, executed successfully and the output was verified.
  • 153. 153 Ex.No:19 BANKERS ALGORITHM Aim: To write a java program to implement Bankers Algorithm Algorithm: 1.If request be the array of process p 2.If request [i]=k then process p wants k instance of resource type R 3.when a request for resources is made by process p then following action are taken i)if request<=available go to step 3 ii)the system pretend to have allocated the request resource to p Available=Available-request Allocation=Allocation+ request Need=Need-request Source code: import java.lang.*; import java.io.*; public static void main(String args[]) { BankSub BS=new BankSub(); try { BS.mainFun(); } catch(Exception E) { System.out.println(“Exception caught from main”); } } }
  • 154. 154 class BankSub { int alloc[][],max[],need[][],ne[][],al[][],interavail[][]; int finish[],avail[],requ[],work[],order[]; int pre,av[]; int n,j,i,f,ch,inc,a,r,flag; char c; public BankSub() { alloc=new int[10][10]; max=new int[10][10]; need=new int[10][10]; ne=new int[10][10]; al=new int[10][10]; interavail=new int[10][10]; finish=new int[10]; avail=new int[10]; requ=new int[10]; work=new int[10]; order=new int[10]; pre=0; av=new int[10]; inc=0; } public void mainFun()throws IOException { try { BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  • 155. 155 System.out.print(“nnHow many process to be entered:”); n=Integer.parseInt(br.readLine()); System.out.print(“nEnter Number of resources:”); r=Integer.parseInt(br.readLine()); System.out.println(“nEnter the allocated value for each process:”); for(i=0;i<n;i++) { System.out.println(“P”+(i+1)+”-->”); for(j=0;j<r;j++) { alloc[i][j]=Integer.parseInt(br.readLine()); } } System.out.println(“nEnter maximum value for each process:”); for(i=0;i<n;i++) { System.out.println(“P”+(i+1)+”-->”); for(j=0;j<r;j++) { max[i][j]=Integer.parseInt(br.readLine()); } } System.out.println(“nEnter available value:”); System.out.prin(“n”); for(i=0;i<r;i++) { System.out.println(“Resource”+(i+1)+”-->”); avail[i]=Integer.parseInt(br.readLine()); }
  • 156. 156 for(i=0;i<n;i++) { for(j=0;j<r;j++) { need[i][j]=max[i][j]-alloc[i][j]; } } do { System.out.print(“nnn1.Safety algorithmn2.Resource Request algorithmn3.ExitnnEnter your choice:”); ch=Integer.parseInt(br.readLine()); switch(ch) { case 1: safety(); break; case 2: try { resources(); } catch(IOException e) {} break; case 3: System.exit(0); } }while(ch<+3); }
  • 157. 157 catch(IOException e) { System.out.println(“Number format invalid”); } } void safety() { int con[]=new int[10]; a=0; inc=0; for(i=0;i<n;i++) finish[i]=0; for(i=0;i<r;i++) work[i]=avail[i]; do { for(i=0;i<n;i++) { con[i]=check(); if(finish[i]==0&&con[i]==1) { for(j=0;j<r;j++) { work[j]=work[j]+alloc[i][j]; } finish[i]=1; order[a]=i+1; a++; /*for(j=0;j<r;j++)
  • 158. 158 { interavail[i][j]=work[j] }*/ } } inc++; }while(inc!=2); f=0; for(i=0;i<n;i++) { if(finish[i]==00 f=1; } if(f==0) { System.out.println(“nnntThe system in safe state:”); System.out.println(“nThe safe sequence:”); for(i=0;i<a;i++) System.out.print(order[i]+” “); } else { System.out.prntln(“nnntThe system in unsafe state:”); pre=1; } System.out.println(); summerize(); System.out.println(); }
  • 159. 159 void summerize() { System.out.println(“nnSummerizing..”); System.out.println(“nMax valuetAllocated valuetNeeded valuetRemaining available”); System.out.println(“nt”); for(i=0;i<n;i++) { for(j=0;j<r;j++) System.out.println(max[i][j]+” “); System.out.print(“t”); for(j=0;j<r;j++) System.out.println(alloc[i][j]+” “); System.out.print(“t”); for(j=0;j<r;j++) System.out.println(need[i][j]+” “); System.out.print(“t”); for(j=0;j<r;j++) System.out.println(interavail[i][j]+” “); System.out.println(); } System.out.print(“The available resource:”); for(i=0;i<r;i++) System.out.print(avail[i]+” “); } int check() { int f=1,flag=1; for(j=0;j<r;j++)
  • 160. 160 { if(need[i][j]<=work[j]) f=1; else f=0; flag=flag*f; } return flag; } void resource()throws IOException { try { BufferedReader b=new BufferedReader(new InputStreamReader(System.in)); int pno,f=1,var=1,flag; while(var!=0) { System.out.print(“nEnter the process no1)-->”+n+”:”); pno=Integr.parseInt(b.readLine()); if(pno<=n&&pno!=0) { pno--; System.out.print(“nEnter the current request for this process:”); for(i=0;i<r;i++) requ[i]=Integer.parseInt(b.readLine()); for(flag=1,i=0;i<r;i++) { if(requ[i]<=need[pno][i]) {
  • 162. 162 } else { System.out.println(“nERROR”); f=0; System.out.println(“nSince proceaa requires more than what it had already asked”); break; } } if(f!=0) { summerize(); if(pre!=0) { alloc[pno][i]=al[pno][i]; need[pno][i]=ne[pno][i]; avail[i]=av[i]; pre=0; } } var=0; } else { continue; } } } catch(IOException e)
  • 163. 163 {} } } Sample Input and Output: How many process to be entered:5 Enter number of resources:4 Enter the allocated value for each process: P1--> 0 0 1 2 P2--> 1 0 0 0 P3--> 1 3 5 4 P4--> 0 0 1 4 P5--> 0
  • 164. 164 6 3 2 Enter maximum value for each process: P1--> 0 0 1 2 P2--> 1 7 5 0 P3--> 2 3 5 6 P4--> 0 6 5 6 P5--> 0 6 5 2
  • 165. 165 Enter available value: Resource1-->1 Resource2-->5 Resource3-->2 Resource4-->0 1.Safety Algorithm 2.Resource request algorithm 3.Exit Enter your choice:1 The system in safe state. The Safe sequence: 1 3 4 5 2 Summerizing.. Max value Allocated value Needed value Remaining Available 0 0 1 2 0 0 1 2 0 0 0 0 1 5 3 2 1 7 5 0 1 0 0 0 0 7 5 0 3 14 12 12 2 3 5 6 1 3 5 4 1 0 0 2 2 8 8 6 0 6 5 6 0 0 1 4 0 6 4 2 2 8 9 10 0 6 5 2 0 6 3 2 0 0 2 0 2 14 12 12 The available resource:1 5 2 0 1.Safety Algorithm 2.Resource request algorithm 3.Exit Enter your choice:2 Enter the process no 1)-->5:2 Enter the current request for this process:0 4 2 0
  • 166. 166 Summerizing.. Max value Allocated value Needed value Remaining Available 0 0 1 2 0 0 1 2 0 0 0 0 1 1 1 2 1 7 5 0 1 4 2 0 0 3 3 0 3 14 12 12 2 3 5 6 1 3 5 4 1 0 0 2 2 4 6 6 0 6 5 6 0 0 1 4 0 6 4 2 2 10 10 10 0 6 5 2 0 6 3 2 0 0 2 0 2 10 9 8 The available resource:1 1 0 0 1.Safety Algorithm 2.Resource request algorithm 3.Exit Enter your choice:3 Result: Thus the java program to implement the Bankers Algorithm was created, executed successfully and the output was verified.
  • 167. 167 Ex.No:20 DINING PHILOSOPHER PROBLEM Aim: To write a java program to implement the concept of the Dining Philosopher problem. Algorithm: 1.Get the total number of philosopher 2.get the number of philosopher who are hungry 3.if all are hungry then deadlock occurs 4.get the philosopher position 5.display the menu 6.Two can eat at a time 7.one can eat at a time 8.if choice is one,then a)get the philosopher states of eating position b)display the means of those who are waiting. Source code: import java.io.*; import.java.math.*; public class DinPhilo { public static void main(String args[]) { DinPhilosopher OB; OB=new DinPhilosopher(); try { OB.mainFun(); }
  • 168. 168 catch(IOException e) { System.out.println(“Exception caught from main.”); } } } class DinPhilosopher { String[] philname; char op,conf=’Y’; int status[],hu[],pos,cho,x,i,j,r,t,tph,howhung,s; public DinPhilosopher() { philname=new String[20]; status=new int[20]; hu=new int[20]; s=0; } void one() { pos=0; System.out.println(“nALLOW ONE PHILOSOPHER TO EAT AT ANY TIMEn”); for(i=0;i<howhung;i++,pos++) { System.out.println(“tPHILOSOPHER<”+philname[hu[pos]]+”>IS GRANTED TO EAT”); for(x=pos;x<howhung;x++) System.out.println(“tPHILOSOPHER<”+philname[hu[x]]+”>IS WAITING”); }
  • 169. 169 } void two() { System.out.println(“nTWO PHILOSOPHER TO EAT AT SAME TIMEn”); for(i=0;i<howhung;i++) { for(j=i+1;j<howhung;j++) { if(Math.abs(hu[i]-hu[j])>=1&&Math.abs(hu[i]-hu[j])!=4) { System.out.println(“nnCOMBINATION”+(s+1)+”n”); t=hu[i]; r=hu[j]; s++; System.out.println(“<”+philname[hu[i]]+”>AND<”+philname[hu[j]]+”>ARE GRANTED TO EAT”); for(x=0;x<howhung;x++) { if((hu[x]!=t)&&(hu[x]!=r)) System.out.println(“PHILOSOPHER<”+philname[hu[x]]+”>IS WAITING”); } } } } } void menu()throws IOException { try {
  • 170. 170 BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); do( System.out.println(“nnDINING PHILOSOPHER PROBLEM”); System.out.print(“n1.One can eat at a timen2.Two can eat at a timen3.ExitnnEnter your choice:”); cho=Integer.parseInt(br.readLine()); switch(cho) { case 1:one(); break; case 2:two(); break; case 3:System.exit(0); default:System.out.println(“nInvalid option..”); } System.out.print(“nContinue with main menu(Y/N):”); conf=(char)br.read(); br.readLine(); }while(conf==’Y’||conf==’y’); } catch(IOException e) { System.out.println(“IOException handled”); } } public void mainFun()throws IOException { try {
  • 171. 171 BufferReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println(“nnDINING PHILOSOPHER PROBLEM”); System.out.println(“nENTER THE TOTAL PHILOSOPHER:”); tph=Integer.parseInt(br.readLine()); System.out.print(“n”); for(i=0;i<tph;i++) { System.out.print(“PHILOSOPHER”+(i+1)+”:”); philname[i]=br.readLine(); status[i]=1; } System.out.print(“nnHow many are hungry:”); howhung=Integer.parseInt(br.readLine()); if(howhung==tph) { System.out.print(“nDO YOU WANT ALL PHILOSOPHER EAT AT A TIME:”); op=(char)br.readLine(); if(op==’y’||op==’Y’) { System.out.println(“nAll are hungry..nDead lock stage will occur”); System.out.println(“nExiting..”); } } else { System.out.print(“n”); for(i=0;i<howhung;i++) { System.out.print(“ENTER PHILOSOPHER”+(i+1)+”POSITION:”);
  • 172. 172 hu[i]=Integer.parseInt(br.readLine()); status[hu[i]]=2; } menu(); } } catch(IOException ex) { System.out.println(“nException caught from mainfun method”); } } } Sample Input and Output: DINING PHILOSOPHER PROBLEM ENTER THE TOTAL PHILOSOPHER:5 PHILOSOPHER 1:a PHILOSOPHER 2:b PHILOSOPHER 3:c PHILOSOPHER 4:d PHILOSOPHER 5:e How many are hungry:3 ENTER PHILOSOPHER 1 POSITION:2 ENTER PHILOSOPHER 2 POSITION:4 ENTER PHILOSOPHER 3 POSITION:5 DINING PHILOSOPHER PROBLEM 1.One can eat at a time 2.Two can eat at a time 3.Exit Enter your choice:1
  • 173. 173 ALLOW ONE PHILOSOPHER TO EAT AT ANY TIME PHILOSOPHER<c>IS GRANTED TO EAT PHILOSOPHER<e>IS WAITING PHILOSOPHER<null>IS WAITING PHILOSOPHER<e>IS GRANTED TO EAT PHILOSOPHER<null>IS WAITING PHILOSOPHER<null>IS GRANTED TO EAT Continue with main menu(Y/N):Y DINING PHILOSOPHER PROBLEM 1.One can eat at a time 2.Two can eat at a time 3.Exit Enter your choice:2 TWO PHILOSOPHER TO EAT AT SAME TIME COMBINATION 1 <c>AND<e>ARE GRANTED TO EAT PHILOSOPHER<null>IS WAITING COMBINATION 2 <c>AND<null>ARE GRANTED TO EAT PHILOSOPHER<e>IS WAITING COMBINATION 3 <e>AND<null>ARE GRANTED TO EAT PHILOSOPHER<c>IS WAITING. Continue with main menu(Y/N):Y DINING PHILOSOPHER PROBLEM 1.One can eat at a time 2.Two can eat at a time 3.Exit Enter your choice:3
  • 174. 174 Result: Thus the java program to implement the Dining philosopher problem was created, executed successfully and the output was verified