Java Lab Progs

25
1) Classes and Objects: i. Write a prog in java with class Rectangle with the data fields width,length,area and color.The length ,width,area are of double type and color is string type.The methods are set_length(),set_width(),set_color and find_area().create two objects of Rectangle and compare their area and color.If area and color both are same for the objects then display "Matching rectangles" otherwise display "Non matching rectangles". ii. Write a java program to overload constructor and method . Program 1a: class Rectangle { double length,width,area; String colour; void SetLength(int i) { length=i; } void SetWidth(int j) { width=j; } void SetColour(String col) { colour=col; } void FindArea() { area=length*width; }

description

Java Lab Programs 0f 5th Sem Cs

Transcript of Java Lab Progs

Page 1: Java Lab Progs

1) Classes and Objects:i. Write a prog in java with class Rectangle with the data fields width,length,area and

color.The length ,width,area are of double type and color is string type.The methods are set_length(),set_width(),set_color and find_area().create two objects of Rectangle and compare their area and color.If area and color both are same for the objects then display "Matching rectangles" otherwise display "Non matching rectangles".

ii. Write a java program to overload constructor and method

.Program 1a:

class Rectangle{

double length,width,area;String colour;

void SetLength(int i){

length=i;}

void SetWidth(int j){

width=j;}

void SetColour(String col){

colour=col;}

void FindArea(){

area=length*width;}

boolean compare(rectangle a){

if(colour==a.colour&&area==a.area)return true;

elsereturn false;

}}

Page 2: Java Lab Progs

class RectDemo{

public static void main(String args[]){

rectangle r1 = new rectangle();rectangle r2 = new rectangle();boolean b = false;

r1.SetLength(5);r2.SetLength(8);

r1.SetWidth(8);r2.SetWidth(5);

r1.SetColour("Red");r2.SetColour("Red");

r1.FindArea();r2.FindArea();b=r1.compare(r2);

if(b==true)System.out.println("Matching Rectangle");

elseSystem.out.println("Not Matching Rectangle");

}}

Output:Matching Rectangle

Page 3: Java Lab Progs

Program 1b :

class Shape{

double lnt,bdt,a;

Shape(double l){

lnt=l;}Shape(double l,double b){

lnt=l;bdt=b;

}

void area(double l){

a=l*l;System.out.println("Area="+a);

}void area(double l,double b){

a=l*b;System.out.println("Area="+a);

}}class Overloadcf{

public static void main(String args[]){

Shape s1=new Shape(5.000);Shape s2=new Shape(5.000,6.000);s1.area(s1.lnt);s2.area(s2.lnt,s2.bdt);

System.out.println("Now if we pass only the length for Rectangle");s2.area(s2.lnt);

}}

Output:Area=25.0Area=30.0Now if we pass only the length for RectangleArea=25.0

Page 4: Java Lab Progs

2) Inheritance and Polymorphismi. Write a program in java to create player class.inherit the classes Cricket_player,

Football_Player and Hockey_player from Player classii. Consider the trunk calls of a telephone exchange.A trunk call can be ordinary,urgent

or lightning.The charges depend on the duration and type of the call.Write a program using the concept of polymorphism to calculate the charges.

Program 2a:

class Player{

String name;int age,matches,ranking;Player(String n,int a,int m,int r){

name=n;age=a;matches=m;ranking=r;

}}class Cricket_Player extends Player{

int High_score,Bowl_average,Bat_average;Cricket_Player(String a,int b,int c,int d,int e,int f,int g){

super(a,b,c,d);High_score=e;Bat_average=f;Bowl_average=g;

}void disp(){

System.out.println("Name: "+name);System.out.println("Age: "+age);System.out.println("No. of Matches: "+matches);System.out.println("Highest Score: "+High_score);System.out.println("Batting Average: "+Bat_average);System.out.println("Balling Average: "+Bowl_average);System.out.println("Player Ranking: "+ranking);

}}

Page 5: Java Lab Progs

class Football_Player extends Player{

int goals,g_avg,pass;Football_Player(String a,int b,int c,int d,int e,int f,int g){

super(a,b,c,d);goals=e;g_avg=f;pass=g;

}void disp(){

System.out.println("Name: "+name);System.out.println("Age: "+age);System.out.println("No. of Matches: "+matches+"\n");System.out.println("No. of Goals: "+goals);System.out.println("Golas Average: "+g_avg);System.out.println("Passing Efficiency: "+pass+"%");System.out.println("Player Ranking: "+ranking);

}}class Hockey_Player extends Player{

int goals,g_avg,pass;Hockey_Player(String a,int b,int c,int d,int e,int f,int g){

super(a,b,c,d);goals=e;gavg=f;pass=g;

}void disp(){

System.out.println("Name: "+name);System.out.println("Age: "+age);System.out.println("No. of Matches: "+matches);System.out.println("No. of Goals: "+goals);System.out.println("Golas Average: "+g_avg);System.out.println("Passing Efficiency: "+pass+"%");System.out.println("Player Ranking: "+ranking);

}}

