Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Nov Dec 19

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Answer Key [Nov./Dec.

2019]
CS8392 – OBJECT ORIENTED PROGRAMMING
Third/Fifth Semester
Part : A
1. What is access specifier?
The access specifiers in Java specify the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by
applying the access modifier on it. There are four access modifiers in java; they are private,
default, public and protected
2. What is Javadoc?
Javadoc is a tool which comes with JDK and it is used for generating Java code
documentation in HTML format from Java source code, which requires documentation in a
predefined format
3. What is object cloning?
Object cloning refers to creation of exact copy of an object. It creates a new instance of the
class of current object and initializes all its fields with exactly the contents of the
corresponding fields of this object.
4. Describe the uses of interfaces in java.
There are mainly three reasons to use interface. They are
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling
5. What is exception handling?
An Exception is an unwanted event that interrupts the normal flow of the program. When an
exception occurs program execution gets terminated. The Exception Handling in Java is one of
the powerful mechanisms to handle the runtime errors so that normal flow of the application
can be maintained.
6. What is the use of assert key word?
Assert is a Java keyword used to define an assert statement. An assert statement is used to
declare an expected boolean condition in a program. If the program is running with assertions
enabled, then the condition is checked at runtime. If the condition is false, the Java runtime
system throws an AssertionError
7. Describe the various states of thread.
New
Runnable
Blocked
Waiting
Timed Waiting
Terminated
8. “Thread is a light weight process” – Comment.
We can say thread is a light weight process. A thread of execution is the smallest sequence
of programmed instructions that can be managed independently by scheduler. Threads reside
inside the process. Each thread belongs to exactly one process. No thread exists outside the
process
9. Write the code segment to handle two mouse events.
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
10. What are the purposes of JPanel?
The JPanel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the JComponents class. The main task of JPanel is to
organize components, various layouts can be set in JPanel which provide better organisation of
components, however it does not have a title bar.
Part : B
11. a. Explain the various features in java in details
The prime reason behind creation of Java was to bring portability and security feature into a
computer language. Beside these two major features, there were many other features that
played an important role in moulding out the final form of this outstanding language. Those
features are :
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to
understand.The confusing and ambiguous concepts of C++ are either left out in Java
or they have been re-implemented in a cleaner way.
Eg : Pointers and Operator Overloading are not there in java but were an important
part of C++.
2) Object Oriented
In java everything is Object which has some data and behaviour. Java can be easily
extended as it is based on Object Model.
3) Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on compile
time error checking and runtime checking. But the main areas which Java improved
were Memory Management and mishandled Exceptions by introducing automatic
Garbage Collector and Exception Handling.
4) Platform Independent
Unlike other programming languages such as C, C++ etc which are compiled into
platform specific machines. Java is guaranteed to be write-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform
independent and can be run on any machine, plus this bytecode format also provide
security. Any machine with Java Runtime Environment can run Java Programs.
5) Secure
When it comes to security, Java is always the first choice. With java secure features
it enable us to develop virus free, temper free system. Java program always runs in
Java runtime environment with almost null interaction with system OS, hence it is more
secure.
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other
resources to execute multiple threads at the same time, like While typing, grammatical
errors are checked along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer
architecture, hence a Java program is easy to intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language
like C or C++. But, Java enables high performance with the use of just-in-time
compiler.
OR
b. What is JVM? Explain the internal architecture of JVM with neat sketch.
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
It is:
1. A specification where working of Java Virtual Machine is specified. But
implementation provider is independent to choose the algorithm. Its implementation has
been provided by Oracle and other companies.
2. An implementationIts implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to
run the java class, an instance of JVM is created.
The JVM performs following operation:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
Class Loader Subsystem
It is mainly responsible for three activities.
• Loading
• Linking
• Initialization
Loading : The Class loader reads the .class file, generate the corresponding binary
data and save it in method area. For each .class file, JVM stores following information
in method area.
• Fully qualified name of the loaded class and its immediate parent class.
• Whether .class file is related to Class or Interface or Enum
• Modifier, Variables and Method information etc.
After loading .class file, JVM creates an object of type Class to represent this file in the heap
memory. Please note that this object is of type Class predefined in java.lang package. This
Class object can be used by the programmer for getting class level information like name of
class, parent name, methods and variable information etc. To get this object reference we can
use getClass() method of Object class.

