0% found this document useful (0 votes)
38 views

16bce0077 Java Lab 3

1. This document describes three Java programs: - A BankAccount class that throws exceptions for negative deposits or withdrawals and includes two constructors. - A program that simulates an election by generating random votes for three candidates and using four threads to count the votes concurrently. - A share trading system class that uses synchronization and wait/notify to control access to a shared variable as it is updated by different trader threads.

Uploaded by

Majety S Lskshmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

16bce0077 Java Lab 3

1. This document describes three Java programs: - A BankAccount class that throws exceptions for negative deposits or withdrawals and includes two constructors. - A program that simulates an election by generating random votes for three candidates and using four threads to count the votes concurrently. - A share trading system class that uses synchronization and wait/notify to control access to a shared variable as it is updated by different trader threads.

Uploaded by

Majety S Lskshmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

JAVA LAB -6

Harshit Aggarwal
16BCE0077

1. Write a Java Program to create a Class BankAccount that maintains a bank


account balance. Its constructors and methods throw a
NegativeAmountexception if there is an attempt to make the balance negative,
deposit a negative amount and withdraw a negative amount. Class BankAccount
supports two constructors- creating a new bank account with an empty balance
and creating a new bank account with a positive balance.

m
er as
class NegativeAmountException extends Exception{
NegativeAmountException(String s){

co
super(s);

eH w
}
}

