Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Java

The document contains a series of Java programs demonstrating various programming concepts including method overloading, exception handling, threading, and collection classes. Each program is accompanied by comments explaining its functionality and expected output. The examples cover a range of topics such as inheritance, interfaces, synchronization, and legacy classes.

Uploaded by

syed farhad
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Java

The document contains a series of Java programs demonstrating various programming concepts including method overloading, exception handling, threading, and collection classes. Each program is accompanied by comments explaining its functionality and expected output. The examples cover a range of topics such as inheritance, interfaces, synchronization, and legacy classes.

Uploaded by

syed farhad
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

1)Write a program to illustrate the concept of class with method overloading.

/*Program to implement method overloading*/

class Test
{
void sum(int x, int y)
{
System.out.println("The sum is "+(x+y));
}
void sum(int x, int y, int z)
{
System.out.println("The sum is "+(x+y+z));
}
void sum(double x, double y)
{
System.out.println("The sum is "+(x+y));
}
void sum(double x, double y, double z)
{
System.out.println("The sum is "+(x+y+z));
}
}
class OverLoad
{
public static void main(String args[])
{
Test t = new Test();
t.sum(10, 20);
t.sum(30, 40, 50);
t.sum(10.4, 20.6);
t.sum(10.9, 11.3, 12.8);
}
}

Output :
2) Write a java program that reads a line of integer and then displays
each integer and sum of all integers(Using String Tokenizer class
of java.util).

/*Display each integer and sum of integers using String Tokenizer*/

import java.util.*;
public class StrToken
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the integer string : ");
String num = sc.nextLine();
int sum = 0;
StringTokenizer st = new StringTokenizer(num, " ");
System.out.println("Number of integer tokens :
"+st.countTokens());
while(st.hasMoreTokens())
{
int val = Integer.parseInt(st.nextToken());
sum = sum + val;
System.out.println(val);
}
System.out.println("Sum : "+sum);
}
}

Output :
3)Write a java program to illustrate the concept of Single level and multilevel
inheritance.

/*Single level and Multilevel inheritance*/

class One
{
String s1 = "Class One";
void displayOne()
{
System.out.println("Parent : "+s1);
}
}
class Two extends One
{
String s2 = "Class Two";
void displayTwo()
{
super.displayOne();
System.out.println("Single level Inheritance");
System.out.println("Child "+s2+"inherited from "+s1);
}
}
class Three extends Two
{
String s3 = "Class Three";
void displayThree()
{
super.displayTwo();
System.out.println("Multi level Inheritance");
System.out.println("Child "+s3+"inherited from "+s2+"and"+s1);
}
}
class SingleMult
{
public static void main(String args[])
{
Three obj = new Three();
obj.displayThree();
}
}

Output :
4)Write a java program to demonstrate the Interfaces and Abstract Classes.

/*Interface and abstract classes*/

abstract class Demo


{
abstract void show();
}
interface Printable
{
void print();
}
class AbstractClassdemo extends Demo implements Printable
{
void show()
{
System.out.println("This is Abstract class Method");
}
public void print()
{
System.out.println("This is interface method");
}
}
public class InterAbstr
{
public static void main(String args[])
{
AbstractClassdemo ac = new AbstractClassdemo();
ac.show();
ac.print();
}
}

Output :

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

/*Program to implement exception handling*/