Linking : Performs verification, preparation, and (optionally) resolution.


• Verification : It ensures the correctness of .class file i.e. it check whether this file
is properly formatted and generated by valid compiler or not. If verification fails, we get
run-time exception java.lang.VerifyError.
• Preparation : JVM allocates memory for class variables and initializing the memory
to default values.
• Resolution : It is the process of replacing symbolic references from the type with
direct references. It is done by searching into method area to locate the referenced
entity.
Initialization : In this phase, all static variables are assigned with their values defined
in the code and static block(if any). This is executed from top to bottom in a class
and from parent to child in class hierarchy.
In general, there are three class loaders :
• Bootstrap class loader : Every JVM implementation must have a bootstrap class
loader, capable of loading trusted classes. It loads core java API classes present in
JAVA_HOME/jre/lib directory. This path is popularly known as bootstrap path. It is
implemented in native languages like C, C++.
• Extension class loader : It is child of bootstrap class loader. It loads the classes
present in the extensions directories JAVA_HOME/jre/lib/ext(Extension path) or any other
directory specified by the java.ext.dirs system property. It is implemented in java by the
sun.misc.Launcher$ExtClassLoader class.
• System/Application class loader : It is child of extension class loader. It is
responsible to load classes from application class path. It internally uses Environment
Variable which mapped to java.class.path. It is also implemented in Java by the
sun.misc.Launcher$AppClassLoader class.

12. a. Explain in detail about various types of inheritance in java with neat diagram
Inheritance can be defined as the procedure or mechanism of acquiring all the properties and
behavior of one class to another, i.e., acquiring the properties and behavior of child class from
the parent class. This concept was built to achieve the advantage of creating a new class that
gets built upon an already existing class(es). It is mainly used for code reusability within a
Java program
Java supports three types of inheritance
1. single inheritance
2. multilevel inheritance
3. hierarchical inheritance

Single Inheritance
When a single class gets derived from its base class, then this type of inheritance is
termed as single inheritance. The figure drawn above has class A as the base class,
and class B gets derived from that base class
classA {
publicString meth() {
return"A's Method";
}
}
classB extendsA {
publicString meth() {
return"B's Method";
}
publicString meth2() {
return"B's Method2";
}
}
publicclassSingleInheritanceDemo {
publicstaticvoidmain(String[] args) {
B b = newB();
System.out.println("B : "+ b.meth());
}
}
Multi-level Inheritance
In this type of inheritance, a derived class gets created from another derived class and
can have any number of levels
classA {
publicString meth() {
return"A's Method";
}
}
classB extendsA {
publicString meth() {
return"B's Method";
}
}
classC extendsB {
publicString meth1() {
return"C's Method";
}
}
publicclassMultiLevelInheritanceDemo {
publicstaticvoidmain(String[] args) {
A a = newC();
System.out.println("A: "+ a.meth());
}
}
Hierarchical Inheritance
In this type of inheritance, there are more than one derived classes which get created
from one single base class
classA {
publicString meth() {
return"A's Method";
}
}
classB extendsA {
publicString meth() {
return"B's Method";
}
}
classC extendsA {
publicString meth2() {
return"C's Method";
}
}
publicclassHierarchicallInheritanceDemo {
publicstaticvoidmain(String[] args) {
A a = newC();
System.out.println("C's A : "+ a.meth());
B b = newB();
System.out.println("B's B : "+ b.meth());
}
}
OR
b. What is an abstract class? Illustrate with an example to demonstrate abstract class
A class that is declared using “abstract” keyword is known as abstract class. It can have
abstract methods(methods without body) as well as concrete methods (regular methods with
body). A normal class(non-abstract class) cannot have abstract methods.
An abstract class can not be instantiated, which means you are not allowed to create an
object of it
// An example abstract class in Java
abstractclassShape {
intcolor;

// An abstract function (like a pure virtual function in C++)


abstractvoiddraw();
}
an abstract class can contain constructors in Java. And a constructor of abstract class is
called when an instance of a inherited class is created
// An abstract class with constructor
abstractclassBase {
Base() { System.out.println("Base Constructor Called"); }
abstractvoidfun();
}
classDerived extendsBase {
Derived() { System.out.println("Derived Constructor Called"); }
voidfun() { System.out.println("Derived fun() called"); }
}
classMain {
publicstaticvoidmain(String args[]) {
Derived d = newDerived();
}
}
we can have an abstract class without any abstract method. This allows us to create classes
that cannot be instantiated, but can only be inherited
abstractclassBase {
voidfun() { System.out.println("Base fun() called"); }
}

