Java Lab Manual Aicte IV-sem
Java Lab Manual Aicte IV-sem
Java Lab Manual Aicte IV-sem
LAB MANUAL
SYLLABUS
EXPERIMENT DETAILS
1. Write a Java program to illustrate the concept of class with method overloading
2. Write a Java Program that reads a line of integers, and then displays each integer, and the sum
of all the integers (Use String Tokenizer class of java.util).
3. Write a Java program to illustrate the concept of Single level and Multi level Inheritance.
4. Write a Java program to demonstrate the Interfaces & Abstract Classes.
5. Write a Java program to implement the concept of exception handling.
6. Write a Java program to illustrate the concept of threading using Thread Class and runnable
Interface.
7. Write a Java program to illustrate the concept of Thread synchronization.
8. Write a Java program that correctly implements producer consumer problem using the concept
of inter thread communication.
9. Write a Java program to illustrate collection classes like Array List, Linked List, and Tree map
and Hash map.
10. Write a Java program to illustrate Legacy classes like Vector, Hash table, Dictionary &
Enumeration interface
11. Write a Java program to implement iteration over Collection using Iterator interface and List
Iterator interface
12. Write a Java program that reads a file name from the user, and then displays information about
whether the file exists, whether the file is readable, whether the file is writable, the type of file
and the length of the file in bytes.
13. Write a Java program to illustrate the concept of I/O Streams
14. Write a Java program to implement serialization concept
15. Write a Java applet program to implement Color and Graphics class
16. Write a Java applet program for handling mouse & key events
17. Write a Java applet program to implement Adapter classes
18. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for
the digits and for the +, -, *, % operations. Add a text field to display the result.
1. Write a Java program to illustrate the concept of class with method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
2. Write a Java program that reads a line of integers, and displays each integer, and the sum of all
the integers ( use StringTokenizer class of java.util)
import java.util.*;
class StringTokenizerDemo {
public static void main(String args[]) {
int n;
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter integers with one space gap:");
String s = sc.nextLine();
StringTokenizer st = new StringTokenizer(s, " ");
while (st.hasMoreTokens()) {
String temp = st.nextToken();
n = Integer.parseInt(temp);
System.out.println(n);
sum = sum + n;
}
System.out.println("sum of the integers is: " + sum);
sc.close();
}
}
Output:
Enter integers with one space gap: 4 5
63242
The integers are:
4
5
6
3
2
4
2
sum of the integers is: 26
3. Write a Java program to illustrate the concept of Single level and Multi level Inheritance.
(a) Single Level Inheritance
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Output:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Output:
disp() method of ClassA disp() method of ClassB
disp() method of ClassC
Output:
callback called with 42
Classes that implement interfaces may also define other members, too.
(b) Abstract Class
abstract class A {
abstract void callme();
void callmetoo() {
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
Output:
B's implementation of callme.
This is a concrete method.
6. Write a Java program to illustrate the concept of threading using Thread Class and runnable
Interface.
(a) Multi-threading by extending Thread class
class NewThread extends Thread
{
NewThread()
{
super("Demo Thread");
System.out.println("Child thread: " + this);
start();
}
}
}
Output:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
(b) Multi-threading by implementing Runnable interface.
class NewThread implements Runnable
{
Thread t;
NewThread()
{
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start();
}
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
{
new NewThread();
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Output:
Child thread: Thread[Demo Thread,5,main]
Child Thread: 5
Main Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
Output:
[Hello]
[World]
[Synchronized]
8. Write a Java program that correctly implements producer consumer problem using the concept
of inter-thread communication.
class Q
{
int n;
boolean valueSet = false;
synchronized int get()
{
while(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n); valueSet = false;
notify();
return n;
}
{
int i = 0; while(true)
{
q.put(i++);
}
}
}
Output:
Press Control-C to
stop. Put: 0
Got: 0
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
.
.
9. Write a Java program to illustrate collection classes like ArrayList, LinkedList, TreeMap and
HashMap.
(a) ArrayList illustration
import java.util.ArrayList;
public class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println("Elements in ArrayList:"+cars);
System.out.println("Element at 0th index: "+cars.get(0));
cars.set(0, "Opel"); //changing element at 0th index
System.out.println("\n0th index element after change: "+cars.get(0));
cars.remove(0); //Removing an element at 0th index
System.out.println("After removal of 0th index element from ArrayList:"+cars);
System.out.println("The size of the ArrayList:"+cars.size());
System.out.println("Using for loop parsing through ArrayList:");
BMW
Ford
Mazda
Using for : each loop to parse through ArrayList:
BMW
Ford
Mazda
Elements in ArrayList after clear:[]
(b) LinkedList illustration
import java.util.LinkedList;
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext())
{
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext())
{
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
10. Write a Java program to illustrate Legacy Classes like Vector, Hashtable, Dictionary &
Enumeration interface.
(a) Vector Class illustration
import java.util.*;
public class VectorDemo
{
public static void main(String args[])
{
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " + v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " + (Integer)v.firstElement());
System.out.println("Last element: " + (Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
Output:
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12
(b) Hashtable Class Illustration
import java.util.*;
while(names.hasMoreElements())
{
str = (String) names.nextElement();
// put() method :
dic.put("123", "Code");
dic.put("456", "Program");
// elements() method :
// get() method :
System.out.println("\nValue at key = 6 : " + dic.get("6"));
System.out.println("Value at key = 456 : " + dic.get("123"));
// isEmpty() method :
System.out.println("\nThere is no key-value pair : " + dic.isEmpty() + "\n");
// keys() method :
for (Enumeration k = dic.keys(); k.hasMoreElements();)
{
System.out.println("Keys in Dictionary : " + k.nextElement());
}
// remove() method :
System.out.println("\nRemove : " + dic.remove("123"));
System.out.println("Check the value of removed key : " + dic.get("123"));
System.out.println("\nSize of Dictionary : " + dic.size());
}
}
Output:
Value in Dictionary : Code
Value in Dictionary : Program
Remove : Code
Check the value of removed key : null
Size of Dictionary : 1
11. Write a Java program to implement iteration over collection using Iterator interface and
ListIterator interface.
(a) Iteration using Iterator inerface
import java.util.*;
public class IteratorDemo
{
public static void main(String args[])
{
// Create an array list
ArrayList al = new ArrayList();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
while(litr.hasNext())
{
Object element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
while(litr.hasPrevious())
{
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
Output:
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+
(b) Iteration using ListIterator Interface
import java.util.*;
// Getting ListIterator
ListIterator<String> namesIterator = names.listIterator();
// Traversing elements
while(namesIterator.hasNext())
{
System.out.println(namesIterator.next());
}
12. Write a Java program that reads on file name from the user then displays information about
whether the file exists, whether the file is readable, whether the file is writable, the type of the file
and the length of the file in bytes.
import java.util.Scanner;
import java.io.File;
class FileDemo
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
String s=input.nextLine();
File f1=new File(s);
System.out.println("File Name:"+f1.getName());
System.out.println("Path:"+f1.getPath());
System.out.println("Abs Path:"+f1.getAbsolutePath());
System.out.println("Parent:"+f1.getParent());
System.out.println("This file is:"+(f1.exists()?"Exists":"Does not exists"));
System.out.println("Is file:"+f1.isFile());
System.out.println("Is Directory:"+f1.isDirectory());
System.out.println("Is Readable:"+f1.canRead());
System.out.println("IS Writable:"+f1.canWrite());
System.out.println("Is Absolute:"+f1.isAbsolute());
System.out.println("File Last Modified:"+f1.lastModified());
System.out.println("File Size:"+f1.length()+"bytes");
System.out.println("Is Hidden:"+f1.isHidden());
}
}
Output:
C:/> javac FileDemo.java
C:/>java FileDemo HelloWorld.java
File Name: HelloWorld.java
Path: HelloWorld.java
Abs Path: c:\HelloWorld.java
Parent: Null
This file is:Exists
Is file:true
Is Directory:false
Is Readable:true Is
Writable:true
Is Absolute:false
File Last Modified:1206324301937
File Size: 406 bytes
Is Hidden:false
try
{
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
Output: input.txt
Compile the above program and execute it, which This is test for copy file.
will result in creating output.txt file with the same
content as we have in input.txt.
$javac CopyFile.java
$java CopyFile
(c)Standard Stream
import java.io.*;
finally
{
if (cin != null)
{
cin.close();
}
}
}
}
Output:
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q
// Parameterized constructor
public Serialization(int a, String b)
{
this.a = a;
this.b = b;
}
class SerializationDemo
{
public static void main(String[] args)
{
Serialization obj = new Serialization(1, "Java Programming");
String fname = "file.txt";
// Serialization
try
{
//Saving of object in a file
FileOutputStream fout = new FileOutputStream(fname);
ObjectOutputStream out = new ObjectOutputStream(fout);
out.close();
fout.close();
// Deserialization
try
{
// Reading the object from a file
FileInputStream fin = new FileInputStream(fname);
ObjectInputStream in = new ObjectInputStream(fin);
in.close();
fin.close();
15. Write a Java applet program to implement Color and Graphics class.
import java.applet.Applet;
import java.awt.*;
/*<applet code="GraphicsDemo" width=600 height=400>
</applet>
*/
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
Output:
16. Write a Java applet program for handling mouse & key events.
(a) Handling Mouse Events
// 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);
}
// Display keystrokes.
public void paint(Graphics g)
{
g.drawString(msg, X, Y);
}
}
Output:
c:\applets> javac KeyboardEvents.java
c:\applets> appletviewer KeyboardEvents.java
{
adapterDemo.showStatus("Mouse dragged");
}
}
Output:
c:\applets> javac AdapterDemo.java
c:\applets> appletviewer AdapterDemo.java
18. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons
for the digits and for the +, -, *, % operations. Add a text field to display the result.
//Program for implementing a Simple Calculator
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="SimpleCalculator" width=300 height=300></applet>*/
for(int i=0;i<10;i++)
{
b[i]=new Button(""+k);
add(b[i]);
k++;
b[i].setBackground(Color.pink);
b[i].addActionListener(this);
}
for(int i=0;i<6;i++)
{
b1[i]=new Button(""+op2[i]);
add(b1[i]);
b1[i].setBackground(Color.pink);
b1[i].addActionListener(this);
}
add(t);
}
{
String str=ae.getActionCommand();
if(str.equals("+"))
{
p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("-"))
{
p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("*"))
{
p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("%"))
{
p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("="))
{
str1="";
if(oper.equals("+"))
{
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p+q)));
}
else if(oper.equals("-"))
{
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p-q)));
}
else if(oper.equals("*"))
{
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p*q)));
}
else if(oper.equals("%"))
{
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p%q)));
}
}
else if(str.equals("C"))
{
p=0;
q=0;
t.setText("");
str1="";
t.setText("0");
}
else
{
t.setText(str1.concat(str));
str1=t.getText();
}
}
}
Output:
C:\>javac SimpleCalculator.java
C:\ >appletviewer SimpleCalculator.java