import java.util.InputMismatchException;
import java.util.Scanner;
public class Exception
{
public static void main(String args[])
{
int arr[] = {15, 20, 33, 40, 55};
Scanner sc = new Scanner(System.in);
int ch = 0, a, b, res;
while(ch != -1)
{
System.out.println("Enter the index of array(-1 to quit):");
try
{
ch = sc.nextInt();
System.out.println(arr[ch]);
System.out.println("Enter two integer : ");

a = sc.nextInt();
b = sc.nextInt();
System.out.println("Division result : "+(a/b));
}
catch(ArrayIndexOutOfBoundsException aie)
{
System.out.println("Index value is out of bounds");
}
catch(InputMismatchException ime)
{
System.out.println("Entered value is not valid,
characters and decimal values are not allowed");
sc.next();
}
catch(ArithmeticException ae)
{
System.out.println("Denominator should not be
zero");
}
}

}
}

Output :
6)Write a java program to illustrate the concept of threading using the Thread
class and Runnable interface.

/*Program to illustrate the concept of threading using the thread class and
runnable interface*/

class One extends Thread


{
public void run()
{
int sum = 0;
String name = Thread.currentThread().getName();
long id = Thread.currentThread().getId();
System.out.println("Executed thread = "+name+",Id = "+id);
for(int i = 10; i < 15; i++)
{
sum = sum + i;
System.out.print(i+"+");
}
System.out.println("Sum = "+sum);
}

}
class Two implements Runnable
{
public void run()
{
int sum = 0;
String name = Thread.currentThread().getName();
long id = Thread.currentThread().getId();;
System.out.println("Executed thread = "+name+",Id = "+id);
for(int i = 20; i < 25; i++)
{
sum = sum + i;
System.out.print(i+"+");
}
System.out.println("Sum = "+sum);
}
}
public class ThreadInter
{
public static void main(String args[])throws InterruptedException
{
One obj1 = new One();
Two t = new Two();
Thread obj2 = new Thread(t);
obj1.start();
obj1.join();
obj2.start();
}
}

Output :
7)Write a java program to implement the concept of thread synchronisation.

/*Implement the concept of thread synchronization*/

class Resource
{
synchronized public void m1()
{
String msg[] =
{"This","is","an","example","for","synchronized","thread"};
String str = Thread.currentThread().getName();
for(int i = 0; i < msg.length; i++)
{
System.out.println(str + " : " + msg[i]);
try
{
Thread.sleep(250);
}
catch(InterruptedException e){}
}
}
}
class T2 extends Thread
{
Resource r;
public T2(Resource r, String name)
{
super(name);
this.r = r;
}
public void run()
{
r.m1();
}
}
public class ThreadSync
{
public static void main(String args[])
{
Resource r_obj = new Resource();
T2 t1 = new T2(r_obj, "First");
T2 t2 = new T2(r_obj, "Second");
t1.start();
t2.start();
}
}

Output :
8)Write a java program that implements producer consumer problem using the
concept of inter thread communication.

/*Program to implement produce consumer problem using Inter Thread


communication */

class SharedResource
{
int item;
boolean flag = true;
synchronized void putItem(int item)
{
while(flag == false)
{
try
{
wait();
}
catch(InterruptedException e){}
}
this.item = item;
System.out.println("Item placed : " + item);
flag = false;
notify();
}
synchronized int getItem()
{
while(flag == true)
{
try
{
wait();
}
catch(InterruptedException e) {}
}
System.out.println("Item consumed : "+item);
flag = true;
notify();
return item;
}
}
class Producer extends Thread
{
SharedResource sr;
Producer(SharedResource sr)
{
this.sr = sr;
start();
}
public void run()
{
int k = 0;
while(true)
{
sr.putItem(k++);
try
{
Thread.sleep(500);
}
catch(InterruptedException e) {}
}
}
}
class Consumer extends Thread
{
SharedResource sr;
Consumer(SharedResource sr)
{
this.sr = sr;
start();
}
public void run()
{
while(true)
{
sr.getItem();
try
{
Thread.sleep(500);
}
catch(InterruptedException e) {}
}
}
}
class InterThread
{
public static void main(String args[])
{
SharedResource sr = new SharedResource();
Producer p = new Producer(sr);
Consumer c = new Consumer(sr);
}
}

Output :
9)Write a java program to illustrate collection classes like ArrayList, LinkedList,
TreeMap, HashMap.

(a)ArrayList

/*Collection class ArrayList*/

import java.util.*;
public class Arraylist
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
ArrayList list = new ArrayList();
System.out.println("List = " + list);
list.add(10);
list.add(20);
list.add(45.6);
list.add(5.7);
list.add("abc");
list.add("xyz");
System.out.println("List after insertion is : " + list);
System.out.println("Enter a positive index number to fetch an item
: ");
int i = sc.nextInt();
System.out.println("Element at " + i + " : " + list.get(i));
System.out.println("Enter a positive index to remove item : ");
i = sc.nextInt();
list.remove(i);
System.out.println("List after removing : " + list);
list.set(i, 100);
System.out.println("List after updating value at "+ i + " : " + list);
list.clear();
System.out.println("Now list : " + list);
}
}

