Professional Documents
Culture Documents
AUDISANKARA
INSTITUTE OF TECHNOLOGY
(Affiliated to JNTUA, Approved by AICTE)
NH-5, Bypass Road, Gudur, 524101.
JAVA
LAB MANUAL
1
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
Program1:
AIM: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.
1.1 WORKING WITH ECLIPSE
Java application development is supported by many different tools. One of the most
powerful and helpful tool is the free Eclipse IDE (IDE = Integrated Development
Environment). To download the Eclipse IDE, go to http://www.eclipse.org. Click on
Downloads and then select the most recent stable or release version of the Eclipse SDK for
your PC platform.
Eclipse requires Java to run, so if you don’t already have Java installed on your
machine, first install a Java 6 SDK. Please note: The DIL/NetPC DNP/2486 MAX-Linux
comes with a Java 6 runtime environment. Your PC as a development system needs the same
Java version. You can download Java SDKs from http://java.sun.com. Look for the Java 6
J2SE SDK (Software Development Kit).
1. Step: Download the Eclipse SDK file to a temporary directory. The download file comes
as a .ZIP (e.g. eclipse-SDK-3.4.1-win32.zip). Use your archive program to unpack Eclipse
into a permanent directory (e.g. C:\Program Files\eclipse). Then run the Eclipse launcher
program (e.g. C:\Program Files\eclipse\eclipse.exe) to bring up the IDE.
Because this is your first time running Eclipse, it will take a while to load as it sets up
the environment.
INITIALIZING ECLIPSE:
When you develop Java applications in Eclipse, it stores all the created files in a
directory called "workspace". When Eclipse is run for the first time, it will ask you where
you want the workspace to be placed:
2
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
You can just use the default location or specify your preferred location. To avoid
getting asked this question every time you start Eclipse, check "Use this as the default and do
not ask again" option and press "OK" button. Once Eclipse finishes its startup process, you
will see the following welcome window:
This welcome screen provides information for new users, examples and tutorials.
2. Step: Click to the Workbench icon within the Eclipse Welcome screen. After that you see
the Eclipse main window, also called the workbench.
Please note: The first time you start Eclipse, you will prompted for the location of your
workspace. The workspace is the location where your files and settings will be stored.
3
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
4. Step: In the New Java Project dialog box, first please enter a project name (e.g.
JavaApp1). Then select the Java 6 Run Time Environment (JRE) for this project (see Use a
project specific JRE). Finally press Finish.
Please note: The DIL/NetPC DNP/2486 MAX-Linux comes with a Java 6 runtime
environment. It is necessary to tell Eclipse that this new project is for Java 6.
4
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
5. Step: Please open the Eclipse File menu again. Then select Class to add a new Java class.
This opens the New Java Class dialog box.
6. Step: In the New Java Class dialog box first select the source folder for the class. Then
enter the name HelloWorldfor the new class. Make sure that in the Which method stubs
would you like to create? area the public static void main(String[] args) check box is
checked. Finally press Finish to create the new class.
5
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
7. Step: The Eclipse workbench now contains an editor window with the Java source code
template for the new HelloWorldclass.
Within the Eclipse editor window please replace the following Java source code line
// TODO Auto-generated method stub with
6
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
System.out.println(“Hello World!”);
8. Step: Please choose the Project => Properties menu item and select the compiler
compliance level 1.6 (this compiler level belongs to Java 6) within the Properties for
JavaApp1 dialog box (see JDK Compliance).
7
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
9. Step: Now choose the Run => Run menu item. This starts the execution of your Java
application within the Eclipse IDE. Watch the Hello World! output within the console
window.
Please note: The Java source code of this sample is stored within the file
HelloWorld.java. It is not necessary to compile the source code to the class file
HelloWorld.classover a menu item or a shortcut. The Eclipse IDE compiles automatically
after each file save operation or before a run.
QUITTING ECLIPSE
You can exit eclipse by using any of the following alternatives:
Hit the X in the upper right corner
Select File -> Exit
The executable HelloWorld.classclass file is located in the bin directory of your project
(in this sample the directory …\workspace\JavaApp1\bin). Please transfer this new class file
to the DNP/2486.
8
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
1.2:Operator Precedence
SOURCE CODE:
publicclass Precedence{
public static void main(String args[]){
System.out.println(3*3*2);
System.out.println(3*3-2);
System.out.println(3*3/2);
System.out.println(“—“);
System.out.println(1*1+1*1);
System.out.println(1+1/1-1);
System.out.println(3*3/2*2);
System.out.println(“—“);
int x=1;
System.out.println(x++ + x++ * --x);
X=1;
System.out.println(x<<1*2>>1);
X=0xf;
System.out.println(0xf & ox5 | oxa);
}
}
Output:
9
7
4
--
2
1
6
--
5
2
15
Program 2:
9
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
AIM: Write Java program(s) on use of inheritance, preventing inheritance using final, abstract
classes.
2.1:Implementing Inheritance
SOURCE CODE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
SOURCE CODE:
SOURCE CODE:
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}
class TestBank{
public static void main(String args[]){
10
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
Output:
Rate of Interest is: 7 %
Rate of Interest is: 8 %
Program 3:
AIM: Write Java program(s) on dynamic binding, differentiating method overloading and overriding.
3.1:Dynamic Binding
SOURCE CODE:
class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");}
3.2:Method Overloading
SOURCE CODE:
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. System.out.println(Adder.add(12.3,12.6);
10. }
11
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
11. }
Output:
22
33
24.9
3.3:Method Overloading
SOURCE CODE:
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike2 extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6.
7. public static void main(String args[]){
8. Bike2 obj = new Bike2();
9. obj.run();
10. }
Output:
Output:Bike is running safely
SOURCE CODE:
1. interface printable{
2. void print();
3. }
4. class A implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A obj = new A();
9. obj.print();
10. }
11. }
12
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
Output:
Hello
Program 5:Creating Applet
SOURCE CODE:
1. //First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Output:
SOURCE CODE:
import java.io.*;
importjava.applet.*;
importjava.awt.*;
public class flag extends Applet
13
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
{
public void paint(Graphics g)
{
g.fillOval(60,450,120,50);
g.fillRect(110,60,10,400);
g.setColor(Color.red);
g.fillRect(120,80,150,30);
g.setColor(Color.white);
g.fillRect(120,110,150,30);
g.setColor(Color.green);
g.fillRect(120,140,150,30);
g.setColor(Color.black);
g.drawRect(120,80,150,90);
g.setColor(Color.blue);
g.drawOval(180,110,30,30);
int t=0;
int x=195,y=125;
double x1,y1;
double r=15;
double d;
for(inti=1;i<=24;i++)
{
d=(double)t*3.14/180.0;
x1=x+(double)r*Math.cos(d);
y1=y+(double)r*Math.sin(d);
g.drawLine(x,y,(int)x1,(int)y1);
t+=360/24;
}
}
}
ss.html
<title>Keyboard Events</title>
<html>
<Body><Applet code="flag.class" height=100 width=700></applet>
</body>
</html>
Compile:javac flag.java
Running:appletviewer ss.html
14
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
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
(i)
Exception handling program
SOURCE CODE:
class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
15
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
}
finally{System.out.println("finally block is always executed");}
}
}
Output:
(ii)
SOURCE CODE:
importjava.util.Scanner;
classMyException extends Exception
{
privateint ex;
MyException(int a)
{
ex=a;
}
public String toString()
{
return "MyException[" + ex +"] is less than zero";
}
}
class Test
{
static void sum(inta,int b) throws MyException
{
if(a<0)
{
throw new MyException(a);
}
else
{
System.out.println(“No Exception”);
System.out.println(“sum=”+(a+b));
}
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("enter a,b value ");
16
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
int a = scanner.nextInt();
int b = scanner.nextInt();
try
{
sum(a, b);
}
catch(MyException me)
{
System.out.println(me);
}
}
}
Output:
C:\>java Test
entera,b value 10 10
No Exception
Sum=20
C:\>java Test
entera,b value -10 10
MyException[-10] is less than zero
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.
SOURCE CODE:
importjava.util.*;
classNum
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Intsid[] = new int[5];
int count = 0;
int x = 0;
intnum = 0;
while (x <sid.length)
{
System.out.println("Enter number: ");
num = input.nextInt();
if ((num>= 10) && (num<= 100))
{
boolean digit = false;
x++;
for (inti = 0; i<sid.length; i++)
{
if (sid[i] == num)
digit = true;
17
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
}
if (!digit) {
sid[count] = num;
count++;
}
else
System.out.printf("the number was entered before \n");
}
else
System.out.println("number must be between 10 and 100");
for (inti =0; i< x; i++) {
if(sid[i]!=0)
System.out.print(sid[i] +" ");
}
System.out.println();
}//while
} //main
}//class
OUTPUT:
C:\>java Dice
Enter number:
11
11
Enter number:
23
11 23
Enter number:
33
11 23 33
Enter number:
11
the number was entered before
11 23 33
Enter number:
44
11 23 33 44
C:\>java Dice
Enter number:
11
11
Enter number:
22
11 22
Enter number:
33
18
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
11 22 33
Enter number:
44
11 22 33 44
Enter number:
55
11 22 33 44 55
Program 8:Creating Multiple Threads
AIM: Write Java program(s) on creating multiple threads, assigning priority to threads, synchronizing
threads, suspend and resume threads
SOURCE CODE:
(ii)priority of a Thread:
SOURCE CODE:
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
19
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
(iii)Synchronizing threads
SOURCE CODE:
classCallme
{
void call(String msg){
System.out.println(“[“+msg);
try{
Thread.sleep(1000);
}
Catch(InterruptedException e){
System.out.println(“interrupted);
}
System.out.println(“]”);
}}
class Caller implements Runnable{
String msg;
Callme target;
Thread t;
public Caller (Callmetarg,String s){
target=targ;
msg=s;
t=new thread(this);
t.start();
}
//Synchronize calls to call()
public void run(){
Synchronized(target){
target.call(msg);
}
}
}
class Synch1{
public static void main(string args[])
{
Callme target=new Callme(target,”Hello”);
Callme target=new Callme(target,”Synchronised”);
Callme target=new Callme(target,”world”);
//wait for threads to end
try{
obj1.t.join();
obj2.t.join();
obj3.t.join();
}
catch(InterruptedException e){
System.out.println(“Interrputed”);
}
}
}
Output:
[Hello
]
[World
]
[Synchronized
]
20
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
SOURCE CODE:
Output:
Newthread:Thread[one,5,main]
One:15
New thread:Thread[Two,5,main]
Two:15
One:14
Two:14
21
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
One:13
Two:13
One:12
Two:12
One:11
Two:11
Suspending thread One
Two:10
Two:9
Two:8
Two:7
Two:6
Resuming thread One
Suspending thread Two
One:10
One:9
One:8
One:7
One:6
Resuming thread two
Waiting for threads to finish
Two:5
One:5
Two:4
One:4
Two:3
One:3
Two:2
One:2
Two:1
One:1
Two exiting.
One exiting.
Main thread exiting.
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.
SOURCE CODE:
import java.io.*;
importjava.util.Scanner;
public class Split {
public static void main(String args[]) {
try{
// Reading file and getting no. of files to be generated
String inputfile = "test.txt"; // Source File Name.
// No. of lines to be split and saved in each output file.
doublenol = 5.0;
File file = new File(inputfile);
Scanner scanner = new Scanner(file);
int count = 0;
while (scanner.hasNextLine())
{
scanner.nextLine();
count++;
22
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
Create test.text file with some content in same folder before executing
23
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
AIM: 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
24
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
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.
SOURCE CODE:
class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
double area() {
System.out.println("Area for Figure is undefined.");
return 0;
}
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
classFindAreas {
public static void main(String args[]) {
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}
25
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
}
OUTPUT:
Inside Area for Rectangle.
Area is 45.0
Inside Area for Triangle.
Area is 40.0
Area for Figure is undefined.
Area is 0.0
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
Source Code:
import java.lang.*;
import java.util.*;
import java.awt.*;
class One implements Runnable
{
One()
{
new Thread(this,"one").start();
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
}
}
public void run()
{
for(;;)
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
}
System.out.println("GOOD MORNING");
}
}
}
class Two implements Runnable
{
26
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
Two()
{
new Thread(this,"two").start();
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
}
public void run()
{
for(;;)
{
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
System.out.println("HELLO");
}
}
}
class Three implements Runnable
{
Three()
{
new Thread(this,"Three").start();
try
{
Thread.sleep(3000);
}
catch(InterruptedException e)
{
}
}
public void run()
{
for(;;)
{
try
{
Thread.sleep(3000);
}
catch(InterruptedException e)
{
27
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
}
System.out.println("WELCOME");
}
}
}
class MyThread
{
public static void main(String args[])
{
One obj1=new One();
Two obj2=new Two();
Three obj3=new Three();
}
}
Output:
good morning
good morning
hello
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
good morning
hello
good morning
Welcome
good morning
hello
AIM: 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.
28
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
SOURCE CODE:
Calculator.java
importjavax.swing.*;
importjava.awt.*;
importjava.awt.event.*;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Calculator Demo");
setResizable(false);
setSize(300,300);
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Calculator();
}
});
}
}
CalculatorPanel.java
importjavax.swing.*;
importjava.awt.*;
importjava.awt.event.*;
public class CalculatorPanel extends JPanel implements ActionListener
{
JButton n1, n2, n3, n4, n5, n6, n7, n8, n9, n0, plus, minus, mul, div, dot, equal;
staticJTextField result = new JTextField("0", 45);
static String lastCommand ="";
JOptionPane p = new JOptionPane();
doublepreRes = 0, secVal = 0, res;
private static void assign(String no)
{
if ((result.getText()).equals("0"))
{
result.setText(no);
}
else if (lastCommand.equals("="))
29
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
{
result.setText(no);
lastCommand ="";
}
else
{
result.setText(result.getText() + no);
}
}
publicCalculatorPanel()
{
setLayout(new BorderLayout());
result.setEditable(false);
result.setSize(300, 200);
add(result, BorderLayout.NORTH);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
n7 = new JButton("7");
panel.add(n7);
n7.addActionListener(this);
n8 = new JButton("8");
panel.add(n8);
n8.addActionListener(this);
n9 = new JButton("9");
panel.add(n9);
n9.addActionListener(this);
div = new JButton("/");
panel.add(div);
div.addActionListener(this);
n4 = new JButton("4");
panel.add(n4);
n4.addActionListener(this);
n5 = new JButton("5");
panel.add(n5);
n5.addActionListener(this);
n6 = new JButton("6");
panel.add(n6);
n6.addActionListener(this);
mul = new JButton("*");
pel.add(mul);
mul.addActionListener(this);
n1 = new JButton("1");
panel.add(n1);
n1.addActionListener(this);
n2 = new JButton("2");
panel.add(n2);
n2.addActionListener(this);
n3 = new JButton("3");
30
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
panel.add(n3);
n3.addActionListener(this);
minus = new JButton("-");
panel.add(minus);
minus.addActionListener(this);
dot = new JButton(".");
panel.add(dot);
dot.addActionListener(this);
n0 = new JButton("0");
panel.add(n0);
n0.addActionListener(this);
equal = new JButton("=");
panel.add(equal);
equal.addActionListener(this);
plus = new JButton("+");
panel.add(plus);
plus.addActionListener(this);
add(panel, BorderLayout.CENTER);
}
public void actionPerformed(ActionEventae)
{
if (ae.getSource() == n1)
{
assign("1");
}
else if (ae.getSource() == n2)
{
assign("2");
}
else if (ae.getSource() == n3)
{
assign("3");
}
else if (ae.getSource() == n4)
{
assign("4");
}
else if (ae.getSource() == n5)
{
assign("5");
}
else if (ae.getSource() == n6)
{
assign("6");
}
else if (ae.getSource() == n7)
{
assign("7");
}
31
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
}
result.setText(" " + res);
lastCommand = "=";
}
else if (ae.getSource() == mul)
{
preRes = Double.parseDouble(result.getText());
lastCommand = "*";
result.setText("0");
}
else if (ae.getSource() == plus)
{
preRes = Double.parseDouble(result.getText());
lastCommand = "+";
result.setText("0");
}
}
}
Output:
SOURCE CODE:
importjava.awt.*;
importjava.awt.event.*;
importjava.applet.*;
/*<applet code=MouseEvents"width=300 height=100>
* </applet>
*/
publicclassMouseEventsextends Applet implementsMouseListener,MouseMotionListener{
String msg="";
intmouseX=0,mouseY=0;
publicvoidinit()
{
addMouseListener(this);
addMouseMotionListener(this);
33
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
}
publicvoidmouseClicked(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="Mouse clicked";
repaint();
}
publicvoidmouseEntered(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="Mouse entered";
repaint();
}
publicvoidmouseExited(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="Mouse exited";
repaint();
}
publicvoidmousePressed(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="Mouse Pressed";
repaint();
}
publicvoidmousereleased(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="Mouse Released";
repaint();
}
publicvoidmouseDragged(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="*";
showStatus("Dragging mouse at "+ mouseX +","+ mouseY);
repaint();
}
publicvoidMouseMoved(MouseEvent me){
showStatus("Moving mouse at"+me.getX()+","+me.getY());
}
publicvoid paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}
Output:
34
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
SOURCE CODE:
importjava.awt.*;
importjava.awt.event.*;
importjava.applet.*;
/*<applet code="SimpleKey" width=300 height=100>
* </applet>
*/
publicvoidkeyTyped(KeyEventke)
{
msg+=ke.getKeyChar();
repaint();
}
publicvoid paint(Graphics g)
{
g.drawString(msg, X, Y);
}
}
Output:
AIM: 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
SOURCE CODE:
importjava.awt.*;
importjava.awt.event.*;
importjava.awt.datatransfer.*;
import java.io.*;
public class Editor extends Frame
{
String filename;
TextAreatx;
Clipboard clip = getToolkit().getSystemClipboard();
Editor()
{
setLayout(new GridLayout(1,1));
tx = new TextArea();
add(tx);
MenuBarmb = new MenuBar();
Menu F = new Menu("file");
MenuItem n = new MenuItem("New");
MenuItem o = new MenuItem("Open");
MenuItem s = new MenuItem("Save");
36
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
ReadFile();
}
tx.requestFocus();
}
}
d.close();
}
catch(FileNotFoundExceptionfe)
{
System.out.println("File not Found");
}
catch(IOExceptionioe){}
}
}
Output:
AIM: 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.
SOURCE CODE:
importjava.awt.*;
importjavax.swing.*;
importjava.awt.event.*;
import java.io.*;
40
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
file=new JMenu("File");
file.add(open);
mb=new JMenuBar();
mb.setBounds(0,0,800,20);
mb.add(file);
ta=new JTextArea(800,800);
ta.setBounds(0,20,800,800);
add(mb);
add(ta);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==open){
openFile();
}
}
voidopenFile(){
JFileChooser fc=new JFileChooser();
inti=fc.showOpenDialog(this);
if(i==JFileChooser.APPROVE_OPTION){
File f=fc.getSelectedFile();
String filepath=f.getPath();
displayContent(filepath);
}
}
voiddisplayContent(String fpath){
try{
BufferedReaderbr=new BufferedReader(new FileReader(fpath));
String s1="",s2="";
while((s1=br.readLine())!=null){
s2+=s1+"\n";
}
ta.setText(s2);
br.close();
}catch (Exception e) {e.printStackTrace(); }
}
public static void main(String[] args) {
OpenMenuom=new OpenMenu();
om.setSize(800,800);
41
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
om.setLayout(null);
om.setVisible(true);
om.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:
C:\ss>javac OpenMenu.java
C:\ss>java OpenMenu
42
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
AIM: Write a Java program that correctly implements producer consumer problem using the concept
of inter thread communication
SOURCE CODE:
importjava.util.LinkedList;
public class Threadexample
{
public static void main(String[] args)
throwsInterruptedException
{
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();
// t1 finishes before t2
t1.join();
43
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
t2.join();
}
intval = list.removeFirst();
System.out.println("Consumer consumed-"
+ val);
// and sleep
Thread.sleep(1000);
}
}
}
}
}
C:\ss>javac Threadexample.java
C:\ss>java Threadexample
OutPut:
Producer produced-0
Producer produced-1
Consumer consumed-0
Consumer consumed-1
Producer produced-2
Producer produced-3
Consumer consumed-2
Consumer consumed-3
Producer produced-4
Producer produced-5
Consumer consumed-4
Consumer consumed-5
Producer produced-6
PRESS CTRL+C
C:\ss>-
AIM: Write a Java program to create aURLConnection and use it to examine the documents
properties and content.
SOURCE CODE:
// Demonstrate URLConnection.
import java.net.*;
import java.io.*;
importjava.util.Date;
classUCDemo
{
public static void main(String args[]) throws Exception {
int c;
URL hp = new URL("http://www.java-samples.com/j2me/");
URLConnectionhpCon = hp.openConnection();
System.out.println("Date: " + new Date(hpCon.getDate()));
45
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
System.out.println("Content-Type: " +
hpCon.getContentType());
System.out.println("Expires: " + hpCon.getExpiration());
System.out.println("Last-Modified: " +
new Date(hpCon.getLastModified()));
intlen = hpCon.getContentLength();
System.out.println("Content-Length: " + len);
if (len> 0) {
System.out.println("=== Content ===");
InputStream input = hpCon.getInputStream();
inti = len;
while (((c = input.read()) != -1) && (i> 0)) {
System.out.print((char) c);
}
input.close();
} else {
System.out.println("No Content Available");
}
}
}
Output:
46
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
AIM: Write a Java program which uses TCP/IP and Datagrams to communicate client and server.
SOURCE CODE:
File: MyServer.java
import java.io.*;
import java.net.*;
classMyServer {
public static void main(String[] args) throws Exception
{
ServerSocketss=new ServerSocket(777);
Socket s=ss.accept();//establishes connection
System.out.println("connection established");
OutputStreamou=s.getOutputStream();
PrintStreamps=new PrintStream(ou);
String str="hello client";
ps.println(str);
ps.println("bye");
ps.close();
ss.close();
s.close();
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
classMyClient {
public static void main(String[] args) throws Exception
{
Socket s=new Socket("localhost",777);
InputStream is=s.getInputStream();
BufferedReaderbr=new BufferedReader(new InputStreamReader(is));
String str;
while((str=br.readLine())!=null)
System.out.println("from server"+str);
br.close();
s.close();
}
}
Output:
Take two command prompts
In first cmd prompt Compile server (don’t run it)
In Second cmd prompt Compile client
In first cmd prompt Run server
In second cmd prompt Run client
47
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE
JAVA Lab MANUAL
48
AUDISANKARA INSTITUTE OF TECHNOLOGY ::GUDUR
Department Of CSE