You are on page 1of 15

JAVA

Section 1
1. What might cause the current thread to stop executing.
A. An InterruptedException is thrown.
B. The thread executes a wait() call.
C. The thread constructs a new Thread.
D. A thread of higher priority becomes ready.
2. Which modifier should be applied to a method for the lock of the object this to be obtained prior to executing any of
the method body?
A. final
B. static
C. abstract
D. protected
E. synchronized
3.Which of the following are Java keywords?
a.
b.
c.
d.

NULL
new
instanceOf
wend

4.Which of the following statements are true?


1) An interface can only contain method and not variables
2) Interfaces cannot have constructors
3) A class may extend only one other class and implement only one interface
4) Interfaces are the Java approach to addressing its lack of multiple inheritance, but require implementing
classes to create the functionality of the Interfaces.
5.Which of the following are methods of the Runnable interface
1) run
2) start
3) yield
4) stop
6.Which of the following are valid methods?
1)
2)
3)
4)

public static native void amethod(){}


public static void amethod(){}
private protected void amethod(){}
static native void amethod();

7.Which of the following statements are true?


1)
2)
3)
4)

Constructors cannot have a visibility modifier


Constructors can be marked public and protected, but not private
Constructors can only have a primitive return type
Constructors are not inherited

8.Which of the following statements are true?


1) static methods do not have access to the implicit variable called this
2) A static method may be called without creating an instance of its class
3) A static method may not be overriden to be non-static
4) A static method may not be overloaded
9.Which of the following are true?
1) A component may have only one event listener attached at a time
2) An event listener may be removed from a component
3) The ActionListener interface has no corresponding Adapter
10.Which of the following statements are true?
1) The default constructor has a return type of void

JAVA
2) The default constructor takes a parameter of void
3) The default constructor takes no parameters
4) The default constructor is not created if the class has any constructors of its own.
11.How do you change the current layout manager for a container
1) Use the setLayout method
2) Once created you cannot change the current layout manager of a component
3) Use the setLayoutManager method
4) Use the updateLayout method
12.For a class defined inside a method, what rule governs access to the variables of the enclosing method?
1) The class can access any variable
2) The class can only access static variables
3) The class can only access transient variables
4) The class can only access final variables
13.Which of the following will compile without error?
1) File f = new File("/","autoexec.bat");
2) DataInputStream d = new DataInputStream(System.in);
3) OutputStreamWriter o = new OutputStreamWriter(System.out);
14.

Which of the following are methods of the Thread class?


1) yield()
2) sleep(long msec)
3) go()
4) stop()

15.Which of the following most closely describes the process of overriding?


1) A class with the same name replaces the functionality of a class defined earlier in the hierarchy
2) A method with the same name completely replaces the functionality of a method earlier in the hierarchy
3) A method with the same name but different parameters gives multiple uses for the same method name
4) A class is prevented from accessing methods in its immediate ancestor
16 Which of the following statements are true about a variable created with the static modifier?
1) Once assigned the value of a static variable may not be altered
2) A static variable created in a method will keep the same value between calls
3) Only one instance of a static variable will exist for any amount of class instances
4) The static modifier can only be applied to a primitive value
17 Which of the following statements are true?
1) A method cannot be overloaded to be less public in a child class
2) To be overridden a method only needs the same name and parameter types
3) To be overridden a method must have the same name, parameter and return types
18. Which of the following best describes the use of the synchronized keyword?
1) Allows two process to run in paralell but to communicate with each other
2) Ensures only one thread at a time may access a method or object
3) Ensures that two or more processes will start and end at the same time
4) Ensures that two or more Threads will start and end at the same time
19. Which is the correct way to start a new thread? Select the one correct answer.
a. Just create a new Thread object. The thread will start automatically.
b. Create a new Thread object and call the method begin().
c. Create a new Thread object and call the method start().