Page 6: Java Lab Progs

class Inherit{

public static void main(String args[]){Cricket_Player C=new Cricket_Player("Sachin Tendulkar",38,600,8,200,55,60);Football_Player F=new Football_Player("Leonel Messi",32,120,90,3,80,94);Hockey_Player H=new Hockey_Player("Dhanraj Pillay",32,120,90,3,80,94);

C.disp();F.disp();H.disp();

}}

Output:

Name: Sachin TendulkarAge: 38No. of Matches: 600Highest Score: 200Batting Average: 55Balling Average: 60Player Ranking: 1

Name: Leonel messiAge: 32No. of Matches: 120No. of Goals: 3Golas Average: 80Passing Efficiency: 94%Player Ranking: 10

Name: Dhanraj PillayAge: 32No. of Matches: 120No. of Goals: 3Golas Average: 80Passing Efficiency: 94%Player Ranking: 90

Page 7: Java Lab Progs

Program 2b:

class trunk{double duration;double charge;

trunk(){duration=0;charge=0;}

trunk(double d){duration=d;}

void cal_charge(){System.out.println("no mechanisms");}

}

class ordinary extends trunk{double call_rate;

ordinary(){super();call_rate=0.60;}

ordinary(double d){super(d);call_rate=0.60;}

ordinary(double d,double f){super(d);call_rate=f;}

Page 8: Java Lab Progs

void cal_charge(){charge=duration*call_rate;System.out.println("For ordinary charge :"+charge);}

}

class urgent extends trunk{double call_rate;

urgent(){super();call_rate=1.0;}

urgent(double d){super(d);call_rate=1.0;}

urgent(double d,double f){super(d);call_rate=f;}

void cal_charge(){charge=duration*call_rate;System.out.println("for urgent charge:"+charge);}

}

class lightning extends trunk{double call_rate;

lightning(){super();call_rate=1.2;}

Page 9: Java Lab Progs

lightning(double d){super(d);call_rate=1.2;}

lightning(double d,double f){super(d);call_rate=f;}

void cal_charge(){charge=duration*call_rate;System.out.println("for lightning charge:"+charge);}

}

class telephone{ public static void main(String args[]) {

trunk tref=new trunk();ordinary ordi=new ordinary(4);urgent urg=new urgent(1.0,2.0);lightning lig=new lightning(2.0,3.0);

tref=ordi;tref.cal_charge();

tref=urg;tref.cal_charge();

tref=lig;tref.cal_charge();

}}

OutputFor ordinary charge :2.4for urgent charge:2.0for lightning charge:6.0

Page 10: Java Lab Progs

3) Package and Interface:i. Write a program to make a package Balance in which has account class with

display_balance method in it.Import balance package in another program to access Display_balance method of account class.

ii. Create the dynamic stack by implementing the interfaces that defines Push() and Pop() methods.

Program 3a:

package Balance;public class Account{

double p,i,r,balance;int t;public Account(double pr,int ti,double ra){

p=pr;t=ti;r=ra;

}public void cal(){

balance=p*r*t;}public void Disply_Balance(){

System.out.println("\n\nPrincipal Amount: "+p+"Rs\nTime: "+t+"Years\n\nCurrent Balance: "+balance+"Rs");

}}

import Balance.*;class Pack{

public static void main(String args[]){

Account b1=new Account(5000,2,0.12);b1.cal();b1.Disply_Balance();

}}

Output:Principal Amount: 5000.0RsTime: 2YearsCurrent Balance: 1200.0Rs

Page 11: Java Lab Progs

Program 3b:

interface instack{

void push(int item);int pop();

}

class dstack implements instack{

private int stk[];private int tos;

dstack(int size){stk=new int[size];tos=-1;}

public void push(int item){if(tos==stk.length-1) { int temp[]=new int[stk.length*2]; for(int i=0;i<stk.length;i++)

temp[i]=stk[i]; stk=temp;

stk[++tos]=item; }else stk[++tos]=item;}

public int pop(){if(tos<0){System.out.println("stack underflow");return 0;}else return stk[tos--];}

}

Page 12: Java Lab Progs

class Dyn_stack{

public static void main(String args[]){dstack mystack1=new dstack(5);dstack mystack2=new dstack(8);

for(int i=0;i<20;i++)mystack1.push(i);for(int i=0;i<20;i++)mystack2.push(i);

System.out.print("\t Elements in stack1 -> "); for(int i=0;i<20;i++) System.out.print(mystack1.pop()+" ");

System.out.println();

System.out.print("\t Elements in stack2 -> "); for(int i=0;i<20;i++) System.out.print(mystack2.pop()+" "); System.out.println();

}

}

Output: Elements in stack1 -> 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 Elements in stack2 -> 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

Page 13: Java Lab Progs

4) Exception Handling:i. On a single track two vehicles are running.As vehicles are going on same direction

there is no problem .If the vehicles are running in different direction there is a chance of collision.To avoid collision write a java program using Exception handling.

Program 4a:

