0% found this document useful (0 votes)
152 views9 pages

ATM Withdrawal Java Implementation

The document contains 4 code examples demonstrating different concepts in Java: 1) An ATM class with methods to withdraw money while handling exceptions for insufficient balances. 2) An interface and class to book and display movie tickets, demonstrating polymorphism. 3) A producer-consumer problem solved using wait/notify to synchronize putting and getting values in a shared queue. 4) A synchronized method example ensuring threads call a target method sequentially by waiting on the target object.

Uploaded by

Rahul Venkatesan
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)
152 views9 pages

ATM Withdrawal Java Implementation

The document contains 4 code examples demonstrating different concepts in Java: 1) An ATM class with methods to withdraw money while handling exceptions for insufficient balances. 2) An interface and class to book and display movie tickets, demonstrating polymorphism. 3) A producer-consumer problem solved using wait/notify to synchronize putting and getting values in a shared queue. 4) A synchronized method example ensuring threads call a target method sequentially by waiting on the target object.

Uploaded by

Rahul Venkatesan
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

1)

import [Link];
class InsufficientBalanceException extends Exception
{
public InsufficientBalanceException(String message)
{
super(message);
}
}
class Atm
{
private double balance;
private static final double Min=500;
private String holdername;
private String branchname;
public Atm(double initialbalance,String
holdername,String branchname)
{
[Link]=initialbalance;
[Link]=holdername;
[Link]=branchname;
}
public void withdraw(double amount) throws
InsufficientBalanceException
{
if(amount>balance)
{ throw new
InsufficientBalanceException("Insuficient balance");}
if(balance-amount<Min)
{
throw new
InsufficientBalanceException("Withdrawal will result ini
balance below minimum required");
}
balance-=amount;
[Link]("Withdrawal Successful!
Remaining balance: "+balance);
}
}
public class AtmFunc
{
public static void main(String[] args)
{
Scanner scanner=new Scanner([Link]);
[Link]("Enter Holder name: ");
String holdername=[Link]();
[Link]("Enter Initial Balance: ");
double initialbalance=[Link]();
[Link]("Enter Branch name: ");
String branchname=[Link]();
Atm atm=new
Atm(initialbalance,holdername,branchname);
try
{
[Link]("Enter Withdrawal Amount :");
double withdrawalAmount=[Link]();
[Link](withdrawalAmount);
}
catch(InsufficientBalanceException e)
{
[Link]("Error: "+[Link]());
}
finally
{
[Link]();
}
}

2)
import [Link];
interface Ticket
{
void book();
void display();
}
class Movie implements Ticket
{
private String name;
private int price;
private int numTickets;
public Movie(String name,int price)
{
[Link]=name;
[Link]=price;
[Link]=0;
}
public void book()
{
Scanner Scanner=new Scanner([Link]);
[Link]("Enter the number of Tickets to
book: ");
int Tickets=[Link]();
if(Tickets>0)
{
numTickets+=Tickets;
[Link](Tickets+" Tickets for"+ name+"
Movie have been booked");
}
else
{
[Link]("Invalid Number of Tickets");
}
}
public void display()
{
[Link]("Movie: "+name);
[Link]("Price: "+price);
[Link]("Total Amount:
"+(price*numTickets));
}
}
public class booking
{
public static void main(String[] args)
{
Movie movieticket=new Movie("Leo",150);
[Link]();
[Link]();
}
}

3)
class Q
{
int num;
boolean valueset=false;
public synchronized void put(int num)
{
while(valueset)
{
try{wait();} catch(Exception e){};
}
[Link]("Put: "+num);
[Link]=num;
valueset=true;
notify();

}
public synchronized void get()
{
while(!valueset)
{
try{wait();} catch(Exception e){};
}
[Link]("Get: "+num);
valueset=false;
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
Thread t=new Thread(this,"Producer");
[Link]();

}
public void run()
{
int i=0;
while(true)
{
[Link](i++);

try{[Link](1000);} catch(Exception
e){};

}
}
}

class Consumer implements Runnable


{
Q q;
Consumer(Q q)
{
this.q=q;
Thread t=new Thread(this,"Consumer");
[Link]();
}
public void run()
{
while(true)
{
[Link]();
try{[Link](2000);} catch(Exception
e){};
}
}
}

public class InterThread


{
public static void main(String[] args)
{
Q q=new Q();
new Producer(q);
new Consumer(q);
}
}

4)
class Callme
{
void call(String msg)
{
[Link]("["+msg);
try{[Link](1000);}
catch(InterruptedException
e){[Link]("Interepted");}
[Link]("]");

}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme target,String msg)
{
[Link]=target;
[Link]=msg;
t=new Thread(this);
[Link]();
}
public void run()
{
synchronized(target)
{
[Link](msg);
}
}

}
public class Synch
{
public static void main(String args[])
{
Callme target=new Callme();
Caller obj1=new Caller(target,"Hello");
Caller obj2=new Caller(target,"Syn");
Caller obj3=new Caller(target,"Rahul");
try{
[Link]();

[Link]();
[Link]();
}
catch(InterruptedException e)
{
[Link]("Interrupted");
}

}
}

Common questions

Powered by AI

The ATM system uses user input to manage banking transactions with exception handling for insufficient funds. It involves capturing the holder's name, initial balance, and branch details to operate, focusing on individual validation and feedback. The ticket booking system, however, is more straightforward, allowing for a single type of transaction (booking tickets) and uses less input validation, focusing more on collective ticket sales without personalization. Both systems reflect context-specific user interactions but vary in complexity and error management, affecting their respective user experiences .

In producer-consumer scenarios, 'notify()' and 'wait()' methods are critical for thread communication and synchronization. 'wait()' allows a thread to pause execution until another thread invokes 'notify()' on the same object monitor, preventing the wasteful busy-waiting. 'notify()' signals waiting threads that a condition or state has changed, allowing them to resume execution when the operation is feasible, thereby managing the access to shared resources efficiently and without conflicts .

The 'Callme' class uses synchronized blocks to safeguard the 'call()' method, ensuring that only one thread can execute it at a time. This approach prevents race conditions by securing the shared resource against concurrent access. The impact is positive on thread safety as it eliminates potential conflicts and inconsistencies when multiple threads attempt to invoke 'call()' simultaneously, thus preserving the integrity of output sequences in a multithreaded environment .

If a user attempts to withdraw more than the available balance, the ATM program will trigger an 'InsufficientBalanceException', indicating an insufficient balance. This exception handling mechanism will print an error message and prevent the withdrawal, ensuring that the account balance does not drop below the minimum requirement, thus maintaining data integrity and providing immediate feedback to the user about the failed transaction attempt .

Not closing the Scanner can lead to resource leaks, as it holds on to the input stream, potentially affecting performance or leading to garbage collection issues. In the ATM example, the 'finally' block ensures the Scanner resource is closed, mitigating these issues by explicitly releasing the resource at the end of its usage, which properly manages system resources and avoids the aforementioned problems .

The 'InsufficientBalanceException' custom exception in the ATM system specifies errors unique to banking operations, such as attempting withdrawals leading to a balance below the minimum or exceeding available balance. Using this specific custom exception allows developers to handle these conditions explicitly, providing clearer diagnostics and user feedback. It enhances error handling by categorizing specific failures, which enables more targeted catch blocks and maintains cleaner code architecture .

The use of an interface in the movie ticket booking system abstracts and standardizes the booking and display operations. By implementing the 'Ticket' interface, the 'Movie' class commits to defining 'book()' and 'display()' methods, which ensure that any class implementing 'Ticket' will consistently provide these functionalities. This enhances modularity and potential scalability of the system, allowing for different ticketing operations to be easily integrated or modified .

Synchronization ensures that only one thread accesses a critical section of the code at a time. In the inter-thread communication example, synchronized methods 'put' and 'get' in the class 'Q' prevent multiple threads from concurrently modifying the shared resource 'num', thus avoiding inconsistent states. By using 'wait()' and 'notify()' properly, they manage the signaling between threads to handle producer-consumer logic effectively .

The producer-consumer implementation using threads effectively manages synchronization and communication with 'wait()' and 'notify()', which can handle real-time applications by balancing production and consumption rates. This ensures that the system efficiently uses CPU resources and maintains responsiveness. However, thread context switching and possible delays from locking mechanisms may impact latency. Despite these challenges, the setup can handle high-load scenarios robustly if designed correctly, demanding careful tuning of buffer sizes and wait durations for optimal performance .

Exception handling in the ATM withdrawal process prevents the program from crashing by catching situations where an 'InsufficientBalanceException' might be thrown. This exception is triggered when a withdrawal would result in a balance less than the minimum required or when the amount exceeds the available balance, thereby informing the user of specific errors while maintaining the program flow without abrupt termination .

You might also like