JAVA
d. Create a new Thread object and call the method run().
e. Create a new Thread object and call the method resume().
20. Which statements are true? Select the two correct answers.
a. The class Thread is abstract.
b. The class Thread implements Runnable.
c. Classes implementing the Runnable interface must define a method named start.
d. Calling the method run() on an object implementing Runnable will create a new thread.
e. A program terminates when the last non-daemon thread ends.
21. What will be printed when the following program is run?
public class ParameterPass {
public static void main(String[] args) {
int i = 0;
addTwo(i++);
System.out.println(i);
}
static void addTwo(int i) {
i += 2;
}
}
Select the one correct answer.
a. 0
b. 1
c. 2
d. 3
22. Given the following code, which statements are true?
public interface HeavenlyBody { String describe(); }
class Star {
String starName;
public String describe() { return "star " + starName; }
}
class Planet extends Star {
String name;
public String describe() {
return "planet " + name + " orbiting star " + starName;
}
}
Select the two correct answers:
a. The code will fail to compile.
b. The use of inheritance is justified, since Planet is-a Star.
c. The code will fail to compile if the name starName is replaced with the name bodyName throughout the
declaration of the Star class.
d. The code will fail to compile if the name starName is replaced with the name name throughout the declaration
of the Star class.
e. An instance of Planet is a valid instance of HeavenlyBody.
23. Given the following code, which statement is true?
public interface HeavenlyBody { String describe(); }
class Star implements HeavenlyBody {
String starName;
public String describe() { return "star " + starName; }
}
class Planet {
String name;
Star orbiting;
public String describe() {
return "planet " + name + " orbiting " + orbiting.describe();
}
}
Select the one correct answer:
a. The code will fail to compile.
b. The use of aggregation is justified, since Planet has-a Star.
c. The code will fail to compile if the name starName is replaced with the name bodyName throughout the
declaration of the Star class.

JAVA
d.

The code will fail to compile if the name starName is replaced with the name name throughout the declaration
of the Star class.
e. An instance of Planet is a valid instance of a HeavenlyBody.
24. What will be the result of attempting to compile and run the following program?
public class MyClass {
public static void main(String[] args) {
String s = "hello";
StringBuffer sb = new StringBuffer(s);
sb.reverse();
if (s == sb) System.out.println("a");
if (s.equals(sb)) System.out.println("b");
if (sb.equals(s)) System.out.println("c");
}
}
Select the one correct answer.
a. The code will fail to compile since the constructor of the String class is not called properly.
b. The code will fail to compile since the expression (s == sb) is illegal.
c. The code will fail to compile since the expression (s.equals(sb)) is illegal.
d. The program will print c when run.
e. The program will throw a ClassCastException when run.
25. What will be the result of attempting to compile and run the following code?
public class StringMethods {
public static void main(String[] args) {
String str = new String("eenny");
str.concat(" meeny");
StringBuffer strBuf = new StringBuffer(" miny");
strBuf.append(" mo");
System.out.println(str + strBuf);
}
}
Select the one correct answer.
a. The code will fail to compile.
b. The program will print eenny meeny miny mo when run.
c. The program will print meeny miny mo when run.
d. The program will print eenny miny mo when run.
26. Which of the following do not denote a primitive data value in Java?
Select the two correct answers.
a. "t"
b. 'k'
c. 50.5F
d. "hello"
e. false
27. Which integral type in Java has the exact range from -2147483648 (-231) to 2147483647 (231 -1), inclusive?
Select the one correct answer.
a. Type byte
b. Type short
c. Type int
d. Type long
e. Type char
28. Which of the following are reserved keywords?
Select the three correct answers.
a. public
b. static
c. void
d. main
e. String
f. args
29.
Which digits, and in which order, will be printed when the following program is run?
public class MyClass {
public static void main(String[] args) {
int k=0;

JAVA
try {
int i = 5/k;
} catch (ArithmeticException e) {
System.out.println("1");
} catch (RuntimeException e) {
System.out.println("2");
return;
} catch (Exception e) {
System.out.println("3");
} finally {
System.out.println("4");
}
System.out.println("5");
}
}
Select the one correct answer.
a. The program will only print 5.
b. The program will only print 1 and 4, in that order.
c. The program will only print 1, 2, and 4, in that order.
d. The program will only print 1, 4, and 5, in that order.
e. The program will only print 1, 2, 4, and 5, in that order.
f. The program will only print 3 and 5, in that order.
30. Given the following program, which statements are true?
public class Exceptions {
public static void main(String[] args) {
try {
if (args.length == 0) return;
System.out.println(args[0]);
} finally {
System.out.println("The end");
}
}
}
Select the two correct answers.
a. If run with no arguments, the program will produce no output.
b. If run with no arguments, the program will print "The end".
c. The program will throw an ArrayIndexOutOfBoundsException.
d. If run with one argument, the program will simply print the given argument.
e. If run with one argument, the program will print the given argument followed by "The end".

Section 2
1) Scenario: XYZ limited has a branch office in Pune and they have their Head Office in Mumbai. The database is
located only in the Head office and using RMI logic we should develop an application, which will retrieve data from the
database on the client side.
The application should have
a)
Text Field to write the SQL Query
b)
Text Area to show the results
c)
OK button
2) Scenario: ABC Limited having its head office in Mumbai has 3 branches in Indore, Patna and Delhi, where it will take
inquiries for its Computers.
These inquiries will be captured in an Application having the following fields:
a)
Party Name
b)
Party Address
c)
Client Office field which will have 3 branch office names
d)
Computer Specification field
e)
Ok Button
f)
Reset Button
The officers in Client Office will click on the OK Button and a text file will get generated and this file will be send to the
Head Office.
The Head Office will have a GUI where the file name will be captured and all the 4 information will be entered in a
Database, which is only present on the Server Side.

