Java Lab Manual
Java Lab Manual
2018-19
LABORATORY MANUAL
OF
(R-15 REGULATION)
Prepared by
CSE Page 1
LAB MANUAL CONTENT
Java Programming Laboratory
(15A05405)
Department Vision:
To produce Industry ready Software Engineers to meet the challenges of
21st Century.
Department Mission:
Impart core knowledge and necessary skills in Computer Science and
Engineering through innovative teaching and learning methodology.
CSE Page 2
2. PO, PEO& PSO Statements
CSE Page 3
Program Educational Objectives (PEOs):
PEO 1:Graduates will be prepared for analyzing, designing, developing and testing the
software solutions and products with creativity and sustainability.
PEO 2: Graduates will be skilled in the use of modern tools for critical problem solvingand
analyzing industrial and societal requirements.
PEO 3:Graduates will be prepared with managerial and leadership skills for career and
starting up own firms.
Program Specific Outcomes (PSOs):
PSO 1:Develop creative solutions by adapting emerging technologies / tools for real time
applications.
PSO 2: Apply the acquired knowledge to develop software solutions and innovative mobile
apps for various automation applications
SAT
CSE Page 4
LIST OF EXPERIMENTS (SYLLABUS)
Learn to use object orientation to solve problems and use java language to implement them.
To experiment with the syntax and semantics of java language and gain experience with java
programming
Course Outcomes:
List of Experiments
1. Preparing and practice – Installation of Java software, study of any Integrated development environment,
sample programs on operator precedence and associativity, class and package concept, scope
concept, control structures, constructors and destructors. Learn to compile, debug and execute java
programs.
2. Write Java program(s) on use of inheritance, preventing inheritance using final, abstract classes.
3. Write Java program(s) on dynamic binding, differentiating method overloading and overriding.
4. Write Java program(s) on ways of implementing interface.
5. Write a program for the following
Develop an applet that displays a simple message.
Develop an applet for waving a Flag using Applets and Threads.
6. Write Java program(s) which uses the exception handling features of the language, creates
exceptions and handles them properly, uses the predefined exceptions, and create own exceptions
7. Write java program that inputs 5 numbers, each between 10 and 100 inclusive. As each number is
read display it only if it’s not a duplicate of any number already read. Display the complete set of
unique values input after the user enters each new value.
Write Java program(s) on creating multiple threads, assigning priority to threads, synchronizing threads,
suspend and resume threads
10) Write a java program to split a given text file into n parts. Name each part as the name of the original file
followed by .part<n> where n is the sequence number of the part file.
CSE Page 5
11) Write a java program to create a super class called Figure that receives the dimensions of two
dimensional objects. It also defines a method called area that computes the area of an object. The program
derives two subclasses from Figure. The first is Rectangle and second is Triangle. Each of the sub classes
override area() so that it returns the area of a rectangle and triangle respectively.
12) Write a Java program that creates three threads. First thread displays “Good Morning” every one second,
the second thread displays “Hello” every two seconds and the third thread displays “Welcome” every three
seconds
13) Design a simple calculator which performs all arithmetic operations. The interface should look like the
calculator application of the operating system. Handle the exceptions if any.
14) Write a java program to handle mouse events
15) Write a java program to handle keyboard events
16) Write a java program that allows conduction of object type examination containing multiple choice
questions, and true/false questions. At the end of the examination when the user clicks a button the total
marks have to be displayed in the form of the message.
17) Write a java program that creates menu which appears similar to the menu of notepad application of the
Microsoft windows or any editor of your choice.
18) Write a java program that creates dialog box which is similar to the save dialog box of the Microsoft
windows or any word processor of your choice.
19) Write a Java program that correctly implements producer consumer problem using the concept of inter
thread communication
20) Write a java program to find and replace pattern in a given file.
21).Use inheritance to create an exception super class called ExceptionA and exception sub classes
ExceptionB and ExceptionC, where ExceptionB inherits from ExceptionA and ExceptionC inherits from
ExceptionB. Write a java Program to demonstrate that the catch block for type ExceptionA catches exception
of type ExceptionB and ExceptionC.
22)Write a Java program which opens a connection to standard port on well known server, sends the data
using socket and prints the returned data.
23)Write a Java program to create a URLConnection and use it to examine the documents properties and
content.
24)Write a Java program which uses TCP/IP and Datagrams to communicate client and server.
25)Create an interface for stack with push and pop operations. Implement the stack in two ways: fixed
size stack and Dynamic stack (stack size is increased when stack is full).
26)Create multiple threads to access the contents of a stack. Synchronize thread to prevent simultaneous
access to push and pop operations.
References:
CSE Page 6
1. CO-PO Attainment
CSE Page 7
SVR ENGINEERING COLLEGE
DEPARTMENT COMPUTER SCIENCE & ENGINEERING
PO-
ATTAINME
NT
P P P P P P
O O O O O O PO PO PO PS PS
PO1 2 PO3 PO4 5 6 7 8 9 10 11 12 O1 O2
15A054
05.1 9 9 6 6 3 6 3 3 6 9 3
INTERNAL
15A054
05.2 9 6 3 3 3 3 3 6 6
15A054
05.3 9 9 6 6 6 3 3 3 6 3
15A054
05.4 9 9 3 6 6 6 6 6 6 6
CSE Page 8
15A054
05.5 9 6 6 6 6 6 3 9 3
15A051
02.1 9 9 6 6 3 6 3 3 6 9 3
15A051
UNIVERSITY
02.2 9 6 3 3 3 3 3 6 6
15A051
02.3 9 9 6 6 6 3 3 3 6 3
15A051
02.4 9 9 3 6 6 6 6 6 6 6
15A051
02.5 9 6 6 6 6 6 3 9 3
15A051
02.1 3 3 3 3 3 3 3 3 3 3 3
15A051
02.2 3 3 3 3 3 3 3 3 3
OVERALL
15A051
02.3 3 3 3 3 3 3 3 3 3 3
15A051
02.4 3 3 3 3 3 3 3 3 3 3
15A051
02.5 3 3 3 3 3 3 3 3 3
Attainment 3 3 3 3 3 3 3 3 3 3 3 3 3 3
CSE Page 9
TITLE: Install and Execute Java Programs SVRE/CSE/EXPT-JAVA1/21
Program 1(a):
Aim: Preparing and practice – Installation of Java software, study of any Integrated
development environment.
Installing JDK is first step in learning Java Programming. If you are using Windows 8 or
Windows 7 Operating System, than installing JDK is quite easy as you just need to follow
instruction given by Java SE Installation wizard. Only thing which requires some attention is,
choosing correct JDK installer based upon, whether you are running with 32-bit or 64-bit
Windows 8 or Windows 7 OS. JDK 7 is latest Java version but JDK 6 is still most popular in
software and programming world. You can choose to install JDK 7 or JDK 6 based upon your
course material. In this Java tutorial, we will learn how to install JDK 7 in Windows 8
operating system by following step by step guide. Another thing, which is part of JDK
installation is setting PATH for Java in Windows 8, this will enable to run javac and java
command from any directory in Windows 8. See that link for step by step guide on setting PATH
in Windows 8. Though, I will use Windows 8 operating system to install JDK 7, You can
still install JDK 6 or 7 in Windows 7 by following those steps. In order to choose correct JDK
installer, we first need to check if Windows is running with 32-bit or 64-bit Windows 8. For that
you can go to Control Panel-->System and Security and check System Type, if it shows 32-bit
operating system means you need Windows x86 Java Installer, if it shows 64-bit operating system
than you need Windows x64 Java Installer. Let's see steps involved to install JDK 6 or JDK 7 in
Windows 8 operating system.
A Java IDE (Integrated Development Environment) is a software application which enables users
to more easily write and debug Java programs. Many IDEs provide features like syntax
highlighting and code completion, which help the user to code more easily.
Eclipse is a Free and Open Source IDE, plus a developer tool framework that can be extended for a
particular development need. IBM was behind its development, and it replaced IBM VisualAge tool.
The idea was to create a standard look and feel that can be extended via plugins. The extensibility
distinguishes Eclipse from other IDEs. Eclipse was also meant to compete with Microsoft Visual
Studio tools. Microsoft tools give a standard way of developing code in the Microsoft world. Eclipse
gives a similar standard way of developing code in the Java world, with a big success so far. With the
online error checking only, coding can be sped up by at least 50% (coding does not include
programming).
The goals for Eclipse are twofold:
Program 1(b):
Output:
# java Precedence
9
7
4
--
2
1
6
--
5
2
15
Program 1(c):
Aim: Write a Java Program to calculate Area of Rectangle using classes
Program:
class Rectangle {
double length;
double breadth;
CSE Page 11
}
}
public static void main(String[] args)
{
constructoremp e=new constructoremp();
e.disp();
}
}
output:-
emp id=111
emp name=HARI
CSE Page 12
TITLE: Inheritance Concept SVRE/CSE/EXPT-JAVA/2/21
Program 2(a):
CSE Page 13
Program 2(b):
Aim: write a Java Program Using final to Prevent Inheritance.
Program:
When a class is declared as final then it cannot be subclassed i.e. no any other class can extend it. This
is particularly useful, for example, when creating an immutable class like the predefined String class.
The following fragment illustrates final keyword with a class:
final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
}
Program 3(a)
Aim: To write a Java program for implementing Method Overloading
Program:
class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:-
a
a 10
CSE Page 14
Program 3)b):
Aim: To write a Java program for implementing Method Overriding
Program:
class Parent
{
void show() { System.out.println("Parent's show()"); }
}
// Inherited class
class Child extends Parent
{
// This method overrides show() of Parent
@Override
void show() { System.out.println("Child's show()"); }
}
// Driver class
class Main
{
public static void main(String[] args)
{
// If a Parent type reference refers
// to a Parent object, then Parent's
// show is called
Parent obj1 = new Parent();
obj1.show();
Output:
Parent's show()
Child's show()
CSE Page 15
TITLE: Interface SVRE/CSE/EXPT-JAVA/4/21
Program 4)a):
Aim: Write a Java program on implementing interface
Program:
interface MyInterface
{
/* compiler will treat them as:
* public abstract void method1();
* public abstract void method2();
*/
public void method1();
public void method2();
}
class Demo implements MyInterface
{
/* This class must have to implement both the abstract methods
* else you will get compilation error
*/
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");
}
public static void main(String arg[])
{
MyInterface obj = new Demo();
obj.method1();
}
}
Output:
implementation of method1
Program 4(b):
Aim: Write a Java program(s) on ways of implementing interface.
.
Program:
import java.io.*;
interface Vehicle {
// all are the abstract methods.
void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}
CSE Page 16
class Bicycle implements Vehicle{
int speed;
int gear;
// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
speed = speed + increment;
}
// to decrease speed
@Override
public void applyBrakes(int decrement){
speed = speed - decrement;
}
public void printStates() {
System.out.println("speed: " + speed
+ " gear: " + gear);
}
}
class Bike implements Vehicle {
int speed;
int gear;
// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
speed = speed + increment;
}
// to decrease speed
@Override
public void applyBrakes(int decrement){
speed = speed - decrement;
}
public void printStates() {
System.out.println("speed: " + speed
+ " gear: " + gear);
}
}
class GFG {
public static void main (String[] args) {
// creating an inatance of Bicycle
// doing some operations
CSE Page 17
Bicycle bicycle = new Bicycle();
bicycle.changeGear(2);
bicycle.speedUp(3);
bicycle.applyBrakes(1);
System.out.println("Bicycle present state :");
bicycle.printStates();
// creating instance of bike.
Bike bike = new Bike();
bike.changeGear(1);
bike.speedUp(4);
bike.applyBrakes(3);
System.out.println("Bike present state :");
bike.printStates();
}
}
Output;
Bicycle present state :
speed: 2 gear: 2
Bike present state :
speed: 1 gear: 1
Program:
import java.applet.*;
import java.awt.*;
public class FA extends Applet
{
private int w, h;
public void init()
{
w = 45;
h = 50;
}
CSE Page 18
Program:-
//<applet code="Flag.class" height=300 width=300></applet>
Program 6:
Aim
Write Java program(s) which uses the exception handling features of the language, creates exceptions and
handles them properly, uses the predefined exceptions, and create own exceptions
Program:
Examples of Built-in Exception:
• Arithmetic exception
// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
• Output:
Can't divide a number by 0
• NullPointer Exception
//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
• Output:
NullPointerException..
• StringIndexOutOfBound Exception
// Java program to demonstrate StringIndexOutOfBoundsException
CSE Page 20
class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}
• Output:
StringIndexOutOfBoundsException
• FileNotFound Exception
//Java program to demonstrate FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
CSE Page 21
}
}
• Output:
Number format exception
• ArrayIndexOutOfBounds Exception
// Java program to demonstrate ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo
{
public static void main(String args[])
{
try{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of Bounds");
}
}
}
• Output:
Array Index is Out Of Bounds
// Java program to demonstrate user defined exception
// default constructor
MyException() { }
// parametrized constructor
MyException(String str) { super(str); }
// write main()
public static void main(String[] args)
{
try {
// display the heading for the table
System.out.println("ACCNO" + "\t" + "CUSTOMER" +
"\t" + "BALANCE");
CSE Page 22
// display the actual account information
for (int i = 0; i < 5 ; i++)
{
System.out.println(accno[i] + "\t" + name[i] +
"\t" + bal[i]);
catch (MyException e) {
e.printStackTrace();
}
}
}
Output:-
ACCNO CUSTOMER BALANCE
1001 Nish 10000.0
1002 Shubh 12000.0
1003 Sush 5600.0
1004 Abhi 999.0
MyException: Balance is less than 1000
Program 7:
Aim:
Write java program that inputs 5 numbers, each between 10 and 100 inclusive. As each number is read
display it only if it’s not a duplicate of any number already read. Display the complete set of unique values
input after the user enters each new value.
Program:
import java.util.Scanner;
r++;
}
}
else
{
System.out.println("value must be in between 10 & 100");
j--;
}
}
System.out.print("The five unique values are ");
for(i=0;i<5;i++)
{
System.out.print(a[i]+" ");
}
Output:-
Enter 5 unique values between 10 & 100
0
value must be in between 10 & 100
10
20
10
Duplicate value found retry
30
CSE Page 24
40
50
The five unique values are 10 20 30 40 50
Program 8:
Aim:
Write Java program(s) on creating multiple threads, assigning priority to threads, synchronizing threads.
B t2 = new B();
t2.start();
B t3 = new B();
t3.start();
}
Output : When you compile and execute the program the output will be as below
CSE Page 25
public void run()
{
System.out.println("Inside run method");
}
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);
// Main thread
System.out.print(Thread.currentThread().getName());
System.out.println("Main thread priority : "
+ Thread.currentThread().getPriority());
Output:
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
Main thread priority : 5
Main thread priority : 10
CSE Page 26
example of multi threading with synchronized.
// A Java program to demonstrate working of synchronized.
import java.io.*;
import java.util.*;
// A Class used to send a message
class Sender
{
public void send(String msg)
{
System.out.println("Sending\t" + msg );
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}
// Class for send a message using Threads
class ThreadedSend extends Thread
{
private String msg;
private Thread t;
Sender sender;
// Recieves a message object and a string
// message to be sent
ThreadedSend(String m, Sender obj)
{
msg = m;
sender = obj;
}
Output:
Sending Hi
Hi Sent
Sending Bye
Bye Sent
CSE Page 28
TITLE: split a given text file into n parts SVRE/CSE/EXPT-OS/9/21
Program 9:
Aim:
Write a java program to split a given text file into n parts. Name each part as the name of the original file
followed by .part<n> where n is the sequence number of the part file.
Program:
import java.io.*;
import java.util.Scanner;
public class Split {
public static void main(String args[])
{
try{
// Reading file and getting no. of files to be generated
String inputfile = "D:\\test.txt"; // Source File Name.
double nol = 2000.0; // No. of lines to be split and saved in each output file.
File file = new File(inputfile);
Scanner scanner = new Scanner(file);
int count = 0;
while (scanner.hasNextLine())
{
scanner.nextLine();
count++;
}
System.out.println("Lines in the file: " + count); // Displays no. of lines in the input file.
//---------------------------------------------------------------------------------------------------------
CSE Page 29
for (int j=1;j<=nof;j++)
{
FileWriter fstream1 = new FileWriter("C:/New Folder/File"+j+".txt"); // Destination File Location
BufferedWriter out = new BufferedWriter(fstream1);
for (int i=1;i<=nol;i++)
{
strLine = br.readLine();
if (strLine!= null)
{
out.write(strLine);
if(i!=nol)
{
out.newLine();
}
}
}
out.close();
}
in.close();
}catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}
CSE Page 30
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
Program 11:
Aim: Write a Java program that creates three threads. First thread displays “Good Morning” every one
second, the second thread displays “Hello” every two seconds and the third thread displays “Welcome”
every three seconds.
Program:
class A extends Thread
{
synchronized public void run()
{
try
{
while(true)
CSE Page 31
{
sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{ }
}
}
class B extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{ }
}
}
class C extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{ }
}
}
class ThreadDemo
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
CSE Page 32
t1.start();
t2.start();
t3.start();
}
}
OUTPUT:-
good morning
good morning
hello
welcome
good morning
hello
good morning
good morning
hello
welcome
good morning
good morning
hello
good morning
welcome
good morning
hello
good morning
good morning
welcome
hello
good morning
good morning
hello
good morning
welcome
good morning
hello
CSE Page 33
TITLE: simple calculator SVRE/CSE/EXPT-OS/12/21
12)
AIM:- Design a simple calculator which performs all arithmetic operations .
Program:- import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
float a, b, res;
char choice, ch;
Scanner scan = new Scanner(System.in);
do
{
System.out.print("1. Addition\n");
System.out.print("2. Subtraction\n");
System.out.print("3. Multiplication\n");
System.out.print("4. Division\n");
System.out.print("5. Exit\n\n");
System.out.print("Enter Your Choice : ");
choice = scan.next().charAt(0);
switch(choice)
{
case '1' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a + b;
System.out.print("Result = " + res);
break;
case '2' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a - b;
System.out.print("Result = " + res);
break;
case '3' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a * b;
System.out.print("Result = " + res);
break;
case '4' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a / b;
System.out.print("Result = " + res);
break;
case '5' : System.exit(0);
break;
CSE Page 34
default : System.out.print("Wrong Choice!!!");
break;
}
System.out.print("\n---------------------------------------\n");
}while(choice != 5);
}
}
OUTPUT:-
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
CSE Page 35
TITLE: Mouse events. SVRE/CSE/EXPT-JAVA/13/21
Date: 01-01- 2018
13)
AIM:-Write a java program to handle mouse events.
Program:-
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
CSE Page 36
}
public void mouseDropped(MouseEvent me)
{
msg=” mouse dropped”;
repaint();
}
public void mouseDragged(MouseEvent me)
{
msg=” mouse dragged”;
repaint();
}
}
HTML Code
<html>
<title>Keyboard Events</title>
<Body><Applet code=”MouseEvents.class” height=100 width=700></applet>
</body>
</html>
Output:-
F:\>javac MouseEvents.java
F:\>appletviewer MouseEvents.html
CSE Page 37
TITLE: keyboard events SVRE/CSE/EXPT-OS/14/21
Date: 01-01- 2018
14)
AIM:- Write a java program to handle keyboard events
Program:-
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="Key" width=300 height=400>
</applet>
*/
public class Key extends Applet
implements KeyListener
{
int X=20,Y=30;
String msg="KeyEvents--->";
public void init()
{
addKeyListener(this);
requestFocus();
setBackground(Color.green);
setForeground(Color.blue);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyDown");
int key=k.getKeyCode();
switch(key)
{
case KeyEvent.VK_UP:
showStatus("Move to Up");
break;
case KeyEvent.VK_DOWN:
showStatus("Move to Down");
break;
case KeyEvent.VK_LEFT:
showStatus("Move to Left");
break;
case KeyEvent.VK_RIGHT:
showStatus("Move to Right");
break;
}
repaint();
}
public void keyReleased(KeyEvent k)
{
CSE Page 38
showStatus("Key Up");
}
public void keyTyped(KeyEvent k)
{
msg+=k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
Output:-
AIM:
15) Write a java program that creates dialog box which is similar to the save dialog box of the Microsoft
windows or any word processor of your choice.
PROGRAM:-
// Demonstrate Dialog box.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="DialogDemo" width=250 height=250>
</applet>
*/
// Create a subclass of Dialog.
class SampleDialog extends Dialog implements ActionListener {
SampleDialog(Frame parent, String title) {
super(parent, title, false);
setLayout(new FlowLayout());
setSize(300, 200);
add(new Label("Press this button:"));
Button b;
add(b = new Button("Cancel"));
b.addActionListener(this);
CSE Page 39
}
public void actionPerformed(ActionEvent ae) {
dispose();
}
public void paint(Graphics g) {
g.drawString("This is in the dialog box", 10, 70);
}
}
// Create a subclass of Frame.
class MenuFrame extends Frame {
String msg = "";
CheckboxMenuItem debug, test;
MenuFrame(String title) {
super(title);
// create menu bar and add it to frame
MenuBar mbar = new MenuBar();
setMenuBar(mbar);
// create the menu items
Menu file = new Menu("File");
MenuItem item1, item2, item3, item4;
file.add(item1 = new MenuItem("New..."));
file.add(item2 = new MenuItem("Open..."));
file.add(item3 = new MenuItem("Close"));
file.add(new MenuItem("-"));
file.add(item4 = new MenuItem("Quit..."));
mbar.add(file);
CSE Page 43
edit.add(item9 = new MenuItem("-"));
Menu sub = new Menu("Special");
MenuItem item10, item11, item12;
sub.add(item10 = new MenuItem("First"));
sub.add(item11 = new MenuItem("Second"));
sub.add(item12 = new MenuItem("Third"));
edit.add(sub);
// these are checkable menu items
debug = new CheckboxMenuItem("Debug");
edit.add(debug);
test = new CheckboxMenuItem("Testing");
edit.add(test);
mbar.add(edit);
// create an object to handle action and item events
MyMenuHandler handler = new MyMenuHandler(this);
// register it to receive those events
item1.addActionListener(handler);
item2.addActionListener(handler);
item3.addActionListener(handler);
item4.addActionListener(handler);
item5.addActionListener(handler);
item6.addActionListener(handler);
item7.addActionListener(handler);
item8.addActionListener(handler);
item9.addActionListener(handler);
item10.addActionListener(handler);
item11.addActionListener(handler);
item12.addActionListener(handler);
debug.addItemListener(handler);
test.addItemListener(handler);
// create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);
}
public void paint(Graphics g) {
g.drawString(msg, 10, 200);
if(debug.getState())
g.drawString("Debug is on.", 10, 220);
else
g.drawString("Debug is off.", 10, 220);
if(test.getState())
g.drawString("Testing is on.", 10, 240);
else
g.drawString("Testing is off.", 10, 240);
}
}
class MyWindowAdapter extends WindowAdapter {
CSE Page 44
MenuFrame menuFrame;
public MyWindowAdapter(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
public void windowClosing(WindowEvent we) {
menuFrame.setVisible(false);
}
}
class MyMenuHandler implements ActionListener, ItemListener {
MenuFrame menuFrame;
public MyMenuHandler(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
// Handle action events.
public void actionPerformed(ActionEvent ae) {
String msg = "You selected ";
String arg = ae.getActionCommand();
if(arg.equals("New..."))
msg += "New.";
else if(arg.equals("Open..."))
msg += "Open.";
else if(arg.equals("Close"))
msg += "Close.";
else if(arg.equals("Quit..."))
msg += "Quit.";
else if(arg.equals("Edit"))
msg += "Edit.";
else if(arg.equals("Cut"))
msg += "Cut.";
else if(arg.equals("Copy"))
msg += "Copy.";
else if(arg.equals("Paste"))
msg += "Paste.";
else if(arg.equals("First"))
msg += "First.";
else if(arg.equals("Second"))
msg += "Second.";
else if(arg.equals("Third"))
msg += "Third.";
else if(arg.equals("Debug"))
msg += "Debug.";
else if(arg.equals("Testing"))
msg += "Testing.";
menuFrame.msg = msg;
menuFrame.repaint();
}
// Handle item events.
public void itemStateChanged(ItemEvent ie) {
CSE Page 45
menuFrame.repaint();
}
}
// Create frame window.
public class MenuDemo extends Applet {
Frame f;
public void init() {
f = new MenuFrame("Menu Demo");
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
setSize(new Dimension(width, height));
f.setSize(width, height);
f.setVisible(true);
}
public void start() {
f.setVisible(true);
}
public void stop() {
f.setVisible(false);
}
}
TITLE: producer consumer problem in Java SVRE/CSE/EXPT-OS/17/21
AIM:
17)Write a Java program that correctly implements producer consumer problem using the concept of
inter thread communication
PROGRAM:
// Java program to implement solution of producer
// consumer problem.
import java.util.LinkedList;
CSE Page 46
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
// t1 finishes before t2
t1.join();
t2.join();
}
System.out.println("Producer produced-"
+ value);
CSE Page 48
// and sleep
Thread.sleep(1000);
}
}
}
}
}
Output:
Producer produced-0
Producer produced-1
Consumer consumed-0
Consumer consumed-1
Producer produced-2
AIM:
18) Write a java program to find and replace pattern in a given file.
Program:
import java.io.*;
OutPut:
I drink Java
I sleep Java
AIM:-
19)Use inheritance to create an exception super class called EexceptionA and exception sub class
ExceptionB and ExceptionC, where ExceptionB inherits from ExceptionA and ExceptionC inherits from
ExceptionB. Write a java program to demonstrate that the catch block for type ExceptionA catches
exception of type ExceptionB and ExceptionC.
Program:
class ExceptionsA{
static void genException(){
int num[]= {4,8,16,32,64,128,256};
CSE Page 50
}
catch (ArithmeticException zero){
System.out.printf("%s",zero);
}
catch (ArrayIndexOutOfBoundsException array){
System.out.printf("%s",array);
}//end catch
}//end class
}//end method
Output:-
4/2is2
8/2is4
16/4is4
32/4is8
java.lang.ArithmeticException: / by zero
TITLE: java program to create a URL Connection in Java SVRE/CSE/EXPT-OS/20/21
AIM:-
20)write a java program to create a URLConnection and use it to examine the documents properties and
content
Program:-
// Demonstrate URLConnection.
import java.net.*;
import java.io.*;
import java.util.Date;
class UCDemo
{
public static void main(String args[]) throws Exception {
int c;
URL hp = new URL("http://www.java.com");
URLConnection hpCon = hp.openConnection();
System.out.println("Date: " + new Date(hpCon.getDate()));
System.out.println("Content-Type: " +
hpCon.getContentType());
System.out.println("Expires: " + hpCon.getExpiration());
System.out.println("Last-Modified: " +
new Date(hpCon.getLastModified()));
int len = hpCon.getContentLength();
System.out.println("Content-Length: " + len);
if (len > 0) {
System.out.println("=== Content ===");
InputStream input = hpCon.getInputStream();
int i = len;
while (((c = input.read()) != -1) && (—i > 0)) {
System.out.print((char) c);
}
input.close();
CSE Page 51
} else {
System.out.println("No Content Available");
}
}
}
AIM:-Write a Java Program which uses TCP/IP and Datagrams to communicate client and server.
Program:
import java.io.*;
import java.net.*;
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(6666);
Socket s = ss.accept();// establishes connection
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = (String) dis.readUTF();
System.out.println("message= " + str);
ss.close();
} catch (Exception e) {
System.out.println(e);
}
CSE Page 52
}
}
CSE Page 53