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

What's hot

Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbook
Manusha Dilan
 
Java lab 2
Java lab 2Java lab 2
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
Khurshid Asghar
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
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.
Nishan Barot
 
Java codes
Java codesJava codes
Java codes
Hussain Sherwani
 
Class method
Class methodClass method
Class method
kamal kotecha
 
Java Programs
Java ProgramsJava Programs
Java Programs
vvpadhu
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALPrabhu D
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
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 beyondMario 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 Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
Ganesh Samarthyam
 
Java simple programs
Java simple programsJava simple programs
Java simple programsVEERA RAGAVAN
 
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
Mario Fusco
 

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

Webdesing lab part-b__java_script_
Webdesing lab part-b__java_script_Webdesing lab part-b__java_script_
Webdesing lab part-b__java_script_
Shivanand Algundi
 
Paris Redis Meetup Introduction
Paris Redis Meetup IntroductionParis Redis Meetup Introduction
Paris Redis Meetup Introduction
Gregory Boissinot
 
Cassandra vs. Redis
Cassandra vs. RedisCassandra vs. Redis
Cassandra vs. RedisTim 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
 
Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1
javatrainingonline
 
Core java course syllabus
Core java course syllabusCore java course syllabus
Core java course syllabus
Papitha Velumani
 
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
Codemotion
 
Redis in Practice
Redis in PracticeRedis in Practice
Redis in Practice
Noah Davis
 
DNS for Developers - ConFoo Montreal
DNS for Developers - ConFoo MontrealDNS for Developers - ConFoo Montreal
DNS for Developers - ConFoo Montreal
Maarten Balliauw
 
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
Maarten Balliauw
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
Eduardo Bergavera
 
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
widespreadpromotion
 

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

Python tour
Python tourPython tour
Python tour
Tamer Abdul-Radi
 
Java practical
Java practicalJava practical
Java practical
william otto
 
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
Rafael Winterhalter
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
Jamie (Taka) Wang
 
Closer look at classes
Closer look at classesCloser look at classes
Closer look at classes
yugandhar vadlamudi
 
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
ESUG
 
Lab4
Lab4Lab4
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
MuhammadTalha436
 
Nabil code
Nabil  codeNabil  code
Nabil code
nabildekess
 
Nabil code
Nabil  codeNabil  code
Nabil code
nabildekess
 
Nabil code
Nabil  codeNabil  code
Nabil code
nabildekess
 
Java 7
Java 7Java 7
Java 7
Bipul Sinha
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
Niraj Bharambe
 
srgoc
srgocsrgoc
Code red SUM
Code red SUMCode red SUM
Code red SUM
Shumail Haider
 
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.2012Anton 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

The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 

Recently uploaded (20)

The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 

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