JAVA
3) Write a code to simulate a Console Chatting program which will send and receive data.

Section 3
1] Which statement about the garbage collection mechanism are true?
A. Garbage collection require additional programe code in cases where multiple threads are running.
B. The programmer can indicate that a reference through a local variable is no longer of interest.
C. The programmer has a mechanism that explicity and immediately frees the memory used by Java objects.
D. The garbage collection mechanism can free the memory used by Java Object at explection time.
E. The garbage collection system never reclaims memory from objects while are still accessible to running user threads.
2]. Which statement about listener is true?
A. Most component allow multiple listeners to be added.
B. If multiple listener be add to a single component, the event only affected one listener.
C. Component don't allow multiple listeners to be add.
D. The listener mechanism allows you to call an addListener method as many times as is needed, specifying as many
different listeners as your design require.
3] Give the code fragment:
1) switch(x){
2)
case 1:System.out.println("Test 1");break;
3)
case 2:
4)
case 3:System.out.println("Test 2");break;
5)
default:System.out.println("end");
6)
}
which value of x would cause "Test 2" to the output:
A. 1
B. 2
C. 3
D. default
4] Which method you define as the starting point of new thread in a class from which new the thread can be excution?
A. public void start()
B. public void run()
C. public void int()
D. public static void main(String args[])
E. public void runnable()
5] What wight cause the current thread to stop excutings?
A. thread of higher priority become ready. B. method sleep() be called.
C. method stop() be called
D. method suspend() be called.
E. method wait() be called
6] Which modifier should be applied to a method for the lock of object this to be obtained prior to excution any of the
method body?
A. synchronized B. abstract
C. final
D. static
E. public
7] The following code is entire contents of a file called Example.java, causes precisely one error during compilation:
1) class SubClass extends BaseClass{
2)
}
3) class BaseClass(){
4)
String str;
5)
public BaseClass(){
6)
System.out.println("ok");}
7)
public BaseClass(String s){
8)
str=s;}}
9)
public class Example{
10)
public void method(){
11)
SubClass s=new SubClass("hello");
12)
BaseClass b=new BaseClass("world");
13)
}
14)
}
Which line would be cause the error?
A. 9
B. 10
C. 11
D.12
8] The piece of preliminary analysis work describes a class that will be used frequently in many unrelated parts of a
project

JAVA
"The polygon object is a drawable, A polygon has vertex information stored in a vector, a color, length and width."
Which Data type would be used?
A. Vector
B. int
C. String
D. Color
E. Date
9] A class design requires that a member variable should be accessible only by same package, which modifer word
should be used?
A. protected
B. public
C. no modifer
D. private
10] Which modifer should be applied to a declaration of a class member variable for the value of variable to remain
constant after the creation of the object?
Ans: _________________________________________________________________________
11] Which is corrected argument of main() method of application?
A. String args
B. String ar[]
C. Char args[][] D. StringBuffer arg[]
12]

Float s=new Float(0.9F);


Float t=new Float(0.9F);
Double u=new Double(0.9);
Which expression's result is true?
A. s==t
B. s.equal(t)

C. s==u

D. t.equal(u)

13] A socket object has been created and connected to a standard internet service on a remote network server. Which
construction give the most suitable means for reading ASCII data online at a time from the socket?
A. InputStream in=s.getInputStream();
B. DataInputStream in=new DataInputstream(s.getInputStream());
C. ByteArrayInputStream in=new ByteArrayInputStream(s.getInputStream());
D. BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
14] What use to position a Button in a Frame only, width of Button is affected by the Frame size, which Layout Button
well be set ?
A. FlowLayout;
B. GridLayout;
C. North of BorderLayout
D. South of BorderLayout
E. East or West of BorderLayout
15] An AWT GUI under exposure condition, which one or more method well be invoke when it redraw?
A. paint();
B. update();
C. repaint();
D. drawing();
16] Which is the range of char?
A. 2 7~2 7-1
B. 0~2 16-1

C. 0~2 16

D. 0~2 8

