Java Lab Manual Aicte IV-sem

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

AICTE Model Curriculum with effect from Academic Year 2019-20

OOPS USING JAVA LAB


(PC262CS)

LAB MANUAL

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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.

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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

public class Overload {


public static void main(String args[]) {
OverloadDemo ob = new
OverloadDemo(); double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Output:
No parameters a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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

// Create a subclass by extending class A.


class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}

public class SingleInheritance {


public static void main(String args[]){
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
// The subclass has access to all public members of its superclass.
subOb.i = 7;

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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

Sum of i, j and k in subOb: i+j+k: 24

(b) Multi Level Inheritance


class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}

class ClassB extends ClassA


{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}

class ClassC extends ClassB


{
public void dispC()
{
System.out.println("disp() method of ClassC");
}

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

public class MultiLevelInheritance


{
public static void main(String args[])
{
ClassC c = new
ClassC(); c.dispA();
c.dispB();
c.dispC();
}
}

Output:
disp() method of ClassA disp() method of ClassB
disp() method of ClassC

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

4. Write a Java program to demonstrate the Interface & Abstract Class.


(a) Interface
interface Callback {
void ifaceMeth(int param);
}

class Client implements Callback {


public void ifaceMeth(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement interfaces " + "may also define other members,
too.");
}
}

public class TestIface {


public static void main(String args[]) {
Callback c = new Client();
c.ifaceMeth(42);
Client cl=new Client();
cl.nonIfaceMeth();
}
}

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.");

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

}
}

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.

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

5. Write a Java program to implement the concept of exception handling.


class ExceptionHandling
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("from throwOne() method");
}
}

public class ExceptionHandlingDemo


