Java Lab Programs
Java Lab Programs
if(arr[fIndex] == searchNum)
{
System.out.print(fIndex);
}
else
{
linSearch2(arr, fIndex+1, lIndex, searchNum);
}
}
}
}
----------------------------------------------------------------------3. Implement linked list showing all the basic operations.
/*
*
*/
import java.util.Scanner;
/*
Class Node
*/
class Node
{
protected int data;
protected Node link;
/*
Constructor
public Node()
{
link = null;
data = 0;
*/
}
/*
Constructor
*/
*/
*/
*/
*/
/* Class linkedList */
class linkedList
{
protected Node start;
protected Node end ;
public int size ;
/*
Constructor
*/
public linkedList()
{
start = null;
end = null;
size = 0;
}
/*
*/
*/
*/
{
start = nptr;
end = start;
}
else
{
nptr.setLink(start);
start = nptr;
}
}
/*
*/
*/
*/
while (s != end)
{
t = s;
s = s.getLink();
}
end = t;
end.setLink(null);
size --;
return;
}
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{
Node tmp = ptr.getLink();
tmp = tmp.getLink();
ptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size-- ;
}
/*
*/
{
System.out.print("empty\n");
return;
}
if (start.getLink() == null)
{
System.out.println(start.getData() );
return;
}
Node ptr = start;
System.out.print(start.getData()+ "->");
ptr = start.getLink();
while (ptr.getLink() != null)
{
System.out.print(ptr.getData()+ "->");
ptr = ptr.getLink();
}
System.out.print(ptr.getData()+ "\n");
}
}
/*
Class SinglyLinkedList
*/
*/
do
{
System.out.println("\nSingly Linked List Operations\n");
System.out.println("1. insert at begining");
System.out.println("2. insert at end");
System.out.println("3. insert at position");
System.out.println("4. delete at position");
System.out.println("5. check empty");
System.out.println("6. get size");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println("Enter integer element to insert");
list.insertAtStart( scan.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to insert");
list.insertAtEnd( scan.nextInt() );
break;
case 3 :
System.out.println("Enter integer element to insert");
int num = scan.nextInt() ;
System.out.println("Enter position");
int pos = scan.nextInt() ;
if (pos <= 1 || pos > list.getSize() )
System.out.println("Invalid position\n");
else
list.insertAtPos(num, pos);
break;
case 4 :
System.out.println("Enter position");
int p = scan.nextInt() ;
if (p < 1 || p > list.getSize() )
System.out.println("Invalid position\n");
else
list.deleteAtPos(p);
break;
case 5 :
System.out.println("Empty status = "+ list.isEmpty());
break;
case 6 :
System.out.println("Size = "+ list.getSize() +" \n");
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
/*
Display List
*/
list.display();
System.out.println("\nDo you want to continue (Type y or n)
\n");
ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}
-----------------------------------------------------------------------
/*
*
*/
import java.util.Scanner.*;
/*
Class Node
*/
class Node
{
protected int data;
protected Node next, prev;
/* Constructor */
public Node()
{
next = null;
prev = null;
data = 0;
}
/* Constructor */
public Node(int d, Node n, Node p)
{
data = d;
next = n;
prev = p;
}
/* Class linkedList */
class linkedList
{
protected Node start;
protected Node end ;
public int size;
/* Constructor */
public linkedList()
{
start = null;
end = null;
size = 0;
}
/* Function to check if list is empty */
public boolean isEmpty()
{
return start == null;
}
/* Function to get size of list */
public int getSize()
{
return size;
}
/* Function to insert element at begining */
public void insertAtStart(int val)
{
}
/* Function to insert element at position */
public void insertAtPos(int val , int pos)
{
Node nptr = new Node(val, null, null);
if (pos == 1)
{
insertAtStart(val);
return;
}
Node ptr = start;
for (int i = 2; i <= size; i++)
{
if (i == pos)
{
Node tmp = ptr.getLinkNext();
ptr.setLinkNext(nptr);
nptr.setLinkPrev(ptr);
nptr.setLinkNext(tmp);
tmp.setLinkPrev(nptr);
}
ptr = ptr.getLinkNext();
}
size++ ;
}
/* Function to delete node at position */
public void deleteAtPos(int pos)
{
if (pos == 1)
{
if (size == 1)
{
start = null;
end = null;
size = 0;
return;
}
start = start.getLinkNext();
start.setLinkPrev(null);
size--;
return ;
}
if (pos == size)
{
end = end.getLinkPrev();
end.setLinkNext(null);
size-- ;
}
Node ptr = start.getLinkNext();
for (int i = 2; i <= size; i++)
{
if (i == pos)
{
Node p = ptr.getLinkPrev();
Node n = ptr.getLinkNext();
p.setLinkNext(n);
n.setLinkPrev(p);
size-- ;
return;
}
ptr = ptr.getLinkNext();
}
}
/* Function to display status of list */
public void display()
{
System.out.print("\nDoubly Linked List = ");
if (size == 0)
{
System.out.print("empty\n");
return;
}
if (start.getLinkNext() == null)
{
System.out.println(start.getData() );
return;
}
Node ptr = start;
System.out.print(start.getData()+ " <-> ");
ptr = start.getLinkNext();
while (ptr.getLinkNext() != null)
{
System.out.print(ptr.getData()+ " <-> ");
ptr = ptr.getLinkNext();
}
System.out.print(ptr.getData()+ "\n");
}
}
/* Class DoublyLinkedList */
public class DoublyLinkedList
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of linkedList */
linkedList list = new linkedList();
System.out.println("Doubly Linked List Test\n");
char ch;
/*
*/
do
{
System.out.println("\nDoubly Linked List Operations\n");
System.out.println("1. insert at begining");
System.out.println("2. insert at end");
System.out.println("3. insert at position");
System.out.println("4. delete at position");
System.out.println("5. check empty");
System.out.println("6. get size");
}
/*
Display List
*/
list.display();
System.out.println("\nDo you want to continue (Type y or n)
\n");
ch = scan.next().charAt(0);
/**
** Java Program to implement Priority Queue
**/
import java.util.Scanner;
this.priority = priority;
}
/** toString() **/
public String toString()
{
return "Job Name : "+ job +"\nPriority : "+ priority;
}
}
heap[++heapSize] = newJob;
int pos = heapSize;
while (pos != 1 && newJob.priority > heap[pos/2].priority)
{
heap[pos] = heap[pos/2];
pos /=2;
}
heap[pos] = newJob;
}
/** function to remove task **/
public Task remove()
{
int parent, child;
Task item, temp;
if (isEmpty() )
{
System.out.println("Heap is empty");
return null;
}
item = heap[1];
temp = heap[heapSize--];
parent = 1;
child = 2;
while (child <= heapSize)
{
if (child < heapSize && heap[child].priority < heap[child +
1].priority)
child++;
if (temp.priority >= heap[child].priority)
break;
heap[parent] = heap[child];
parent = child;
child *= 2;
}
heap[parent] = temp;
return item;
}
char ch;
/*
do
{
System.out.println("\nPriority Queue Operations\n");
System.out.println("1. insert");
System.out.println("2. remove");
System.out.println("3. check empty");
System.out.println("4. check full");
System.out.println("5. clear");
System.out.println("6. size");
/*output:
Priority Queue Test
Enter size of priority queue
7
Priority Queue Operations
1. insert
2. remove
3. check empty
4. check full
5. clear
6. size
1
Enter job name and priority
job1 24
Do you want to continue (Type y or n)
y
Priority Queue Operations
1.
2.
3.
4.
5.
6.
insert
remove
check empty
check full
clear
size
*/
import java.lang.*;
import java.io.*;
class MatMulti extends Thread
{
static int in1[][];
static int in2[][];
static int out[][];
static int n=2;
int row;
MatMulti(int i)
{
row=i;
this.start();
}
public void run()
{
int i,j;
for(i=0;i<n;i++)
{
out[row][i]=0;
for(j=0;j<n;j++)
out[row][i]=out[row][i]+in1[row]
[j]*in2[j][i];
}
}
public static void main(String args[])
{
int i,j;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter the order of Matrix : ");
try
{
n=Integer.parseInt(br.readLine());
}catch(Exception e){}
in1=new int[n][n];
in2=new int[n][n];
out=new int[n][n];
System.out.println("Enter the First Matrix : ");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
try
{
in1[i]
[j]=Integer.parseInt(br.readLine());
}catch(Exception e){}
}
}
System.out.println("Enter the Second Matrix : ");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
try
{
in2[i]
[j]=Integer.parseInt(br.readLine());
}catch(Exception e){}
}
}
MatMulti mat[]=new MatMulti[n];
for(i=0;i<n;i++)
mat[i]=new MatMulti(i);
try
{
for(i=0;i<n;i++)
mat[i].join();
}catch(Exception e){}
System.out.println("OUTPUT :");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
System.out.println(out[i][j]);
}
}
----------------------------------------------------------------------9. Implement an abstract class named Person and two subclasses named Student and
Employee. A person has a name, address, phone number and e-mail address. A student
has a class status (freshman, second year junior or senior). Define the status as a
constant. An employee has an office, salary and date-hired. Implement the above
classes. Provide Constructors for classes to initialize private variables. Override the
toString method in each class to display the class name and the persons name. Write an
application to create objects of type Student and Employee and print the persons name and the class name of the objects.
na=name;
ID=id;
}
abstract public void tooString();
}
if(status==1)
{
curst="Freshman";
}
else if(status==2)
{
curst="Second Year";
}
else
{
curst="Senior";
}
}
public void tooString()
{
System.out.println("The Details
are\nName:"+na+"ID:"+ID+"Current Status:"+curst);
}
}
salary=sal;
}
public void tooString()
{
System.out.println("The Details are\nName:"+na+"ID:"+ID+"Date
Of hire:"+dhire+"Salary:"+salary+"Office:"+off);
}
}
class Morph
{
public static void main(String v[])
{
Student s=new Student("XYZ",345,3);
Employee e=new
Employee("ABC",345,"25/9/14","Bangalore",35000);
s.tooString();
e.tooString();
}
}
-------------------------------------------------------------------------------------------------------------------------------10. Write a program to show that private member of a super class cannot be accessed
from derived classes.
i=x;
j=y;
}
}
//sub class
class B extends A
{
int total;
void sum()
{
total=i+j;
}
}
----------------------------------------------------------------------11. Write a program in Java to create a Player class. Inherit the classes Cricket Player,
Football Player and Hockey Player from Player class.
class Player{
String name;
int age;
Player(String n,int a){
name=n; age=a;
}
void show(){
System.out.println("\n");
System.out.println("Player name : "+name);
System.out.println("Age: "+age);
}
}
class CricketPlayer extends Player{
String type;
CricketPlayer(String n,String t,int a){
super(n,a);
type=t;
}
public void show(){
super.show();
System.out.println("Player type : "+type);
}
}
class FootballPlayer extends Player{
String type;
FootballPlayer(String n,String t,int a){
super(n,a);
type=t;
}
public void show(){
super.show();
System.out.println("Player type : "+type);
}
}
class HockeyPlayer extends Player{
String type;
HockeyPlayer(String n,String t,int a){
super(n,a);
type=t;
}
public void show(){
super.show();
System.out.println("Player type : "+type);
}
}
class TestPlayer{
public static void main(String args[]){
CricketPlayer c=new CricketPlayer("A","Cricket",25);
FootballPlayer f=new FootballPlayer("B","Football",25);
HockeyPlayer h=new HockeyPlayer("C","Hockey",25);
c.show();
f.show();
h.show();
}
}
----------------------------------------------------------------------12. Write a class Worker and derive classes DailyWorker and SalariedWorker from it.
Every worker has a name and a salary rate. Write method ComPay (int hours) to compute
the week pay of every worker. A Daily Worker is paid on the basis of the number of days
she/he works. The Salaried Worker gets paid the wage for 40 hours a week no matter
what the actual hours are. Test this program to calculate the pay of workers. You are
expected to use the concept of polymorphism to write this program.
class Worker{
String name;
int empno;
Worker(int no,String n){
empno=no; name=n;
}
void show(){
System.out.println("Employee number : "+empno);
System.out.println("Employee name: "+name);
}
}
class DailyWorker extends Worker{
int rate;
DailyWorker(int no,String n,int r){
super(no,n);
rate=r;
}
void company(int h){
show();
System.out.println("Salary : "+(rate*h));
}
}
class SalariedWorker extends Worker{
int rate;
SalariedWorker(int no,String n,int r){
super(no,n);
rate=r;
}
int hour=40;
void company(){
show();
System.out.println("Salary : "+(rate*hour));
}
}
class TestWorker{
public static void main(String args[]){
DailyWorker d=new DailyWorker(11,"A",75);
SalariedWorker s=new SalariedWorker(22,"B",100);
d.company(45);
s.company();
}
}
----------------------------------------------------------------------13. Consider the trunk calls of a telephone exchange. A trunk call can be ordinary, urgent
or lightning. The charges depend on the duration and the type of the call. Writ a program
using the concept of polymorphism in Java to calculate the charges.
import java.util.*;
class Calls{
float dur;
String type;
float rate(){
if(type.equals("urgent"))
return 4.5f;
else if(type=="lightning")
return 3.5f;
else
return 3f;
}
}
class Bill extends Calls{
float amount;
void read(){
Scanner input=new Scanner(System.in);
System.out.print("Enter Call Type(urgent,lightning,ordinary): ");
type=input.next();
System.out.print("Enter Call duration:");
dur=input.nextFloat();
}
void calculate(){
if(dur<=1.5){
amount=rate()*dur+1.5f;
}
else if(dur<=3){
amount=rate()*dur+2.5f;
}
else if(dur<=5){
amount=rate()*dur+4.5f;
}
else{
amount=rate()*dur+5f;
}
}
void print(){
System.out.println(" Call Type : "+type);
System.out.println(" Duration : "+dur);
System.out.println(" Charge: "+amount);
}
}
class TelephoneExchange{
public static void main(String arg[]){
String x="yes";
Scanner input=new Scanner(System.in);
while(x.equals("yes")||x.equals("Y"))
{
Bill b=new Bill();
b.read();
b.calculate();
b.print();
System.out.println("Do you want another transaction? TYPE yes if you
want to");
input.next();
}
}
}
----------------------------------------------------------------------15. Create an Interface having two methods division and modules. Create a class, which
overrides these methods.
interface Artth_operations
{
void division(int a,int b);
void modules(int c, int d);
}
class DivisionModulus
{
public static void main(String args[])
{
calculate s=new calculate();
s.division(15, 3);
s.modules(15, 4);
s.disp();
}
}
-------------------------------------------------------------16. Write a program in Java which implements interface Student which has two methods
Display Grade and Attendance for PG Students and UG Students (PG Students and UG
Students are two different classes for Post Graduate and Under Graduate students
respectively).
import java.io.*;
interface student
{
void disp_grade();
void disp_attendance();
}
class pg_stud implements student
{
String name,grade;
int reg,m1,m2,m3,att;
void read()throws Exception
{
DataInputStream in= new DataInputStream(System.in);
System.out.println("enter the register no : ");
reg=Integer.parseInt(in.readLine());
System.out.println("enter the name : ");
name=in.readLine();
System.out.println("enter attendance : ");
att=Integer.parseInt(in.readLine());
System.out.println("enter mark1 : ");
m1=Integer.parseInt(in.readLine());
System.out.println("enter mark2 : ");
m2=Integer.parseInt(in.readLine());
System.out.println("enter mark3 : ");
m3=Integer.parseInt(in.readLine());
}
public void disp_grade()
{
int tt=m1+m2+m3;
if(tt>=250) grade="A";
else if(tt>=200) grade="B";
else if(tt>=150) grade="C";
else if(tt>=100) grade="D";
else grade="E";
System.out.println("Grade:"+grade);
}
public void disp_attendance()
{
System.out.println("Attendance:"+att);
}
void disp()
{
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" MARK LIST OF PG STUDENTS");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Register No :"+reg);
System.out.println("Name:"+name);
System.out.println("Mark1 :"+m1);
System.out.println("Mark2:"+m2);
System.out.println("Mark3 :"+m3);
disp_grade();
disp_attendance();
}
}class ug_stud implements student
{
String name,grade;
int reg,m1,m2,m3,att;
void read()throws Exception
{
DataInputStream in= new DataInputStream(System.in);
System.out.println("enter the register no : ");
reg=Integer.parseInt(in.readLine());
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Register No :"+reg);
System.out.println("Name:"+name);
System.out.println("Mark1 :"+m1);
System.out.println("Mark2 :"+m2);
System.out.println("Mark3 :"+m3);
disp_grade();
disp_attendance();
}
}
class StudentInterface
{
public static void main(String args[])throws Exception
{
pg_stud pg=new pg_stud();
pg.read();
pg.disp();
ug_stud ug=new ug_stud();
ug.read();
ug.disp();
}
}
----------------------------------------------------------------------17. Write a program in Java to display the names and roll numbers of students. Initialize
respective array variables for 10 students. Handle ArrayIndexOutOfBoundsExeption, so
that any such problem doesnt cause illegal termination of program.
import java.io.*;
class student
{
String name,grade;
int reg,m1,m2,m3;
void read()throws Exception
{
DataInputStream in= new DataInputStream(System.in);
System.out.println("enter the register no : ");
reg=Integer.parseInt(in.readLine());
System.out.println("enter the name : ");
name=in.readLine();
System.out.println("enter mark1 : ");
m1=Integer.parseInt(in.readLine());
System.out.println("enter mark2 : ");
m2=Integer.parseInt(in.readLine());
System.out.println("enter mark3: ");
m3=Integer.parseInt(in.readLine());
}
public void disp_grade()
{
int tt=m1+m2+m3;
if(tt>=250)
grade="A";
else if(tt>=200) grade="B";
else if(tt>=150) grade="C";
else if(tt>=100) grade="D";
else grade="E";
System.out.println("Grade :"+grade);
}void disp()
{
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" MARK LIST OF STUDENTS ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Register No :"+reg);
System.out.println("Name :"+name);
System.out.println("Mark1 :"+m1);
System.out.println("Mark2 :"+m2);
System.out.println("Mark3 :"+m3);
disp_grade();}
}
class AIOBException
{
public static void main(String ar[])
{
int no=0;
student s=new student();
try
{
DataInputStream in= new DataInputStream(System.in);
System.out.println("enter the number of students :
");no=Integer.parseInt(in.readLine());
for(int i=0;i<no;i++);
s.read();
}catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("the maximum students should be ten\n");no=10;}
catch(Exception e)
{
System.out.println(e);
}
for(int i=0;i<no;i++);
s.disp();
}
----------------------------------------------------------------------18. Write a program to solve N queens problem. Provide solution applying branch and
bound, and backtracking methods. Provide necessary GUI to display the solution.
// not exactly got.. done for 8queens
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
wholepanel.add("Center", boardpanel);
solnumtext = new JTextArea(10,20);
JScrollPane scroller = new JScrollPane(solnumtext);
wholepanel.add("South", scroller);
solnumtext.setEditable(false);
queencol = new int[boardsize];
return wholepanel;
}
k++;
}
return answer;
}
try {
UIManager.setLookAndFeel(laf);
}
catch (UnsupportedLookAndFeelException exc) {
System.out.println("Unsupported: " + laf);
}
catch (Exception exc) {
System.out.println("Error loading: " + laf);
}
if (args.length == 0)
howmany = 8;
else {
try {
howmany = Integer.parseInt(args[0]);
}
catch (NumberFormatException ne) {
howmany = 4;
}
try {
sleepAmount = Integer.parseInt(args[1]);
}
catch (Exception e) {
}
}
nqf = new JFrame("N Queens " + howmany);
Component contents = nq.createComponents(howmany, sleepAmount);
nqf.getContentPane().add(contents,BorderLayout.CENTER);
nqf.setBackground(Color.white);
nqf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
nqf.setSize(400, 400);
nqf.show();
//nq.addqueen();
nq.queens(-1);
} catch (ArithmeticException e)
{
a[i]=1;
}
}
}
}
----------------------------------------------------------------------20. Create an exception class, which throws an exception if operand is nonnumeric in
calculating modules. (Use command line arguments).
}
----------------------------------------------------------------------21. On a single track two vehicles are running. As vehicles are going in same direction
there is no problem. If the vehicles are running in different direction there is a chance of
collision. To avoid collisions write a Java program using exception handling. You are free
to make necessary assumptions.
import java.io.*;
class collision extends Exception
{
collision(String s)
{
super(s);
}
}
class TwoVehicles
{
public static void main(String ar[])
{
String t1=null,t2=null;
try
{
DataInputStream in= new DataInputStream(System.in);
System.out.println("enter the direction of vehicle1:(left/right):");
t1=in.readLine();
System.out.println("enter the direction of vehicle2:(left/right):");
t2=in.readLine();
if(!t1.equals(t2))
throw new collision("truck2 has to go on "+ t1 +" direction");
}
catch(collision e)
{
System.out.println(e);
t2=t1;
System.out.println("the collision has been avoided by redirection
truck2");
}
catch(Exception e)
{
System.out.println(e); }
System.out.println("direction of truck1 :"+t1);
System.out.println("direction of truck2 :"+t2);
}
}
-----------------------------------------------------------------22. Write a program for generating 2 threads, one for printing even numbers and the
other for printing odd numbers.
catch(Exception e)
{System.out.println("thread interepted");}
}
}
class ThreadEvenOdd
{
public static void main(String arg[])
{
even e=new even();
odd o=new odd();
}
}
--------------------------------------------------------------------23. Write a Java Applet program which reads your name and address in different text
fields and when a button named find is pressed the sum of the length of characters in
name and address is displayed in another text field.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="s09_01.class" width=400 height=400>
</applet>
*/
public class s09_01 extends Applet implements ActionListener {
public void init() {
label1 = new Label();
label2 = new Label();
label3 = new Label();
t1 = new TextField();
t2 = new TextField();
t3 = new TextField();
b1 = new Button();
setLayout(null);
setBackground(new Color(0, 153, 102));
label1.setAlignment(Label.RIGHT);
label1.setText("Name");
add(label1);
label1.setBounds(140, 60, 50, 20);
label2.setAlignment(Label.RIGHT);
label2.setText("Address");
add(label2);
label2.setBounds(140, 90, 50, 20);
label3.setAlignment(Label.RIGHT);
label3.setText("Total length");
add(label3);
label3.setBounds(130, 120, 60, 20);
add(t1);
t1.setBounds(200, 60, 100, 20);
add(t2);
t2.setBounds(200, 90, 100, 20);
add(t3);
t3.setBounds(200, 120, 100, 20);
b1.setBackground(new Color(255, 204, 153));
b1.setLabel("Total");
b1.addActionListener(this);
add(b1);
b1.setBounds(150, 180, 80, 24);
}
public void actionPerformed(ActionEvent ae)
{
int a=t1.getText().length();
a+=t2.getText().length();
t3.setText(Integer.toString(a));
}Label label1;
Label label2; Label label3; TextField t1; TextField t2; TextField t3;
Button b1;
}
----------------------------------------------------------------------THE END!!! ALL THE BEST EVERYONE
-----------------------------------------------------------------------