17] Which code fragments would correctly identify the number of arguments passed via command line to a Java
application, exclude the name of the class that is being invoke.
A. int count = args.length;
B. int count = args.length-1;
C. int count=0; while(args[count]!=null)
count++;
D. int count=0;while(!(args[count].equals("")))
count++;
18] A class design requires that a particular member variable must be accessible for direct access by any subclasses of
this class. but otherwise not by classes which are not members of the same package. What should be done to achieve
this?
A. The variable should be marked public
B. The variable should be marked private
C. The variable should be marked protected
D. The variable should have no special access modifier
E. The variable should be marked private and an accessor method provided
19] Which is the return value of Event listener's method?
A. String
B. AWTEvent
C. void

D. int

20] A byte can be of what size


1) -128 to 127
2) (-2 power 8 )-1 to 2 power 8
3) -255 to 256

JAVA
4) depends on the Java Virtual machine
21] What will happen when you compile the following code
public class MyClass{
static int i;
public static void main(String argv[]){
System.out.println(i);
}
}
1) Error Variable i may not have been initialized
2) null
3) 1
4) 0
22] What tags are mandatory when creating HTML to display an applet
1) name, height, width
2) code, name
3) codebase, height, width
4) code, height, width
23] What will be displayed when you attempt to compile and run the following code
//Code start
import java.awt.*;
public class Butt extends Frame{
public static void main(String argv[]){
Butt MyBut= new Butt();
}
Butt(){
Button HelloBut = new Button("Hello");
Button ByeBut = new Button("Bye");
add(HelloBut);
add(ByeBut);
setSize(300,300);
setVisible(true);
}
}
//Code end
1) Two buttons side by side occupying all of the frame, Hello on the left and Bye on the right
2) One button occupying the entire frame saying Hello
3) One button occupying the entire frame saying Bye
4) Two buttons at the top of the frame one saying Hello the other saying Bye
24] Which of the following would be an illegal identifier for a Java method?
a) do_it_now
b) _Substitute
c) 9thMethod
d) $addMoney
e) %getPath
25] Which of the following statements is correct for a method which is overriding the following method:
public void add(int a) {...}
the overriding method must return void
the overriding method must return int
the overriding method can return whatever it likes
Enterprise Java
26] What will be the output of the following JSP code?
<html><body>
<% int a = 10; %>
<%! int a = 20; %>
<%! int b = 30; %>
The value of b multiplied by a is <%= b * a %>
</body> </html>

JAVA
A) The code will not compile
B) The value of b multiplied by a is 30
C) The value of b multiplied by a is 300
D) The value of b multiplied by a is 600
E) The value of b multiplied by a is 0
27] Which method should not be overridden in HttpServlet, if the request is coming from a browser?
28] Which of the following staments are correct about the following jsp lines:
<jps:useBean id=name class=java.lang.String />
<%= name %>
1) It won't compile.
2) It is a valid jsp line and it will print the variable called name.
3) It will compile but it will always produce null as the output.
4) It will work if you create a javabean class with only one variable of type java.lang.String.
29] What will be the result of running the following jsp file taking into account that the Web server has just been started
and this is the first page loaded by the server?
<html><body>
<%= request.getSession(false).getId() %>
</body></html>
1)It won't compile
2)It will print the session id.
3)It will produce a NullPointerException as the getSession(false) method's call returns null, cause no session
had been created.
4)It will produce an empty page.
30] Which are mandatory elements of the web-resouce-collection element?
1) web-resource-name
2) url-pattern
3) http-method
4) auth-constraint
31] Which of the following statements regarding HttpRequest methods are correct?
1) getParameterNames returns an Enumeration
2) getParameter returns a String[]
3) getParameterValues returns a String[]
4) getIntParameter returns an int
32] Which of the following jsp action allow to specify the value of the attribute as an expresion(so it is evaluated at
runtime)?
1) Attribute value of <jsp:setProperty name=name value=<%= expression %>
2) Attribute page of <jsp:include page=<%= expresion %>
3) Attribute value of <jsp:paran name=name value=<%= expression %>
4) Attribute name of <jsp:getProperty name=<% expression %>
33] What will be the result of the following jsp action?
<jsp:setProperty name=myBean property=factor parameter=inputFactor />
1) The program won't compile
2) The servlet container will call myBean.setFactor() method with the content of the parameter inputFactor
3) The servlet container will call myBean.setInputFactor method with the content of the factor input
4) It will only work if the form parameter inputFactor is not empty when the form is submitted.
34] Which statements are correct about the way a servlet can acces its initialization parameters?
1) By simply calling getInitParameter from any of the servlets methods (for example doGet)
2) It must be done by calling getServletConfig().getInitParaemter
3) It can only be done by overriding the method init(ServletConfig config)
4) It can be done by calling getServletContext().getInitParameter method
Ans: 1)By simply calling getInitParameter from any of the servlets methods (for example doGet)

