SlideShare a Scribd company logo
1. Write a JAVA Program to demonstrate Constructor Overloading and
Method overloading.
class box
{
double width,height,depth,length,breadth;
box()
{ }
box(double w,double h,double d)
{
width = w; height = h; depth = d;
}
box(double len)
{
width = height = depth = len;
}
void rect(double x,double y)
{
length = x; breadth = y;
}
void rect(double x)
{
length = breadth = x;
}
double volume()
{
return(width * height * depth);
}
double area()
{
return(length * breadth);
}
}
class lab01a
{
public static void main(String args[])
{
box mybox1 = new box(10,20,15);
box mybox2 = new box(5);
box rect1 = new box();
box rect2 = new box();
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);
}
}

More Related Content

PDF
Java Lab Manual
DOC
CS2309 JAVA LAB MANUAL
PDF
Java programming lab manual
DOCX
Java PRACTICAL file
PDF
Advanced Java Practical File
DOC
Advanced Java - Praticals
PDF
All experiment of java
PDF
66781291 java-lab-manual
Java Lab Manual
CS2309 JAVA LAB MANUAL
Java programming lab manual
Java PRACTICAL file
Advanced Java Practical File
Advanced Java - Praticals
All experiment of java
66781291 java-lab-manual

What's hot (20)

PDF
Java_practical_handbook
DOCX
Java practical
PPT
Simple Java Programs
PDF
Java lab-manual
PDF
Java Simple Programs
PDF
Java programming-examples
DOC
Final JAVA Practical of BCA SEM-5.
PDF
Java programs
DOCX
Java codes
PPS
Class method
PPTX
Java Programs
DOC
Cs2312 OOPS LAB MANUAL
PDF
Advanced Debugging Using Java Bytecodes
PDF
Important java programs(collection+file)
PDF
FP in Java - Project Lambda and beyond
PDF
Laziness, trampolines, monoids and other functional amenities: this is not yo...
PDF
Java Concurrency by Example
PPTX
Java simple programs
PDF
OOP and FP - Become a Better Programmer
Java_practical_handbook
Java practical
Simple Java Programs
Java lab-manual
Java Simple Programs
Java programming-examples
Final JAVA Practical of BCA SEM-5.
Java programs
Java codes
Class method
Java Programs
Cs2312 OOPS LAB MANUAL
Advanced Debugging Using Java Bytecodes
Important java programs(collection+file)
FP in Java - Project Lambda and beyond
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Java Concurrency by Example
Java simple programs
OOP and FP - Become a Better Programmer
Ad

Viewers also liked (12)

PDF
Webdesing lab part-b__java_script_
PDF
Paris Redis Meetup Introduction
PDF
Cassandra vs. Redis
PDF
Accelerating Hadoop, Spark, and Memcached with HPC Technologies
PPTX
Java J2EE Interview Questions Part-1
PDF
Core java course syllabus
PDF
Full-Text Search Explained - Philipp Krenn - Codemotion Rome 2017
KEY
Redis in Practice
PPTX
DNS for Developers - ConFoo Montreal
PPTX
Get more than a cache back! - ConFoo Montreal
PPT
Chapter 11 - Sorting and Searching
PPTX
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
Webdesing lab part-b__java_script_
Paris Redis Meetup Introduction
Cassandra vs. Redis
Accelerating Hadoop, Spark, and Memcached with HPC Technologies
Java J2EE Interview Questions Part-1
Core java course syllabus
Full-Text Search Explained - Philipp Krenn - Codemotion Rome 2017
Redis in Practice
DNS for Developers - ConFoo Montreal
Get more than a cache back! - ConFoo Montreal
Chapter 11 - Sorting and Searching
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
Ad

Similar to Java programming lab_manual_by_rohit_jaiswar (20)

PDF
Sam wd programs
ODT
Java practical
PPTX
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
PPT
file handling in object oriented programming through java
DOCX
Cs141 mid termexam2_v1
DOC
Inheritance
DOCX
Java assignment 1
PDF
java-programming.pdf
PDF
The_Ultimate_Java_CheatSheet.pdfjkrwogjw
PDF
Java and j2ee_lab-manual
PDF
sample_midterm.pdf
DOCX
OOP Lab-manual btech in cse kerala technological university
PDF
55 new things in Java 7 - Devoxx France
PPT
M251_Meeting 7 (Exception Handling and Text IO).ppt
PDF
Core java pract_sem iii
DOCX
Jist of Java
DOCX
JAVA CONCEPTS AND PRACTICES
DOCX
Java execise
PDF
PDF
Java practical N Scheme Diploma in Computer Engineering
Sam wd programs
Java practical
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
file handling in object oriented programming through java
Cs141 mid termexam2_v1
Inheritance
Java assignment 1
java-programming.pdf
The_Ultimate_Java_CheatSheet.pdfjkrwogjw
Java and j2ee_lab-manual
sample_midterm.pdf
OOP Lab-manual btech in cse kerala technological university
55 new things in Java 7 - Devoxx France
M251_Meeting 7 (Exception Handling and Text IO).ppt
Core java pract_sem iii
Jist of Java
JAVA CONCEPTS AND PRACTICES
Java execise
Java practical N Scheme Diploma in Computer Engineering

Recently uploaded (20)

PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
From loneliness to social connection charting
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PPTX
Introduction and Scope of Bichemistry.pptx
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PPTX
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Open folder Downloads.pdf yes yes ges yes
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
How to Manage Starshipit in Odoo 18 - Odoo Slides
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Module 3: Health Systems Tutorial Slides S2 2025
PPTX
Cell Structure & Organelles in detailed.
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
From loneliness to social connection charting
human mycosis Human fungal infections are called human mycosis..pptx
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
Introduction and Scope of Bichemistry.pptx
NOI Hackathon - Summer Edition - GreenThumber.pptx
Cardiovascular Pharmacology for pharmacy students.pptx
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Abdominal Access Techniques with Prof. Dr. R K Mishra
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Open folder Downloads.pdf yes yes ges yes
102 student loan defaulters named and shamed – Is someone you know on the list?
How to Manage Starshipit in Odoo 18 - Odoo Slides
O5-L3 Freight Transport Ops (International) V1.pdf
Open Quiz Monsoon Mind Game Final Set.pptx
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Module 3: Health Systems Tutorial Slides S2 2025
Cell Structure & Organelles in detailed.
Open Quiz Monsoon Mind Game Prelims.pptx

Java programming lab_manual_by_rohit_jaiswar

  • 1. 1. Write a JAVA Program to demonstrate Constructor Overloading and Method overloading. class box { double width,height,depth,length,breadth; box() { } box(double w,double h,double d) { width = w; height = h; depth = d; } box(double len) { width = height = depth = len; } void rect(double x,double y) { length = x; breadth = y; } void rect(double x) { length = breadth = x; } double volume() { return(width * height * depth); } double area() { return(length * breadth); } } class lab01a { public static void main(String args[]) { box mybox1 = new box(10,20,15); box mybox2 = new box(5); box rect1 = new box(); box rect2 = new box();
  • 2. 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)); } } }
  • 3. 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[]) {
  • 4. 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"); } }
  • 5. 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 ();
  • 6. 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 :
  • 7. 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);
  • 8. 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() {
  • 9. 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()));
  • 10. } } 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
  • 11. 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)
  • 12. { 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); } }