Output :

(b)LinkedList

/*Linked list in java*/

import java.util.*;
public class Linkedlist
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
LinkedList list = new LinkedList();
System.out.println("Linked List is " + list + ",size is " + list.size());
list.add(10.11);
list.add(7);
list.add(18);
list.add("MS");
list.add("LINUX");
list.add(5.9);
System.out.println("Linked List is " + list + ",size is " + list.size());
list.addFirst("first item");
list.addLast("second item");
list.add(3, 50);
System.out.println("Linked List after adding elements at first, last,
3 : " + list);
System.out.println("Linked List size is " + list.size());
int i = sc.nextInt();
System.out.println("Element at " + i + " is " + list.get(i));
System.out.println("Enter element positive index to be removed :
");
i = sc.nextInt();
list.remove(i);
list.removeFirst();
list.removeLast();
System.out.println("Linked List after removing " + i + ", first, last
items : " + list + ", size = " + list.size());
list.set(i, 100);
System.out.println("List after updating value at " + i + "is " + list);
list.clear();
System.out.println("Now list : " + list + ",size = " + list.size());
}
}

Output :
(c)TreeMap

/*Tree Map implementation*/

import java.util.*;
public class Treemap
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
TreeMap tm = new TreeMap();
System.out.println("TreeMap : " + tm);
tm.put(121, "Warner");
tm.put(156, "Travis");
tm.put(101, "Pujara");
tm.put(145 ,"Rahane");
System.out.println("TreeMap : " + tm + ", Size : " + tm.size());
System.out.println("Enter a key to fetch its values : ");
int key = sc.nextInt();
System.out.println("Value for " + key + ":" + tm.get(key));
System.out.println("First entry in tree map : " + tm.firstEntry());
System.out.println("Last entry in tree map : " + tm.lastEntry());
System.out.println("Higher entry than 101 : " +
tm.higherEntry(101));
System.out.println("Lower entry than 145 : " +
tm.lowerEntry(145));
tm.replace(101, "Shreyas");
System.out.println("Tree Map after replacing 101 : " + tm);
tm.remove(156);
System.out.println("Tree Map after removing 156 : " + tm);
tm.clear();
System.out.println("TreeMap : " + tm + ", Size : " + tm.size());
}
}

Output :

(d)HashMap
/*Hash Map implementation*/
import java.util.*;
public class Hashmap
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
HashMap hm = new HashMap();
System.out.println("HashMap : " + hm);
hm.put(121, "Warner");
hm.put(156, "Travis");
hm.put(101, "Pujara");
hm.put(145 ,"Rahane");
System.out.println("HashMap : " + hm + ", Size : " + hm.size());
System.out.println("Enter a key to fetch its values : ");
int key = sc.nextInt();
System.out.println("Value for " + key + ":" + hm.get(key));
hm.replace(101, "Shreyas");
System.out.println("Hash Map after replacing 101 : " + hm);
hm.remove(156);
System.out.println("Hash Map after removing 156 : " + hm);
System.out.println("Enter a key to check if it exists or not : ");
int searchKey = sc.nextInt();
boolean b = hm.containsKey(searchKey);
System.out.println("Search status : " + b);
hm.clear();
System.out.println("HashMap : " + hm + ", Size : " + hm.size());
}
}

Output :

10)Write a java program to illustrate Legacy classes like Vector, Hash Table,
Dictionary & Enumeration interface.

(a)Vector

/*Implementation of Vector*/