JAVA
35] Which type of Bean represents data in a database?
36] Do we require Home and Remote interface in every type of EJB? (Specify Yes or No)..
37] A Session and Entity bean should have __________________ method in the bean class for every create method in
the Home Interface.
38) Which jsp lines are correct?
1) <%! String myString=Hello %>
2) <% String myString=request.getServerName() %>
3) <%= out.print(Hello) %>
4) <%= Hello %>
39) Which are mandatory sub-elements of the web-app elements?
1) servlet element
2) login-config element
3) display-name element
4) There are no mandatory elements.
40) What will be the result of this jsp line if the user takes a look at the page source code?
<!-- Today is <%= new java.util.Date() %>.Hava a nice day -->
1) It won't compile
2) The user won't see the comment
3) The user will see the same jsp line as above
4) The user will see the comment with the current date because the expression is evaluated at runtime.
41] Which of the following are attributes of the page directive?
1) infoDetails
2) ERRORPAGE
3) isErrorPage
4) import
42) Which is the mandatory attribute name and value for the <jsp:include> action____________________
43] JTA stands for ___________________________
44] What are the 2 types of Session Beans ___________________________________________
45] Mention any 2 methods which are new in Entity Bean and not found in Session Bean
________________________________________________________________________________________
46] Which is the only method that should always be overridden in the Message Driven Bean
___________________________________
47] Which one of the following statements are requirements for the session bean's remote home interface?
1)The interface must extend javax.ejb.EJBObject.
2)The return type for a create<Method>(...) method must be void.
3)The throws clause of a create<Method>(...) method must include javax.ejb.CreateException.
4)The return type for a create<Method>(...) method must match the return type of the corresponding
ejbCreate<METHOD> method that is defined in the session bean class.
48] Which one of the following responsibilities related to session beans belong to the bean provider?
1)Ensuring that only one thread can execute a bean instance at anyone time
2)Managing the session bean instances at runtime.
3)Supplying resource connections used by an enterprise bean.
4)Deciding whether a session bean should use either container-managed or bean-managed transaction
demarcation.
5)Handling of a system exception thrown by a session bean's business method.
49] Which of the following responsibilities related to session bean's belong to the EJB container provider? [Select all
correct answers]
1)Affecting transaction management of a session bean with container-managed transaction demarcation.
2)Handling of a system exception thrown by a session bean's business method.
3)Defining the session bean class.

10

JAVA
4)Deciding whether a session bean should use either container-managed or bean-managed transaction
demarcation.
5)Supplying resource connections used by an enterprise bean.
50] Which of the following statements regarding the create methods of a session bean are correct. [Select all correct
answers]
1)Each session bean class must have at least one ejbCreate<METHOD>.
2)The return type of the ejbCreate method is the session bean's remote interface.
3)The container always calls ejbCreate() on the bean instance when a client invokes a create operation on the
home interface of a stateless session object.
4)ejbCreate() is invoked by the container with an unspecified transaction context.
5)Invoking EJBContext.getRollbackOnly() is not permitted in ejbCreate() of a session bean instance with
container-managed transaction demarcation.

Section 4(Practical)
1. A insurance company wants :
a) The details are taken from a HTML file (Name of the Customer, Type of Insurance Life Insurance or General
Insurance, Amount of policy).
b) There will be a validation wherein all the columns should be filled in, otherwise it will give error message that Items
not completed.
c) There will be a validation wherein the Amount column should be only numeric and an error message should be
thrown.
b) These details will be taken from a Servlet which will talk to an EJB
c) There will be an entity bean which will take these details and insert it in the database.
You are required to develop an application to this effect.Marks would be distributed as under:
1)
HTML file 10 Marks
2)
Servlet file with validations 20 marks
3)
Completed Servlet File 20 Marks
4)
Entity Bean code 30 Marks
5)
DD files 20 marks
2. Develop a Appraisal system for employees, wherein
a) The details are taken from a HTML file which will be filled in by the Manager would be (Employee ID, Name
of the Employee, Comments of the Manager).
b) There will be a validation wherein all the columns should be filled in, otherwise it will give error message that
Items not completed.
c) There will be a validation wherein the Employee ID column should be only numeric and an error message
should be thrown.
d) These details will be taken from a Servlet which will talk to an EJB.
e) There will be an entity bean which will take these details and insert it in the database.
Marks would be distributed as under:
1)
HTML file 10 Marks
2)
Servlet file with validations 20 marks
3)
Completed Servlet File 20 Marks
4)
Entity Bean code 30 Marks
5)
DD files 20 marks
3. scenario: XYZ limited has a branch office in Pune and they have their Head Office in Mumbai. The database is located
only in the Head office and using RMI logic we should develop an application, which will retrieve data from the database
on the client side.
The application should have
a)
Text Field to write the SQL Query
b)
Text Area to show the results
c)
OK button
d)
Use Anonymous listener to close the frame.
Write a code to simulate a Console Chatting program which will send and receive data.