o.
class BankAccount{
rs e
ou urc
private float balance;
o

BankAccount(){
this.balance = 0;
aC s

}
v i y re

BankAccount(float bal) throws NegativeAmountException{


if(bal<0) {
throw new NegativeAmountException("Enter Positive amount");
ed d

}
ar stu

else
this.balance = bal;
}
sh is

public void withdraw(float bal) throws NegativeAmountException{


if(bal<0) {
Th

throw new NegativeAmountException("Please withdraw positive


amount");
}
else
this.balance-= bal;
}

public static void main(String args[]){


try {
BankAccount account1 = new BankAccount(); // empty balance
BankAccount account2 = new BankAccount(5000);//deposit amount
account2.withdraw(2000); // money withdrawn
BankAccount account3 = new BankAccount(-8000);//exception

This study source was downloaded by 100000790675436 from CourseHero.com on 05-20-2021 00:04:41 GMT -05:00

https://www.coursehero.com/file/39618607/16BCE0077-JAVA-LAB-3docx/
}catch(Exception m){System.out.println("Exception occured: "+m);}
}
}

m
er as
co
eH w
o.
rs e
ou urc
o
aC s
v i y re
ed d
ar stu
sh is
Th

This study source was downloaded by 100000790675436 from CourseHero.com on 05-20-2021 00:04:41 GMT -05:00

https://www.coursehero.com/file/39618607/16BCE0077-JAVA-LAB-3docx/
2. Three candidates OPS, EPS and Stalin of Tamilnadu to contest for the Chief
Minister election with the total strength of 240 MLAs. Write a Java program to
simulate the vote casting by generating 240 random numbers (1 for OPS, 2 for
EPS and 3 for Stalin) and store them in an array. Create four threads to equally
share the task of counting the number of votes cast for all the three candidates.
Use synchronized method or synchronized block to update the three count
variables. The main thread should receive the final vote count for all three
contestants and decide the Chief Minister based on the values received.

import java.util.Random;
class voting extends Thread
{
static int tot = 240;
static int ops;
static int eps;

m
er as
static int stalin;
static int arr[];

co
voting(){

eH w
ops = 0;
eps = 0;

o.
stalin = 0;
arr = new int[240];
rs e
ou urc
}
public void run(){
if(Thread.currentThread().getName()=="arr"){
o

synchronized(this){
for(int i=0; i<tot; i++)
aC s

arr[i] = randInt(1, 3);


v i y re

}
}
else if(Thread.currentThread().getName()=="ops"){
synchronized(this){
ed d

for(int i=0; i<tot; i++)


if(arr[i]==1)
ar stu

ops += 1;
}
}
else if(Thread.currentThread().getName()=="eps"){
sh is

synchronized(this){
for(int i=0; i<tot; i++)
Th

if(arr[i]==2)
eps += 1;
}
}
else if(Thread.currentThread().getName()=="stalin"){
synchronized(this){
for(int i=0; i<tot; i++)
if(arr[i]==3)
stalin += 1;
}
}
}

public static int randInt(int min, int max){

This study source was downloaded by 100000790675436 from CourseHero.com on 05-20-2021 00:04:41 GMT -05:00

https://www.coursehero.com/file/39618607/16BCE0077-JAVA-LAB-3docx/
Random rand = new Random();
int random = rand.nextInt((max - min) + 1) + min;
return random;
}

public static void main(String args[]){

voting obj = new voting();


Thread arr = new Thread(obj, "arr");
Thread a = new Thread(obj, "ops");
Thread b = new Thread(obj, "eps");
Thread c = new Thread(obj, "stalin");
arr.start();
try{
arr.join();
}
catch(Exception e){
System.out.println(e);
}
a.start();

m
b.start();

er as
c.start();

co
try{

eH w
Thread.sleep(200);
}

o.
catch(Exception e){
rs e
System.out.println(e);
ou urc
}
System.out.println(obj.ops);
System.out.println(obj.eps);
System.out.println(obj.stalin);
o

}
aC s

}
v i y re
ed d
ar stu
sh is
Th

This study source was downloaded by 100000790675436 from CourseHero.com on 05-20-2021 00:04:41 GMT -05:00

https://www.coursehero.com/file/39618607/16BCE0077-JAVA-LAB-3docx/
3. Design a class for share trading system. Create necessary supporting
variables for a share trading system also which has share_value. The
share_value is the variable used by many threads who has rights to update it
from time to time. Imagine thread owner is modifying the share_value, other
threads like, buyer1, buyer2, buyer3 has to wait till the owner notifies them.
Also when share broker thread is modifying the share_value all others including
owner has to wait till share broker notifies them. Use the multithreading
concepts, wait, notify, notifyall, sleep, synchronized.

class Main extends Thread{


int share_value=10;

void modify(int change){


if(Thread.currentThread().getName().equals("owner") ||

m
Thread.currentThread().getName().equals("broker"))

er as
{

co
eH w
if(change<0 && share_value<Math.abs(change))
{

o.
rs e System.out.println("less share than change");
try{
ou urc
wait();
}
catch(Exception e){
System.out.println(e);
o

}
aC s

notify();
}
v i y re

else
synchronized(this){
{
share_value+=change;
ed d

System.out.println("share value is:"+share_value);


ar stu

notifyAll();
}

}
sh is

}
else
Th

{
synchronized(this){
if(change<0 && share_value<Math.abs(change))
{
System.out.println("less share than change");
try{
wait();
}
catch(Exception e){
System.out.println(e);
}
notify();
}
else
{

This study source was downloaded by 100000790675436 from CourseHero.com on 05-20-2021 00:04:41 GMT -05:00

https://www.coursehero.com/file/39618607/16BCE0077-JAVA-LAB-3docx/
share_value+=change;
System.out.println("share value is:"+share_value);
notify();
}

}
}
}

public class Share {

public static void main(String[] args) {

Main m=new Main();


Thread t1=new Thread();
t1.setName("owner");
Thread t2=new Thread();

m
er as
t1.setName("broker");
Thread t3=new Thread();

co
t1.setName("b1");

eH w
Thread t4=new Thread();
t1.setName("b2");

o.
rs e
Thread t5=new Thread();
t1.setName("b3");
ou urc
new Thread(){
public void run(){
o

m.modify(10);
}
aC s

}.start();
v i y re

new Thread(){
public void run(){
m.modify(-21);
ed d

}
ar stu

}.start();

new Thread(){
public void run(){
sh is

m.modify(21);
}
Th

}.start();

This study source was downloaded by 100000790675436 from CourseHero.com on 05-20-2021 00:04:41 GMT -05:00

https://www.coursehero.com/file/39618607/16BCE0077-JAVA-LAB-3docx/
4. Design a class for cash counter processing system. Assume several variables
in class like mode of payment, amount, account number, remitter name, remitter
mobile number…..etc. Several objects are created for the account class by
cashier. When cashier opts to signout, write the state of all objects to an existing
file. When cashier performs login to the machine, read the state of all objects
from the file and display it on monitor.

import java.io.Serializable;
import java.util.Date;
public class CashCounter implements Serializable {

private float payment;


private float amount;
private String account_num;
private String remmiter_name;
private String remmiter_num;

m
er as
public CashCounter(float payment, float amount, String account_num, String

co
remmiter_name, String remmiter_num) {

eH w
super();
this.payment = payment;

o.
this.amount = amount;rs e
this.account_num account_num= account_num;
ou urc
this.remmiter_name = remmiter_name;
this.remmiter_num = remmiter_num;
}
o

@Override
aC s

public String toString() {


return new StringBuffer(" payment: ").append(this.payment).append(", Amount :
v i y re

").append(this.amount).append(", account num :").append(this.account_num).append(",


remmiter_name : ").append(this.remmiter_name).append(",remmiter_Num :
").append(this.remmiter_num).toString();
}
ed d
ar stu

@Cashier Class
import java.io.FileOutputStream;
import java.io.FileInputStream;
sh is

import java.io.ObjectOutputStream;
import java.util.ArrayList;
Th

import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.io.ObjectInputStream;\

public class Cashier {


@SuppressWarnings("deprecation")
public static void main(String args[])throws Exception{

CashCounter cash1 = new CashCounter(584.6, 87.2, "87956845", "jaya", "745868541");


CashCounter cash2 = new CashCounter(875, 874, "457845", "vijay", "8745621851");
CashCounter cash2 = new CashCounter(658, 963, "87956845", "rohith",
"8718628541");

This study source was downloaded by 100000790675436 from CourseHero.com on 05-20-2021 00:04:41 GMT -05:00

https://www.coursehero.com/file/39618607/16BCE0077-JAVA-LAB-3docx/
// Writing the object in File

ArrayList<CashCounter> woi=new ArrayList<>();


try {
FileOutputStream fop=new
FileOutputStream("C:\\Users\\Harshit\\Desktop\\List.txt");
ObjectOutputStream oos=new ObjectOutputStream(fop);
woi.add(cash1);
woi.add(cash2);
woi.add(cash3);

oos.writeObject(woi);
oos.flush();
} catch (Exception e) {
}
// Reading the file and fetching object and displaying the required

try {
FileInputStream fis=new
FileInputStream("C:\\Users\\Harshit\\Desktop\\List.txt");

m
ObjectInputStream ois=new ObjectInputStream(fis);

er as
// Donor wo=null;

co
// Donor[] woj=new Donor[5];

eH w
ArrayList<CashCounter> woi1=new ArrayList<>();
woi1=(ArrayList<CashCounter>)ois.readObject();

o.
for(int i=0;i<woi1.size();i++){
rs e
ou urc
}catch (Exception e) {
}
o
aC s
v i y re
ed d
ar stu
sh is
Th

5. Write a Java program to read book id, author and publisher details and add
books to list and printing all the books using ArrayList and Iterator.

This study source was downloaded by 100000790675436 from CourseHero.com on 05-20-2021 00:04:41 GMT -05:00

https://www.coursehero.com/file/39618607/16BCE0077-JAVA-LAB-3docx/
import java.util.ArrayList;

class Book{
public int id;
public String author;
public String pub_details;
Book(int a,String b,String c){
id=a;
author=b;
pub_details=c;
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Book> list=new ArrayList<Book>();
Book b1=new Book(15,"harshit","abc_publications");
Book b2=new Book(11,"vijay","xyz_publications");
Book b3=new Book(12,"aakash","qwz_publications");

m
er as
list.add(b1);
list.add(b2);

co
list.add(b3);

eH w
int i;
Book b;

o.
rs e
for(i=0;i<list.size();i++){
b=list.get(i);
ou urc
System.out.println("author is:"+b.author+" ,id
is:"+b.id+",publication is:"+b.pub_details);
}
o

}
}
aC s
v i y re
ed d
ar stu
sh is
Th

This study source was downloaded by 100000790675436 from CourseHero.com on 05-20-2021 00:04:41 GMT -05:00

https://www.coursehero.com/file/39618607/16BCE0077-JAVA-LAB-3docx/
Powered by TCPDF (www.tcpdf.org)

You might also like