import java.util.*;
public class VectorDemo
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Vector v1 = new Vector();
System.out.println("Vector = " + v1 + ", Size = " + v1.size());
for(int i = 1; i <= 6; i++)
{
v1.add(i);
}
System.out.println("Vector1 = " + v1 + ",Size = " + v1.size() +
",capacity = " + v1.capacity());
System.out.println("Vector1 is empty ? " + v1.isEmpty());
System.out.println("First element = " + v1.firstElement());
System.out.println("Last element = " + v1.lastElement());
v1.insertElementAt(100, 5);
System.out.println("Vector after inserting 100 = " + v1 + ", size = "
+ v1.size());
v1.removeElement(100);
System.out.println("Element removed at 0 index = " +
v1.remove(0));
System.out.println("Vector = " + v1 + ", size = " + v1.size() +
",capacity = " + v1.capacity());
Vector v2 = (Vector)v1.clone();
v1.clear();
System.out.println("Vector1 = " + v1 +", Size = " + v1.size() + ",
Capacity = " + v1.capacity());
System.out.println("Vector2 = " + v2 +", Size = " + v2.size() + ",
Capacity = " + v2.capacity());
}
}
Output :
(b)Hashtable

/*Implementation of Hashtable*/

import java.util.Hashtable;
public class hashTable
{
public static void main(String args[])
{
Hashtable ht = new Hashtable();
System.out.println("Hashtable : " + ht + ", size = " + ht.size());
System.out.println("Hashtable is empty?" + ht.isEmpty());
ht.put(101, "abc");
ht.put(201, "xyz");
ht.put(302, "ijk");
ht.put(321, "jkl");
System.out.println("Hashtable : " + ht + ", size = " + ht.size());
System.out.println("Value at 101 = " + ht.get(101));
ht.remove(201);
System.out.println("Hashtable after removing 201 : " + ht + ", size = " +
ht.size());
ht.replace(321, "james");
System.out.println("Hashtable after replace : " + ht + ", size = " +
ht.size());
boolean status = ht.containsKey(201);
System.out.println("Status of the key 201 = "+status);
ht.clear();
System.out.println("Hashtable : " + ht + ", size = " + ht.size());
System.out.println("Hashtable is empty?" + ht.isEmpty());
}
}

Output :
(c)Dictionary

/*Implementation of dictionary */

import java.util.Dictionary;
import java.util.Hashtable;
public class dictionary
{
public static void main(String args[])
{
Dictionary d = new Hashtable();
System.out.println("Dictionary : " + d + ", size = " + d.size());
System.out.println("Dictionary is empty?" + d.isEmpty());
d.put(101, "abc");
d.put(201, "xyz");
d.put(302, "ijk");
d.put(321, "jkl");
System.out.println("Dictionary : " + d + ", size = " + d.size());
System.out.println("Value at 101 = " + d.get(101));
d.remove(201);
System.out.println("Dictionary after removing 201 : " + d + ", size = " +
d.size());
System.out.println("Dictionary : " + d + ", size = " + d.size());
System.out.println("Dictionary is empty?" + d.isEmpty());
}
}

Output :
(d)Enumeration

/*Implementation of enumeration interface */

import java.util.Enumeration;
import java.util.Vector;
public class enumeration
{
public static void main(String args[])
{
Vector v = new Vector();
System.out.println("Vector = " + v);
for(int i = 1; i <= 5; i++)
{
v.add(i);
}
System.out.println("Vector = " + v);
System.out.println("Traversing vector using enumeration === ");
Enumeration e = v.elements();
while(e.hasMoreElements())
{
System.out.println(e.nextElement());
}
}
}

Output :
11)Write a java program to implement iteration over Collection using Iterator
interface and ListIterator Interface.

/*Implementation of iteration over Collection */

import java.util.*;
public class IterColl
{
public static void main(String args[])
{
ArrayList list = new ArrayList();
for(int i = 10; i <= 15; i++)
{
list.add(i);
}
System.out.println("Items in Arraylist = " + list);
System.out.println("Traversing Arraylist using Iterator = ");
Iterator it = list.iterator();
while(it.hasNext())
{
System.out.println(it.next()+"\t");
}
System.out.println("Traversing ArrayList in forward direction using
ListIterator = ");
ListIterator lit = list.listIterator();
while(lit.hasNext())
{
System.out.println(lit.next()+"\t");
}
System.out.println("Traversing ArrayList in backward direction using
ListIterator = ");
while(lit.hasPrevious())
{
System.out.println(lit.previous()+"\t");
}
System.out.println();
}
}

Output :

You might also like