11

JAVA
4. Scenario: ABC Limited having its head office in Mumbai has 3 branches in Indore, Patna and Delhi, where it will take
inquiries for its Computers.
These inquiries will be captured in an Application having the following fields:
a)
Party Name
b)
Party Address
c)
Client Office field which will have 3 branch office names
d)
Computer Specification field
e)
Ok Button
f)
Reset Button
The officers in Client Office will click on the OK Button and a text file will get generated and this file will be send to the
Head Office.
The Head Office will have a GUI where the file name will be captured and all the 4 information will be entered in a
Database, which is only present on the Server Side.
5. A insurance company wants :
a) The details are taken from a HTML file (Name of the Customer, Type of Insurance Life Insurance or General
Insurance, Amount of policy).
b) There will be a validation wherein all the columns should be filled in, otherwise it will give error message that Items
not completed.
c) There will be a validation wherein the Amount column should be only numeric and an error message should be
thrown.
b) These details will be taken from a Servlet which will talk to an EJB
c) There will be an entity bean which will take these details and insert it in the database.
You are required to develop an application to this effect.
Marks would be distributed as under:
1)
HTML file 10 Marks
2)
Servlet file with validations 20 marks
3)
Completed Servlet File 20 Marks
4)
Entity Bean code 30 Marks
5)
DD files 20 marks
6. Write a RMI / Networking program to simulate a GUI chatting process.

Section 5
Case study 1: Simulation and Modeling
The word simulate means to imitate or to have the same effect as. Computer simulation imitates an activity in the real
world using a computer program in order to understand how the real-world process behaves. The advantage of computer
simulation is that you can easily change the system to see the impact of modifications on the result. For example, an
airport designer might know the rates at which airplanes ar e coming in from other airports and how long it takes for a
single plane to land. The designer would like to estimate how many runways are needed to handle the load and how long,
on average, the airplanes would have to circle before they could land. Since planes don't come in from different airports
at perfectly spaced intervals, it would be hard to figure out the answers to these questions by hand. However, a simple
program to simulate the airport traffic can give good estimates to the designer. In this case study we will look the design
of a network router. Network routers are the connection points between different links in a network. Fig. 1 shows a
diagram of a simple network router. The r outer takes incoming messages from other routers and computers on a network
(the incoming lines) and copies them to another destination (the outgoing line).
Line 0
Router
Messages from both lines
Line 1
Incoming line outgoing line A network router has a set of input lines (feeder airports) that carry messages (airplanes) to
the node. The router forwards the messages to the outgoing lines (runways). It takes a certain amount of time to send the
message on the outgoing line (land the plane). During that time the outgoing line (runway) cannot be used for anything
else. The designer would like to know, given the expected input traffic, how many output lines (runways) are needed. If
the router does not allow messages to wait (planes to circle) until an outgoing line becomes available, the designer would
also like to know how many messages are lost (Planes are usually sent back to originating airport instead by being
thrown away.)
Study Questions Part I:
1. Find another real-world problem that is in the same form as the network routerproblem and the airport runway
simulation. Fill in the equivalents for the following.
Node:

12

