rect1.rect(10,20);
rect2.rect(8);
double areaR, vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 = " +vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 = " +vol);
areaR = rect1.area();
System.out.println("Area of rect1= " +areaR);
areaR = rect2.area();
System.out.println("Area of rect1 = " +areaR);
}
}
Output:
C:New Folder>java lab01a
Volume of mybox1 = 3000.0
Volume of mybox2 = 125.0
Area of rect1= 200.0
Area of rect1 = 64.0
2. Write a JAVA Program to implement Inner class and demonstrate its Access
Protections.
class outer
{
int outdata = 10;
void display()
{
inner inobj = new inner();
System.out.println("Accessing from outer class");
System.out.println("The value of outdata is " +outdata);
System.out.println("The value of indata is " +inobj.indata);
}
class inner
{
int indata = 20;
void inmethod()
{
System.out.println("Accessing from inner class");
System.out.println("The sum of indata & outdata is " +(outdata + indata));
}
}
}
class lab01b
{
public static void main(String args[])
{
outer outobj = new outer();
outobj.display();
outer.inner inobj1 = outobj.new inner();
inobj1.inmethod();
}
}
Output:
C:New Folder>java lab01b
Accessing from outer class
The value of outdata is 10
The value of indata is 20
Accessing from inner class
The sum of indata & outdata is 30
3. Write a JAVA Program to implement Inheritance.
class A
{
int i = 10;
protected int j = 20;
void showij()
{
System.out.println("i = " +i);
System.out.println("j = " +j);
}
}
class B extends A
{
int k = 30;
void showk()
{
System.out.println("k = " +k);
}
void sum()
{
System.out.println("i + j + k = " +(i+j+k));
}
}
class lab02a
{
public static void main(String args[])
{
B subobj = new B();
System.out.println("Contents of Super class accessed using sub class object");
subobj.showij();
System.out.println("Contents of Supter class accessed using sub class object");
subobj.showk();
System.out.println("Sum of i, j, & k accessed using sub class object");
subobj.sum();
}
}
Output:
C:New Folder>java lab02a
Contents of Super class accessed using sub class object
i = 10
j = 20
Contents of Super class accessed using sub class object
k = 30
Sum of i, j, & k accessed using sub class object
i + j + k = 60
4. Write a JAVA Program to implement Exception Handling (Using Nested try catch
and finally).
class Nesttry
{ public static void main(String args[])
{ try
{ int a = args.length;
int b = 42 / a;
System.out.println("a" + "= " + a);
try
{ if(a==1) a = a / (a-a);
if(a==2)
{
int c[] = {1}; c[42] = 99;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array out of bounds" + e) ;
}
finally
{
System.out.println("inside first try");
}
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exp" + e);
}
finally
{ System.out.println("Inside 2nd try");
}
}
}
Output:
C:New Folder>java Nesttry
Arithmetic Expjava.lang.ArithmeticException: / by zero
Inside 2nd try
C:New Folder>java Nesttry 1 3
a= 2
array out of boundsjava.lang.ArrayIndexOutOfBoundsException: 42
inside first try
Inside 2nd try
5. Write JAVA programs which demonstrate utilities of Linked List Class.
// Demonstrate Linked List.
import java.util.*;
class LinkedListDemo
{
public static void main (String args[])
{
// Create a linked list.
Linked List<String> ll = new LinkedList<String>();
// Add elements to the linked list.
ll.add ("F");
ll.add ("B");
ll.add ("D");
ll.add ("E");
ll.add ("C");
ll.addLast ("Z");
ll.addFirst ("A");
ll.add (1, "A2");
System.out.println ("Original contents of ll: " + ll);
// Remove elements from the linked list.
ll.remove ("F");
ll.remove (2);
System.out.println ("Contents of ll after deletion: "+ ll);
// Remove first and last elements.
ll.removeFirst ();
ll.removeLast ();
System.out.println ("ll after deleting first and last: "+ ll);
// Get and set a value. String val = ll.get (2);
ll.set (2, val + “Changed");
System.out.println ("ll after change: " + ll);
}
}
OutPut :
Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]
6. Write JAVA programs which uses FileInputStream/FileOutputStream Classes.
a) FileinputStream
/*FileInStreamDemo.java*/
import java.io.*;
public class FileInStreamDemo
{
public static void main(String[] args)
{
// create file object
File file = new File("DevFile.txt");
int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;
try
{
fin = new FileInputStream(file);
while ((ch = fin.read()) != -1)
strContent.append((char) ch);
fin.close();
}
catch (FileNotFoundException e)
{
System.out.println("File " + file.getAbsolutePath() + " could not be
found on filesystem");
}
catch (IOException ioe)
{
System.out.println("Exception while reading the file" + ioe);
}
System.out.println("File contents :");
System.out.println(strContent);
}
}
OutPut:
C:New Folder>java FileInStreamDemo
File contents :
The text shown here will write to a file after run
b)FileoutputStream
/* Example of FileOutputStream */
import java.io.*;
public class FileOutStreamDemo
{
public static void main(String[] args)
{
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try
{
// Create a new file output stream connected to "DevFile.txt"
out = new FileOutputStream("DevFile.txt");
// Connect print stream to the output stream
p = new PrintStream(out);
p.println("The text shown here will write to a file after run");
System.out.println("The Text is written to DevFile.txt");
p.close();
}
catch (Exception e)
{
System.err.println("Error writing to file");
}
}
}
OutPut:
C:New Folder>java FileOutStreamDemo
The Text is written to DevFile.txt
7. Write a JAVA Program which writes a object to a file (use transient variable also).
import java.util.Vector;
import java.io.*;
public class SerializationTest
{
static long start,end;
OutputStream out = null;
OutputStream outBuffer = null;
ObjectOutputStream objectOut = null;
public Person getObject()
{
Person p = new Person("SID","austin");
Vector v = new Vector();
for(int i=0;i<7000;i++)
{
v.addElement("StringObject:" +i);
}
p.setData(v);
return p;
}
public static void main(String[] args)
{
SerializationTest st = new SerializationTest();
start = System.currentTimeMillis();
st.writeObject();
end = System.currentTimeMillis();
System.out.println("Time taken for writing :"+ (end-start) + "milli seconds");
}
public void writeObject()
{
try
{
out = new FileOutputStream("c:/temp/test.txt");
outBuffer = new BufferedOutputStream(out);
objectOut = new ObjectOutputStream(outBuffer);
objectOut.writeObject(getObject());
}
catch(Exception e){e.printStackTrace();}
finally
{
if(objectOut != null)
try
{
objectOut.close();}catch(IOException e){e.printStackTrace();
}
}
}
}
class Person implements java.io.Serializable
{
private String name;
private transient Vector data;
private String address;
public Person(String name,String address)
{
this.name = name;
this.address = address;
}
public String getAddress()
{
return address;
}
public Vector getData()
{
return data;
}
public String getName()
{
return name;
}
public void setData(Vector data)
{
this.data = data;
}
}
8. Write JAVA programs which uses Datagram Socket for Client Server
Communication.
// Demonstrate datagrams.
import java.net.*;
class WriteServer
{
public static int serverPort = 998;
public static int clientPort = 999;
public static int buffer_size = 1024;
public static DatagramSocket ds;
public static byte buffer[] = new byte[buffer_size];
public static void TheServer() throws Exception
{
int pos=0;
while (true)
{
int c = System.in.read();
switch (c)
{
case -1:
System.out.println("Server Quits.");
return;
case 'r':
break;
case 'n':
ds.send(new DatagramPacket(buffer,pos,
InetAddress.getLocalHost(),clientPort));
pos=0;
break;
default:
buffer[pos++] = (byte) c;
}
}
}
public static void TheClient() throws Exception
{
while(true)
{
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
ds.receive(p);
System.out.println(new String(p.getData(), 0, p.getLength()));
}
}
public static void main(String args[]) throws Exception
{
if(args.length == 1)
{
ds = new DatagramSocket(serverPort);
TheServer();
}
else
{
ds = new DatagramSocket(clientPort);
TheClient();
}
}
}
9. Write JAVA programs which handles MouseEvent
// Demonstrate the mouse event handlers.
import java.awt.*; import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener
{
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me)
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me)
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me)
{
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me)
{
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me)
{
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}
10. Write JAVA programs which handles keyboardEvent
// Demonstrate the key event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SimpleKey" width=300 height=100>
</applet>
*/
public class SimpleKey extends Applet implements KeyListener
{
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g)
{
g.drawString(msg, X, Y);
}
}