SlideShare a Scribd company logo
1 of 12
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

What's hot

Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
Prabhu D
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
Alok Kumar
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Mario Fusco
 
Java simple programs
Java simple programsJava simple programs
Java simple programs
VEERA RAGAVAN
 

What's hot (20)

Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbook
 
Java lab 2
Java lab 2Java lab 2
Java lab 2
 
Java practical
Java practicalJava practical
Java practical
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
Java programs
Java programsJava programs
Java programs
 
Java codes
Java codesJava codes
Java codes
 
Class method
Class methodClass method
Class method
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Java simple programs
Java simple programsJava simple programs
Java simple programs
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 

Viewers also liked

Cassandra vs. Redis
Cassandra vs. RedisCassandra vs. Redis
Cassandra vs. Redis
Tim Lossen
 
Accelerating Hadoop, Spark, and Memcached with HPC Technologies
Accelerating Hadoop, Spark, and Memcached with HPC TechnologiesAccelerating Hadoop, Spark, and Memcached with HPC Technologies
Accelerating Hadoop, Spark, and Memcached with HPC Technologies
inside-BigData.com
 

Viewers also liked (12)

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

Similar to Java programming lab_manual_by_rohit_jaiswar

Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012
Anton Arhipov
 

Similar to Java programming lab_manual_by_rohit_jaiswar (20)

Python tour
Python tourPython tour
Python tour
 
Java practical
Java practicalJava practical
Java practical
 
Inheritance
InheritanceInheritance
Inheritance
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
Oop lecture9 11
Oop lecture9 11Oop lecture9 11
Oop lecture9 11
 
Closer look at classes
Closer look at classesCloser look at classes
Closer look at classes
 
Application-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageApplication-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta Language
 
Lab4
Lab4Lab4
Lab4
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Nabil code
Nabil  codeNabil  code
Nabil code
 
Nabil code
Nabil  codeNabil  code
Nabil code
 
Nabil code
Nabil  codeNabil  code
Nabil code
 
Thread
ThreadThread
Thread
 
Java 7
Java 7Java 7
Java 7
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
srgoc
srgocsrgoc
srgoc
 
Code red SUM
Code red SUMCode red SUM
Code red SUM
 
Bhaloo
BhalooBhaloo
Bhaloo
 
Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012
 

Recently uploaded

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Krashi Coaching
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 

Recently uploaded (20)

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 

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); } }