JAVA
Message:
Incoming Line:
Outgoing Line:
Waiting:
2. For the example that you gave in study question 1, list possible events.
3. What types of events are identified by the Event class (Case Study Figure 2)?
4. What happened when an event that is not identified is created ( Lab Part A <2>)?
5. What data field in the Event class determines the order the events are removed from the Priority Queue (Case Study
Figure 9)?
6. Why does the Event class need to implement the Comparable interface? (Case Study Figure 2)?
7. How is the average interarrival time of an Incoming Line related to the arrival Parm (Lab Par t B <1>)?
8. Using the inter arrival times generated in your project in Lab Part I. B <2>, make a list of arrival times and interarrival
times for each line: Line Arrival Times Interarrival Times 0 1
9. Using the arrival times for the two lines, what is the average time between messages? Show your work (Case Study
Figure 4).
10. What is the expected time between the interleaved messages from the two lines if the simulation is run for a long time
(Case Study Figure 6)?
11. Explain why the two lines don't generate exactly the same number of messages. (Case Study Figure 5 ).
12. When the simulation ends, why doesn't the number of events (number Events) equal the number of messages
generated (total Messages) (Case Study Figure 13)?
13. How do you think the average time between message arrival at the router should be related to the number of
incoming lines and their individual arrival rates?
Case Study 2: Event-driven Simulation
We now need to decide on a strategy for implementing our simulation in a computer program. We could define objects
representing each of the items in the model (messages, lines and the router). We could have a variable representing time,
and as we step forward (increment time) we could ask each object in the model to perform the actions it would take at
this time. This general strategy is called time- driven simulation. The main difficulty with a time-dr iven strategy is that
in the real world, time is continuous. How large a step can we take in time and still be sure that we don't miss anything?
A second, more-common strategy is called event-driven simulation. Each thing that happens is represented by an event.
Examples of events are the ar rival of a message or the sending of a message in the networ k simulation. In the airport
simulations events may include taking off, circling the airport, landing and taxiing to the gate. The components of the
model gener ate events. The simulation itself keeps track of the events and sends them to the appropriate component for
processing in the order that they occurred. Time is updated to the time of the next event at each step in the simulation.
The idea of event-driven operation may seem strange at first. However, you have experienced this mode of operation in
using inter active computer applications such as word processors. When you open such an application, the program does
an initial setup and then waits for an event (e.g., a keystroke or a mouse- click from you indicating what to do). The
program processes the event and then resumes waiting for you to do something else. In contrast, most of the programs
that you write for your courses are execution-driven. They begin execution at a well-defined point (the main method)
and continue executing a well-specified sequence of commands until completion.
Study Question Part 2:
14. Suppose the UnbufferedNodeModel is run with one incoming line and one outgoing line. The incoming line produces
incoming messages at times 10, 45, 64, and 79. The outgoing line (initially free) takes 30 time units to send a message.
Trace the following values as the messsages are being processed. Which message( s) will be lost? (Case Study Figure
16)?
Start Time
Done Time
Messages Sent
Messages Lost
15. If the Event e received in processEvent is a MSG_ARRIVAL, the sendMessage method in OutgoingLine is invoked.
What will be returned if the line is free? What will be returned if the line is busy?
16. Explain why it is necessary to use the queue rather than a priority queue for the message buffer.
17. For each of 4 runs in Part I. C <5>, give an estimate of the expected average interarrival time. Write the expected
result for each of the 4 trials on the graph of Part II. C <1> and compare this with your simulation results.
18. As the average interarrival times increase, fewer messages will be ar riving. Use your chart in Part II. C <1> to
explain how lost messages will be affected in the unbufferd case.
19. Compare the outgoing line utilization of the buffered and unbuffered models as the average interarrival times
decrease.
20. Which of the models (unbuffered or buffered) performs better when the lines are very busy (interarrival time is
small). Explain this observation.
Case Study 3: Events
Each thing that happens is called an event. Events have a who (who caused the event to happen) a what (what type of
event happened), and a when (what time did the event occur). For the network simulation the events are mainly the
sending and arriving of messages. What are the events in an airport simulation? Fig. 2 shows a definition of the Event
class that we will use in the simulation. Notice that Event implements the Java Comparable interface. This means that
Event objects can be ordered. In this case they are ordered by their times.
Figure 2: The Event Class

13

JAVA
public class Event implements Comparable {
public static final int STOP = 0;
public static final int MSG_ARRIVAL = 1;
public static final int MSG_SENT = 2;
private int who; // Who did it
private int what; // What they did
private double when; // When they did it
public Event(int ID, int type,
double time) {
who = ID;
what = type;
when = time;
}
public int getWho( ) {return who;}
public int getWhat( ) {return what;}
public double getWhen( ) {r eturn when;}
public int compareTo ( Object rhs)
throws ClassCastException{
double rhsTime = ((Event)rhs).getWhen();
return when < rhsTime ? -1:
rhsTime < when ? 1: 0;
}
public String toString(){
return "[Who:" + who + ", What:" + what + ", When:" + when +"]";
}
}
In the simulation we will want to process events in the order that they occur. The priority queue is a natural data structure
for storing events in a specified or der as they come in. We can use the deleteMin method of PriorityQueue to remove the
event from the prior ity queue with the smallest when, that is, the event that happened first. We will use the priority
queue specification and implementations from the Weiss Data
Structures Textbook (Fig. 3) : Figure 3: The PriorityQueue Interface
public inter face PriorityQueue {
Position insert( Comparable x ) // --> Inserts x
Comparable deleteMin( ) // --> Removes and returns the smallest item
Comparable findMin( ) // --> Returns smallest item
void makeEmpty( )
// - -> Removes all items
boolean isEmpty( )
// --> Returns true if empty; else false
int size( )
// --> Retur ns the size of the queue
void decreaseKey(Position p, Comparable newVal) //--> For special implementations
}
Example: Write code to generate 100 MSG_ARRIVAL events with consecutive ID numbers and random times of
occurrence between 0 and 1000. Place the events on a priority queue as they are generated. Remove them and calculate
the average interarrival time between events. What would you expect the interar rival time to be?
int numberEvents = 100;
double maxTime = 1000;
PriorityQueue p = new BinaryHeap();
Random randproc = new Random();
// Generate the events and put them on the queue
for (int i = 0; i < number Events; i++) {
Event e = new Event(i, Event.MSG_ARRIVAL,
randproc.nextDouble()*maxTime);
p.insert(e);
}
double lastArr ival = 0.0;
for (int j = 0; j < number Events; j++) {
Event e = (Event)(p.deleteMin());
System.out.println("Removing " + e);
lastAr rival = e.getWhen( );
}
System.out.println("The average interarrival is " + (lastArrival/numberEvents));
case study 4: The Buffered Router
The buffered router has an incoming line, and outgoing line and a buffer for temporarily holding messages when the
outgoing line is busy. The incoming line generates messages randomly, with a specified aver age rate. The outgoing line