class collision{String i,j;collision(String a,String b){

i=a;j=b;

}void check(){

try{

if(i==j){

System.out.println("The two vehicles are moving in same direction, hence no problem");

}else{

throw new Exception("The two vehicles are moving in different directions,so collision occurs");

}}catch(Exception e){

System.out.println(e);}}

}

class exception{public static void main(String args[]){

collision s=new collision("north","north");collision n=new collision("north","east");s.check();System.out.println();

Page 14: Java Lab Progs

n.check();System.out.println();

}}

Output:The two vehicles are moving in same direction,hence no problemjava.lang.Exception: The two vehicles are moving in different

Page 15: Java Lab Progs

5) Multithreading:i. Write a program in java to create five java threads with different priorities.send two

threads of higher priority to sleep state.Check the aliveness of the threads and mark which thread is long lasting.

ii. Write a Multi_threaded java program to implement producer-consumer problem.

Program 5a:

class MulThread implements Runnable {

static String last;String name;Thread t;MulThread(String n,int p){

name=n;t=new Thread(this, name);t.setPriority(p);System.out.println(name+" started");System.out.println("new thread: "+t);t.start();

}

public void run() {

try{

if((t.getPriority()==9)||(t.getPriority()==10)){

Thread.sleep(1000);System.out.println(t.getName()+" is going to sleep");

}for(int i=0;i<5;i++){

System.out.println(name+":"+i);Thread.sleep(500);

} }

catch(InterruptedException e) {

System.out.println(name+" thread interrupted");

}last=name;System.out.println(name+" exiting");

}}

Page 16: Java Lab Progs

class NewThread{

public static void main(String args[]){ Thread.currentThread().setPriority(Thread.MAX_PRIORITY);MulThread m1=new MulThread("one",Thread.NORM_PRIORITY-1);MulThread m2=new MulThread("two",Thread.MAX_PRIORITY);MulThread m3=new MulThread("three",Thread.NORM_PRIORITY+2);MulThread m4=new MulThread("four",Thread.NORM_PRIORITY+4);MulThread m5=new MulThread("five",Thread.MIN_PRIORITY+1);

try{

Thread.sleep(500);}catch(InterruptedException e){

System.out.println("main thread interrupted");}

System.out.println("Thread one is:"+m1.t.isAlive()); System.out.println("Thread two is:"+m2.t.isAlive()); System.out.println("Thread three is:"+m3.t.isAlive()); System.out.println("Thread four is:"+m4.t.isAlive()); System.out.println("Thread five is:"+m5.t.isAlive());

try{

System.out.println("waiting for thread to finish");m1.t.join();m2.t.join();m3.t.join();m4.t.join();m5.t.join();

}catch(InterruptedException e){

System.out.println("main thread interrupted");}

System.out.println("thread one is:"+m1.t.isAlive());System.out.println("thread two is:"+m2.t.isAlive());System.out.println("thread three is:"+m3.t.isAlive());System.out.println("thread four is:"+m4.t.isAlive());System.out.println("thread five is:"+m5.t.isAlive());System.out.println();System.out.println("priority of one:"+m1.t.getPriority());System.out.println("priority of two:"+m2.t.getPriority());System.out.println("priority of three:"+m3.t.getPriority());System.out.println("priority of four:"+m4.t.getPriority());System.out.println("priority of five:"+m5.t.getPriority());System.out.println();

Page 17: Java Lab Progs

System.out.println(MulThread.last+" is long lasting thread");}

}

Output:

one startednew thread: Thread[one,4,main]two startednew thread: Thread[two,10,main]three startednew thread: Thread[three,7,main]one:0four startednew thread: Thread[four,9,main]three:0five startednew thread: Thread[five,2,main]five:0Thread one is:trueThread two is:trueThread three is:trueThread four is:trueThread five is:truewaiting for thread to finishthree:1one:1five:1two is going to sleepfour is going to sleepfour:0two:0three:2one:2five:2four:1two:1three:3one:3five:3two:2four:2three:4one:4five:4four:3two:3

Page 18: Java Lab Progs

three exitingfive exitingone exitingtwo:4four:4four exitingtwo exitingthread one is:falsethread two is:falsethread three is:falsethread four is:falsethread five is:false

priority of one:4priority of two:10priority of three:7priority of four:9priority of five:2

two is long lasting thread

Page 19: Java Lab Progs

Program 5b:

class Q{int n;boolean valueset=false;

synchronized int get(){while(!valueset)

try{wait();} catch(InterruptedException e){System.out.println("interrupted exception 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("interrupted exception caught");}

this.n=n;valueset=true;System.out.println("put:"+n);notify();}}

Page 20: Java Lab Progs

class producer implements Runnable{Q q;producer(Q q){this.q=q;new Thread(this,"producer").start();}

public void run(){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();}}

}

class pcfixed{public static void main(String args[]){

Q q=new Q();new producer(q);new consumer(q);System.out.println("press control-c to stop");

}

Page 21: Java Lab Progs

}

Output:

put:58633got:58633put:58634got:58634put:58635got:58635put:58636got:58636