{
public static void main(String args[])
{
ExceptionHandling eh = new ExceptionHandling();
try
{
eh.throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
finally
{
System.out.println("Code from finally block...");
}
}
}
Output:
Inside throwOne.
Caught java.lang.IllegalAccessException: from throwOne() method
Code from finally block...

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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

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

public class ExtendThread


{
public static void main(String args[])
{
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.");

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

}
}

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

public class ThreadDemo


{
public static void main(String args[])

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

{
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.

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

7. Write a Java program to illustrate the concept of Thread synchronization.


class Callme
{
synchronized void call(String msg)
{
System.out.print("[" + msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}

class Caller implements Runnable


{
String msg;
Callme target; Thread t;
public Caller(Callme call, String s)
{
target = call;
msg = s;
t = new Thread(this);
t.start();
}

public void run()


{
target.call(msg);
}
}

public class Synch


{
public static void main(String args[])
{
Callme call = new Callme();
Caller ob1 = new Caller(call, "Hello");
Caller ob2 = new Caller(call, "Synchronized");
Caller ob3 = new Caller(call, "World");
try
{
ob1.t.join();
ob2.t.join();

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}

Output:
[Hello]
[World]
[Synchronized]

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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

synchronized void put(int n)


{
while(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.n = n; valueSet = true;
System.out.println("Put: " + n);
notify();
}
}

class Producer implements Runnable


{
Q q;
Producer(Q q)
{
this.q = q;
new Thread(this, "Producer").start();
}
public void run()

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

{
int i = 0; while(true)
{
q.put(i++);
}
}
}

class Consumer implements Runnable


{
Q q;
Consumer(Q q)
{
this.q = q;
new Thread(this, "Consumer").start();
}

public void run()


{
while(true)
{
q.get();
}
}
}

public class PCDemo


{
public static void main(String args[])
{
Q q = new Q();
new Producer(q); new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

Output:
Press Control-C to
stop. Put: 0
Got: 0
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
.
.

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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:");

for (int i = 0; i < cars.size(); i++)


System.out.println(cars.get(i));

System.out.println("Using for : each loop to parse through ArrayList:");

for (String i : cars)


System.out.println(i);

cars.clear(); //Clearing all elements in an ArrayList


System.out.println("Elements in ArrayList after clear:"+cars);
}
}
Output:
Elements in ArrayList:[Volvo, BMW, Ford, Mazda]
Element at 0th index: Volvo

0th index element after change: Opel


After removal of 0th index element from ArrayList:[BMW, Ford, Mazda]
The size of the ArrayList:3
Using for loop parsing through ArrayList:

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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;

public class LinkedListDemo


{
public static void main(String args[])
{
// create a linked list
LinkedList ll = new LinkedList();

// 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


Object val = ll.get(2);
ll.set(2, (String) val + " Changed");

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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]
(c) TreeMap illustration
import java.util.*;
public class TreeMapDemo
{
public static void main(String args[])
{
// Create a TreeMap
TreeMap tm = new TreeMap();

// Put elements to the map


tm.put("Zara", new Double(3434.34));
tm.put("Mahnaz", new Double(123.22));
tm.put("Ayan", new Double(1378.00));
tm.put("Daisy", new Double(99.22));
tm.put("Qadir", new Double(-19.08));

// Get a set of the entries


Set set = tm.entrySet();

// 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();

// Deposit 1000 into Zara's account


double balance = ((Double)tm.get("Zara")).doubleValue();
tm.put("Zara", new Double(balance + 1000));

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

System.out.println("Zara's new balance: " + tm.get("Zara"));


}
}
Output:
Ayan: 1378.0
Daisy: 99.22
Mahnaz: 123.22
Qadir: -19.08
Zara: 3434.34

Zara's new balance: 4434.34


(d) HashMap Illustration
import java.util.*;
public class HashMapDemo
{
public static void main(String args[])
{
// Create a hash map
HashMap hm = new HashMap();

// Put elements to the map


hm.put("Zara", new Double(3434.34));
hm.put("Mahnaz", new Double(123.22));
hm.put("Ayan", new Double(1378.00));
hm.put("Daisy", new Double(99.22));
hm.put("Qadir", new Double(-19.08));

// Get a set of the entries


Set set = hm.entrySet();

// 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();

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

// Deposit 1000 into Zara's account


double balance = ((Double)hm.get("Zara")).doubleValue();
hm.put("Zara", new Double(balance + 1000));
System.out.println("Zara's new balance: " + hm.get("Zara"));
}
}
Output:
Daisy: 99.22
Ayan: 1378.0
Zara: 3434.34
Qadir: -19.08
Mahnaz: 123.22

Zara's new balance: 4434.34

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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.");

// enumerate the elements in the vector.


Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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.*;

public class HashTableDemo


{
public static void main(String args[])
{
// Create a hash map
Hashtable balance = new Hashtable();
Enumeration names;
String str; double bal;

balance.put("Zara", new Double(3434.34));


balance.put("Mahnaz", new Double(123.22));
balance.put("Ayan", new Double(1378.00));
balance.put("Daisy", new Double(99.22));
balance.put("Qadir", new Double(-19.08));

// Show all balances in hash table.


names = balance.keys();

while(names.hasMoreElements())
{
str = (String) names.nextElement();

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

System.out.println(str + ": " + balance.get(str));


}
System.out.println();

// Deposit 1,000 into Zara's account


bal = ((Double)balance.get("Zara")).doubleValue();
balance.put("Zara", new Double(bal + 1000));
System.out.println("Zara's new balance: " + balance.get("Zara"));
}
}
Output:
Qadir: -19.08
Zara: 3434.34
Mahnaz: 123.22
Daisy: 99.22
Ayan: 1378.0

Zara's new balance: 4434.34


(c) Dictionary abstract class and Enumeration Interface Illustration
import java.util.*;
public class DictionaryEnumDemo
{
public static void main(String[] args)
{
// Initializing a Dictionary
Dictionary dic = new Hashtable();

// put() method :
dic.put("123", "Code");
dic.put("456", "Program");

// elements() method :

for (Enumeration i = dic.elements(); i.hasMoreElements();)


{
System.out.println("Value in Dictionary : " + i.nextElement());
}

// get() method :
System.out.println("\nValue at key = 6 : " + dic.get("6"));
System.out.println("Value at key = 456 : " + dic.get("123"));

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

// 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

Value at key = 6 : null


Value at key = 456 : Code

There is no key-value pair : false

Keys in Dictionary : 123


Keys in Dictionary : 456

Remove : Code
Check the value of removed key : null

Size of Dictionary : 1

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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

// add elements to the array list


al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");

// Use iterator to display contents of al


System.out.print("Original contents of al: ");
Iterator itr = al.iterator();

while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

// Modify objects being iterated


ListIterator litr = al.listIterator();

while(litr.hasNext())
{
Object element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();

while(itr.hasNext())

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

// Now, display the list backwards


System.out.print("Modified list backwards: ");

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.*;

public class ListIteratorDemo


{
public static void main(String[] args)
{
List<String> names = new LinkedList<>();
names.add("John");
names.add("David");
names.add("Rubu");

// Getting ListIterator
ListIterator<String> namesIterator = names.listIterator();

// Traversing elements
while(namesIterator.hasNext())
{
System.out.println(namesIterator.next());
}

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

// Enhanced for loop creates Internal Iterator here.


for(String name: names)
{
System.out.println(name);
}
}
}
Output:
John
David
Rubu
John
David
Rubu

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

13. Write a Java program to illustrate the concept of I/O Streams


(a)Byte Stream
import java.io.*;
public class CopyFile
{
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream("input.txt");
out = new FileOutputStream("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
(b)Character Stream
import java.io.*;

public class CopyFile


{
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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.*;

public class ReadConsole


{
public static void main(String args[]) throws IOException
{
InputStreamReader cin = null;
try
{
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do
{
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

finally
{
if (cin != null)
{
cin.close();
}
}
}
}
Output:
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

14. Write a Java program to implement serialization concept


// Program for serialization and deserialization of a Java object
import java.io.*;

class Serialization implements java.io.Serializable


{
public int a;
public String b;

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

// Method for serialization of object


out.writeObject(obj);

out.close();
fout.close();

System.out.println("Object has been serialized");


}
catch(IOException ie)
{
System.out.println("IOException is caught");
}

Serialization serial = null;

// Deserialization

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

try
{
// Reading the object from a file
FileInputStream fin = new FileInputStream(fname);
ObjectInputStream in = new ObjectInputStream(fin);

// Method for deserialization of object


serial = (Serialization)in.readObject();

in.close();
fin.close();

System.out.println("Object has been deserialized ");


System.out.println("a = " + serial.a);
System.out.println("b = " + serial.b);
}
catch(IOException ie)
{
System.out.println("IOException is caught");
}
catch(ClassNotFoundException ce)
{
System.out.println("ClassNotFoundException is caught");
}
}
}
Output:
Object has been serialized
Object has been deserialized
a=1
b = Java Programming

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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:

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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

// 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();

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

// 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);
}
}
Output:
c:\applets> javac MouseEvents.java

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

c:\applets> appletviewer MouseEvents.java

(b) Handling Keyboard Events


// Demonstrate the key event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="KeyboardEvents" width=300 height=100>
</applet>
*/
public class KeyboardEvents 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)

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

{
g.drawString(msg, X, Y);
}
}
Output:
c:\applets> javac KeyboardEvents.java
c:\applets> appletviewer KeyboardEvents.java

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

17. Write a Java applet program to implement Adapter classes.


// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet
{
public void init()
{
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}

class MyMouseAdapter extends MouseAdapter


{
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo)
{
this.adapterDemo = adapterDemo;
}

// Handle mouse clicked.


public void mouseClicked(MouseEvent me)
{
adapterDemo.showStatus("Mouse clicked");
}
}

class MyMouseMotionAdapter extends MouseMotionAdapter


{
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo)
{
this.adapterDemo = adapterDemo;
}

// Handle mouse dragged.


public void mouseDragged(MouseEvent me)

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

{
adapterDemo.showStatus("Mouse dragged");
}
}
Output:
c:\applets> javac AdapterDemo.java
c:\applets> appletviewer AdapterDemo.java

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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>*/

public class SimpleCalculator extends Applet implements ActionListener


{
TextField t;
Button b[]=new Button[15];
Button b1[]=new Button[6];
String op2[]={"+","-","*","%","=","C"};
String str1="";
int p=0,q=0;
String oper;
public void init()
{
setLayout(new GridLayout(5,4));
t=new TextField(20);
setBackground(Color.pink);
setFont(new Font("Arial",Font.BOLD,20));
int k=0;
t.setEditable(false);
t.setBackground(Color.white);
t.setText("0");

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

public void actionPerformed(ActionEvent ae)

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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

JAVA LAB MANUAL MOHAMMED AFZAL


AICTE Model Curriculum with effect from Academic Year 2019-20

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

JAVA LAB MANUAL MOHAMMED AFZAL

You might also like