14

JAVA
takes a fixed amount of time to send a message out. If the incoming line produces a message before the outgoing line has
finished sending, the new message is placed in the buffer (we will use a queue) until the outgoing line is free. The
messages will be removed fr om the queue(sent) in the order they were received. The following changes that are needed
to convert the UnbufferedNodeModel class to a
BufferedNodeModel class:
Fields: Add a pr ivate data item Queue messageBuffer
Constructor: Instantiate a new QueueAr object to initialize messageBuffer.
Event processing: In processEvent
If the event is a MSG_ARRI VAL and if the outgoing line is busy, place the event in messageBuffer ( use enqueue).
If the event is a MSG_SENT, finish the message as before but if messageBuffer is not empty get the next event from
messageBuffer (use dequeue) and try to send the message. If the send is successful, add a new MSG_SENT event to the
pr iority queue.
Case Study 5: Bowling Scores
The game of bowling is a world-wide sport. More than 95 million
people bowl, in 90 countries spanning six continents
. It is played by rolling a ball down a bowling lane to knock down
the pins at the end of the lane. The situation is diagrammed in
Figure 1.A bowling game is divided into ten frames . The bowler is
allowed up to two balls in each frame to knock down all ten pins.
Knocking down all the pins with the first ball ends the frame, and is
called a strike. Knocking down all the pins with the first two balls is
called a spare
Knocking down fewer than ten pins with the fir st two balls is called a miss . A bowler earns one point for each
pin knocked down, plus bonuses for each str ike and spare. A strike scores 10 points plus the total of the next
two balls; a spare scores 10 points plus the score of the next ball. A strike in the tenth frame earns the bowler
two
extra balls; a spare in the tenth frame earns one extra ball. An example of how a game is scored is shown in Table 1.
Bowlers use a score sheet thats organized to clearly display the score for each frame and each ball. By convention, they
use an X to represent a strike and a / (slash) to represent a spare. Heres how the game in Table 1 would be scored: In
olden days, bowlers kept their own scores. Computers, however, have brought automatic scorekeeping to bowling. After
each ball, sensors count and tally the number of pins knocked down.
Frame
balls
score for the frame
cumulative score
1
9+1 (spare)
10+0=10
10
2
0+10 (spare)
10+10=20
30
3
10 (strike)
10+10+6=26
56
4
10 (strike)
10+6+2=18
74
5
6+2
8
82
6
7+3 (spare)
10+8=18
100
7
8+2 (spare)
10+10=20
120
8
10 (strike)
10+9+0=19
139
9
9+0
9
148
10
10 (strike)
10+10+8=28
176
+10+8 (bonuses)
Table 1: A sample bowling game

Case Study 6: Automatic bowling scorer


Design and implement a class that represents an automatic bowling scorer object. It will provide several methods:
a constructor;
an int frameNumber method that r eturns the number of the frame containing the ball about to be rolled;
an int scoreSoFar method that returns the score in the game so far;
a boolean gameIsOver method that r etur ns true when the tenth frame has been scored and false otherwise, and which
causes the next roll to start a new game;
an int [ ] roll method that, given the number of pins knocked down by a roll of the ball, returns an arr ay whose
length is the number of frames completely scored and whose contents are the cumulative scores for those frames.
The arrays returned by roll in the game just described appear in Table 2. You may assume that the argument to roll
correctly represents the number of pins knocked down by the roll. That is, no error checking is necessary.

15

You might also like