classDerived extendsBase { }

classMain {
publicstaticvoidmain(String args[]) {
Derived d = newDerived();
d.fun();
}
}
Abstract classes can also have final methods (methods that cannot be overridden).
abstractclassBase {
finalvoidfun() { System.out.println("Derived fun() called"); }
}

classDerived extendsBase {}

classMain {
publicstaticvoidmain(String args[]) {
Base b = newDerived();
b.fun();
}
}

13. a. Explain different types of exceptions in java.


Exceptions are the unwanted errors or bugs or events that restrict the normal execution of a
program. Each time an exception occurs, program execution gets disrupted.
Java’s exceptions can be categorized into two types:
• Checked exceptions
• Unchecked exceptions
Generally, checked exceptions are subject to the catch or specify a requirement, which
means they require catching or declaration. This requirement is optional for unchecked
exceptions. Code that uses a checked exception will not compile if the catch or
specify rule is not followed.
Unchecked exceptions come in two types:
• Errors
• Runtime exceptions
Checked Exceptions
Checked exceptions are the type that programmers should anticipate and from which
programs should be able to recover. All Java exceptions are checked exceptions except
those of the Error and RuntimeException classes and their subclasses.
A checked exception is an exception which the Java source code must deal with,
either by catching it or declaring it to be thrown. Checked exceptions are generally
caused by faults outside of the code itself - missing resources, networking errors, and
problems with threads come to mind. These could include subclasses of
FileNotFoundException, UnknownHostException, etc.
Popular Checked Exceptions:
Name Description
IOException While using file input/output stream related exception
SQLException. While executing queries on database related to SQL syntax
DataAccessException Exception related to accessing data/database
Thrown when the JVM can’t find a class it needs, because of
ClassNotFoundException a command-line error, a classpath issue, or a missing .class
file
InstantiationException Attempt to create an object of an abstract class or interface.
Below example program of reading, file shows how checked exception should be
handled. Below image shows compile time error due to checked exception
(FileNotFoundException and IO Exception) related to file operation. IDE suggests either
we need to enclose our code inside try-catch block or we can use throws keyword in
the method declaration.
Unchecked Exceptions
Unchecked exceptions inherit from the Error class or the RuntimeException class. Many
programmers feel that you should not handle these exceptions in your programs
because they represent the type of errors from which programs cannot reasonably be
expected to recover while the program is running.
When an unchecked exception is thrown, it is usually caused by a misuse of code -
passing a null or otherwise incorrect argument.
Popular Unchecked Exceptions:
Name Description
Thrown when attempting to access an object with a reference
NullPointerException
variable whose current value is null
Thrown when attempting to access an array with an invalid
ArrayIndexOutOfBound
index value (either negative or beyond the length of the array)
IllegalArgumentException. Thrown when a method receives an argument formatted
differently than the method expects.
Thrown when the state of the environment doesn’t match the
IllegalStateException operation being attempted,e.g., using a Scanner that’s been
closed.
Thrown when a method that converts a String to a number
NumberFormatException
receives a String that it cannot convert.
ArithmaticException Arithmetic error, such as divide-by-zero.
OR
b.Explain in detail about the following with sample program
i. reading from a file
Java FileWriter and FileReader classes are used to write and read data from text files (they
are Character Stream classes). It is recommended not to use the FileInputStream and
FileOutputStream classes if you have to read and write any textual information as these are
Byte stream classes.
FileReader is useful to read data in the form of characters from a ‘text’ file.
• This class inherit from the InputStreamReader Class.
• The constructors of this class assume that the default character encoding and the
default byte-buffer size are appropriate. To specify these values yourself, construct an
InputStreamReader on a FileInputStream.
• FileReader is meant for reading streams of characters. For reading streams of raw
bytes, consider using a FileInputStream.
importjava.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReaderfr=new FileReader("D:\\testout.txt");
inti;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
ii. writing in a file
FileWriter is useful to create a file writing characters into it.
This class inherits from the OutputStream class.
The constructors of this class assume that the default character encoding and the
default byte-buffer size are acceptable. To specify these values yourself, construct an
OutputStreamWriter on a FileOutputStream.
FileWriter is meant for writing streams of characters. For writing streams of raw bytes,
consider using a FileOutputStream.
FileWriter creates the output file , if it is not present already
importjava.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriterfw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to javaTpoint.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
14. a. What is a thread? Explain multithreading and multitasking in detail.
A thread is a:
• Facility to allow multiple activities within a single process
• Referred as lightweight process
• A thread is a series of executed statements
• Each thread has its own program counter, stack and local variables
• A thread is a nested sequence of method calls
• Its shares memory, files and per-process state
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
classRunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}

public void run() {


System.out.println("Running " + threadName );
try {
for(inti = 4; i> 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start () {


System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {

public static void main(String args[]) {


RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");


R2.start();
}
}

Multitasking is when a single CPU performs several tasks (program, process, task, threads) at
the same time. To perform multitasking, the CPU switches among theses tasks very frequently
so that user can interact with each program simultaneously.
The basic difference between multitasking and multithreading is that in multitasking, the system
allows executing multiple programs and tasks at the same time. In multitasking CPU has to
switch between multiple programs so that it appears that multiple programs are running
simultaneously. Multitasking allocates separate memory and resources for each process/program
whereas, in multithreading threads belonging to the same process shares the same memory
and resources as that of the process.
OR
b. What is synchronization? Explain the different types of synchronization in java
At times when more than one thread try to access a shared resource, we need to ensure
that resource will be used by only one thread at a time. The process by which this is
achieved is called synchronization. Synchronized keyword in java create a critical section in
which a lock is associated with the object . To enter the critical section a thread need to
obtain the object lock. The general form of synchronized is as follows
synchronized(object){
statement;
}
There are basically two types of synchronization available. They are:
1. Process Synchronization: The simultaneous execution of multiple threads or
processes to reach a state such that they commit to a certain sequence of actions.
2. Thread Synchronization: At times when more than one thread tries to access a
shared resource, you need to ensure that resource will be used by only one thread
at a time.
In JAVA we have two types of synchronization techniques. They are synchronized methods and
synchronized blocks.
1. Synchronized methods:
If any method is sharable for 'n' number of threads then make the method as synchronized by using a
keyword synchronized.
In JAVA we have two types of synchronized methods. They are synchronized Instance methods and
synchronized static methods.
Synchronized Instance methods: If the ordinary instance method is made it as synchronized then the
object of the corresponding class will be locked.
class Account {

intbal = 0;

synchronized void deposit(intamt) {


bal = bal + amt;
System.out.println("CURRENT BALANCE =" + bal);
}
};
2. Synchronized block:
This is an alternative technique for obtaining the concept of synchronization instead of synchronized
methods.
When we inherit non-synchronized methods from either base class or interface into the derived class, we
cannot make the inherited method as synchronized. Hence, we must use synchronized blocks.
abstract class BankOp {

abstract void deposit(intamt);// p a instance


};

class Account extends BankOp {


intbal = 0;

public void deposit(intamt) {


synchronized (this)
{
bal = bal + amt;
System.out.println("current value=" + bal);
}
}
}

15. a. Describe in detail about the different layouts in java GUI. Which layout is the default
one?
Layouts tell Java where to put components in containers (JPanel, content pane, etc).
Every panel (and other container) has a default layout, but it's better to set the layout
explicitly for clarity. Create a new layout object (using one of its constructors) and use
the container's setLayout method to set the layout.
Flow Layout - left to right, top to bottom. Good for initial testing. FlowLayout does not
respect preferred size information, so it may make variable size elements (eg, a
graphics panel) extremely small.
Border Layout - north, east, south, west, and center areas. Has various rules for how
components are stretched to fit these areas. Both common and useful.
Grid Layout - equal sized grid elements.
Box Layout and Boxes - horizontal or vertical sequence of components.
Grid Bag Layout - unequal sized grid. Can produce excellent results, but can be
difficult to use.
SpringLayout was added in Java 1.4, but is difficult for humans. It is rumored to be
intended for authomatic layout programs..
CardLayout is good for something like a wizard interface which shows one of several
possible layouts (think about a stack of index cards). Tabbed panes are something like
a card layout with tabs.
OR
b. Discuss mouse listener and mouse motion listener. Give an example program
MouseListener and MouseMotionListener is an interface in java.awt.event package. MouseListener
handles the events when the mouse is not in motion. While MouseMotionListenerhandles the
events when mouse is in motion

There are five types of events that MouseListener can generate. There are five
abstract functions that represent these five events. The abstract functions are :
1. void mouseReleased(MouseEvent e) : Mouse key is released
2. void mouseClicked(MouseEvent e) : Mouse key is pressed/released
3. void mouseExited(MouseEvent e) : Mouse exited the component
4. void mouseEntered(MouseEvent e) : Mouse entered the component
5. void mousepressed(MouseEvent e) : Mouse key is pressed
There are two types of events that MouseMotionListener can generate. There are two
abstract functions that represent these five events. The abstract functions are :
1. voidmouseDragged(MouseEvent e) : Invoked when a mouse button is pressed in
the component and dragged. Events are passed until the user releases the mouse
button.
2. voidmouseMoved(MouseEvent e) : invoked when the mouse cursor is moved from
one point to another within the component, without pressing any mouse buttons.
importjava.awt.*;
importjava.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);

l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
newMouseListenerExample();
}
}

importjava.awt.*;
importjava.awt.event.*;
public class MouseMotionListenerExample extends Frame implements MouseMotionListener{
MouseMotionListenerExample(){
addMouseMotionListener(this);

setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {}

public static void main(String[] args) {


newMouseMotionListenerExample();
}
}
Part : C
16. a. Develop a java program to find a smallest in the given array by creating one
dimensional array and two dimensional array using new operator.
importjava.util.*;
classOneArray{
public static void main(String[] args){
int[] array=new int[10];
Scanner scan=new Scanner(System.in);
int size=scan.nextInt();
for(inti=0;i<size;i++){
array[i]=scan.nextInt();
}
System.out.println("Array Elements are");
for(inti=0;i<size;i++){
System.out.println(array[i]);
}
int small=array[0];
for(inti=1;i<size;i++){
if(array[i]<small){
small=array[i];
}
}
System.out.println("smallest is:"+small);
}
}

importjava.util.*;
classTwoArray{
public static void main(String[] args){
int[][] array=new int[5][5];
Scanner scan=new Scanner(System.in);
int size=scan.nextInt();
for(inti=0;i<size;i++){
for(int j=0;j<size;j++){
array[i][j]=scan.nextInt();
}
}
System.out.println("Array Elements are");
for(inti=0;i<size;i++){
for(int j=0;j<size;j++){
System.out.println(array[i][j]+" ");
}
System.out.println();
}
int small=array[0][0];
for(inti=0;i<size;i++){
for(int j=0;j<size;j++){
if(array[i][j]<small){
small=array[i][j];
}
}
}
System.out.println("smallest is:"+small);
}
}
OR
b. Create a simple real life application program in java to illustrate the use of multithreads.

importjava.util.ArrayList;

public class Bank {


privateArrayList<Account> accounts;

public Bank(intaccountsCount) {
accounts = new ArrayList<Account>();
for (inti = 0; i<accountsCount; i++) {
accounts.add(new Account(i));
}
}

public Account getRandomAccount() {


returnaccounts.get((int) (Math.random() * accounts.size()));
}

public void printSummary() {


for (Account a : accounts)
System.out.println(a.toString());
}
}
public class Account {
privateint balance = 1000;
privateint number;

public Account(int number) {


this.number = number;
}

public synchronized intgetBalance() {


return balance;
}

public synchronized void withdraw(Client client, intbal) {


try {

if (balance >= bal) {


System.out.println(client.getName() + " "+ "is trying to withdraw from account " + number);
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
balance = balance - bal;
System.out.println(client.getName() + " "
+ "has completed withdrawal from account " + number);
} else {
System.out.println(client.getName()+ " "+ "doesn't have enough money for withdraw from
account "+ number);
}
System.out.println(client.getName() + " withdrawal value: "
+ balance + " from account " + number);
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void deposit(Client client, intbal) {
try {
if (bal> 0) {
System.out.println(client.getName() + " "
+ "trying to deposit on account " + number);
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
balance = balance + bal;
System.out.println(client.getName() + " "
+ "has completed the deposit on account " + number);
} else {
System.out.println(client.getName() + " "
+ " doesn't have enough money for deposit on account "
+ number);
}
System.out.println(client.getName() + " deposited " + balance
+ " on account " + number);
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public String toString() {
return "Account " + number + " balance: " + balance;
}
}

public class Client {


private String name;
public Client(String name) {
this.name = name;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

@Override
public String toString() {
return name;
}
}

importjava.util.Random;
importjava.util.logging.Level;
importjava.util.logging.Logger;

public class Main extends Thread implements Runnable {

private static final int CLIENT_COUNT = 5;


private static final int CLIENT_ITERATIONS = 5;
private static final int ACCOUNTS_COUNT = 2;

private static final int RAND_MIN = 10;


private static final int RAND_MAX = 10;
private static final int RAND_MIN_AMOUNT = 10;
private static final int RAND_MAX_AMOUNT = 200;

private static Bank bank = new Bank(ACCOUNTS_COUNT);


private Client client;
public Main(Client c) {
client = c;
}

privateintrandAmount() {
return (new Random()).nextInt((RAND_MAX_AMOUNT - RAND_MIN_AMOUNT) + 1)
+ RAND_MIN_AMOUNT;
}

privateintrandSleepTime() {
return (new Random()).nextInt((RAND_MAX - RAND_MIN) + 1) + RAND_MIN;
}

public static void main(String[] args) {


for (inti = 0; i< CLIENT_COUNT; i++) {
Main ts1 = new Main(new Client("Person " + i));
ts1.start();
}
}

private void clientWork() {


try {
Thread.sleep(randSleepTime());
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}

@Override
public void run() {
for (inti = 0; i< CLIENT_ITERATIONS; i++) {
Account acc = bank.getRandomAccount();
clientWork();
acc.withdraw(client, randAmount());
clientWork();
acc.deposit(client, randAmount());
}
System.out.println("#Account balance: " + Account.getBalance());
}
}

You might also like