MT0045

35
August 2010 Master of Science in Information Technology (MScIT- NEW) – Semester 3 MT0045 –: Java– 2 Credits (Book ID: B0831) Assignment Set – 1 (20 Marks) 1. Explain the following features of java a) Multithreaded A fundamental concept of computer programming is the idea of handling more than one task at a time. Within a program these separately running pieces are called threads and the general concept is called multithreading. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. Each thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. When a Java Virtual Machine starts up there is usually a single non-daemon thread. The Java Virtual Machine continues to execute threads until either of the following occurs. The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place. All threads that are not daemon threads have died either by returning from the call to the run method or by performing the stop method.

Transcript of MT0045

Page 1: MT0045

August 2010

Master of Science in Information Technology (MScIT-NEW) – Semester 3

MT0045 –: Java– 2 Credits(Book ID: B0831)

Assignment Set – 1 (20 Marks)

1. Explain the following features of java

a) Multithreaded

A fundamental concept of computer programming is the idea of handling more than one task at a

time. Within a program these separately running pieces are called threads and the general concept is

called multithreading.

The Java Virtual Machine allows an application to have multiple threads of execution running

concurrently. Each thread has a priority. Threads with higher priority are executed in preference to

threads with lower priority. When a Java Virtual Machine starts up there is usually a single non-

daemon thread. The Java Virtual Machine continues to execute threads until either of the following

occurs.

The exit method of class Runtime has been called and the security manager has permitted the exit

operation to take place.

All threads that are not daemon threads have died either by returning from the call to the run method

or by performing the stop method.

There are two ways to create a new thread of execution. One is to declare a class to be subclass of

Thread. This subclass should override the run method of class Thread. An instance of the subclass can

then be allocated and started.

Dynamic

Page 2: MT0045

While executing the java program the user can get the required files dynamically from a local drive or

from a computer thousands of miles away from the user just by connecting with the Internet.

2. Explain how you can compile and execute a java program.

Let’s assume that the JDK has been installed in

C:\Program Files\java\jdk1.6.0_07

and your program is stored in a file AreaOfSquare.java in the folder C:\MyJava.

We will run our programs using the “Command Prompt” window. This is also called the MS-DOS

window.

Open the window by clicking on Start > All Programs > Accessories > Command Prompt

At the command prompt >, type cd C:\MyJava

The window should now look as follows (your first lines may be slightly different):

This changes the directory to the folder containing your program, AreaOfSquare.java.

To compile the program, we would like to type

javac AreaOfSquare.java

where javac.exe is the file containing the compiler.

However, if we did this, we would get a message to the effect that javac is unknown.

1

Page 3: MT0045

The file javac.exe is found in the bin folder of the JDK.

C:\Program Files\java\jdk1.6.0_07\bin is called the “path” to the compiler. We must tell Windows

where to find the compiler by setting the Path “environment variable.”

How to set the "Path"

To set Path, go to Start > Control Panel and open the System control panel.

Click on the Advanced tab and then on Environment Variables. In the section System variables, click

on Path (you may need to scroll) and then on Edit. In the pop-up window, click in the Variable value

field and use the right arrow key to go to the end of the field.

Type a semi-colon ( ; ) if one is not present as the last character on the line. After the semi-colon, type

the path C:\Program Files\java\jdk1.6.0_07\bin\ or C:\ jdk1.6\bin\ or to wherever you installed it.

Click OK all the way out to the Control Panel.

Now you can type

javac xxxx.java

(where xxxx is the name of your program) from any command prompt and Windows will know where

to find the compiler.

Helpful hint: if you’ve set Path correctly and it doesn’t work, close the Command Prompt window and

then reopen it. (If it is open when you set Path, it will not recognize the change.)

Compile and execute

Now that you’ve set Path, you can compile the program with

javac AreaOfSquare.java

If there are no errors in the program, the compiler will create a file called AreaOfSquare.class in the

folder C:\MyJava. This file contains the Java bytecode (think of it as machine language) equivalent of

the source program.

2

Page 4: MT0045

To execute the program, type

java AreaOfSquare

(Note that you do not type .class.) This invokes the Java interpreter, java.exe, also stored in the bin

folder of the JDK. The Java interpreter will execute the code in the class file.

Here, the computer will type

Enter length of side:

and wait for you to enter a number. Suppose you type 12. The screen will then look like this:

Enter length of side: 12

Area of square is 144

and you are returned to the command prompt. The following shows the Command Prompt window at

the end of the above activities:

3. Explain the switch statement in java.

The switch statement transfers control to one of several statements depending on the value of an

expression.

SwitchStatement:

switch ( Expression ) SwitchBlock

SwitchBlock:

{ SwitchBlockStatementGroupsopt SwitchLabelsopt }

3

Page 5: MT0045

SwitchBlockStatementGroups:

SwitchBlockStatementGroup

SwitchBlockStatementGroups SwitchBlockStatementGroup

SwitchBlockStatementGroup:

SwitchLabels BlockStatements

SwitchLabels:

SwitchLabel

SwitchLabels SwitchLabel

SwitchLabel:

case ConstantExpression :

default :

The type of the Expression must be char, byte, short, or int, or a compile-time error occurs.

The body of a switch statement is known as a switch block. Any statement immediately contained by

the switch block may be labeled with one or more case or default labels. These labels are said to be

associated with the switch statement, as are the values of the constant expressions (§15.28) in the

case labels.

All of the following must be true, or a compile-time error will result:

Every case constant expression associated with a switch statement must be assignable (§5.2) to the

type of the switch Expression.

No two of the case constant expressions associated with a switch statement may have the same value.

At most one default label may be associated with the same switch statement. In C and C++ the body of

a switch statement can be a statement and statements with case labels do not have to be immediately

contained by that statement. Consider the simple loop:

for (i = 0; i < n; ++i) foo();

4

Page 6: MT0045

where n is known to be positive. A trick known as Duff's device can be used in C or C++ to unroll the

loop, but this is not valid code in the Java programming language:

int q = (n+7)/8;

switch (n%8) {

case 0: do { foo(); // Great C hack, Tom,

case 7: foo(); // but it's not valid here.

case 6: foo();

case 5: foo();

case 4: foo();

case 3: foo();

case 2: foo();

case 1: foo();

} while (--q >= 0);

}

Fortunately, this trick does not seem to be widely known or used. Moreover, it is less needed

nowadays; this sort of code transformation is properly in the province of state-of-the-art optimizing

compilers.

When the switch statement is executed, first the Expression is evaluated. If evaluation of the

Expression completes abruptly for some reason, the switch statement completes abruptly for the same

reason. Otherwise, execution continues by comparing the value of the Expression with each case

constant. Then there is a choice:

If one of the case constants is equal to the value of the expression, then we say that the case matches,

and all statements after the matching case label in the switch block, if any, are executed in sequence. If

all these statements complete normally, or if there are no statements after the matching case label,

then the entire switch statement completes normally.

If no case match but there is a default label, then all statements after the matching default label in the

switch block, if any, are executed in sequence. If all these statements complete normally, or if there

are no statements after the default label, then the entire switch statement completes normally.

If no case matches and there is no default label, then no further action is taken and the switch

statement completes normally.

5

Page 7: MT0045

If any statement immediately contained by the Block body of the switch statement completes

abruptly, it is handled as follows:

If execution of the Statement completes abruptly because of a break with no label, no further action is

taken and the switch statement completes normally.

If execution of the Statement completes abruptly for any other reason, the switch statement

completes abruptly for the same reason. The case of abrupt completion because of a break with a

label is handled by the general rule for labeled statements.

As in C and C++, execution of statements in a switch block "falls through labels."

For example, the program:

class Toomany {

static void howMany(int k) {

switch (k) {

case 1: System.out.print("one ");

case 2: System.out.print("too ");

case 3: System.out.println("many");

}

}

public static void main(String[] args) {

howMany(3);

howMany(2);

howMany(1);

}

}

contains a switch block in which the code for each case falls through into the code for the next case. As

a result, the program prints:

many

too many

one too many

6

Page 8: MT0045

If code is not to fall through case to case in this manner, then break statements should be used, as in

this example:

class Twomany {

static void howMany(int k) {

switch (k) {

case 1: System.out.println("one");

break; // exit the switch

case 2: System.out.println("two");

break; // exit the switch

case 3: System.out.println("many");

break; // not needed, but

good style

}

}

public static void main(String[] args) {

howMany(1);

howMany(2);

howMany(3);

}

}

This program prints:

one

two

many

4. What is an Exception? What are the different types of Exceptions?

7

Page 9: MT0045

Exceptions are the customary way in Java to indicate to a calling method that an abnormal condition

has occurred. When a method encounters an abnormal condition (an exception condition) that it can't

handle itself, it may throw an exception. When a program violates the semantic constraints of the Java

programming language, the Java virtual machine signals this error to the program as an exception. An

example of such a violation is an attempt to index outside the bounds of an array.

Some programming languages and their implementations react to such errors by peremptorily

terminating the program; other programming languages allow an implementation to react in an

arbitrary or unpredictable way. Neither of these approaches is compatible with the design goals of the

Java platform: to provide portability and robustness. Instead, the Java programming language specifies

that an exception will be thrown when semantic constraints are violated and will cause a non-local

transfer of control from the point where the exception occurred to a point that can be specified by the

programmer. An exception is said to be thrown from the point where it occurred and is said to be

caught at the point to which control is transferred.

Throwing an exception is like throwing a beeping, flashing red ball to indicate there is a problem that

can't be handled where it occurred. Somewhere, you hope, this ball will be caught and the problem

will be dealt with. Exceptions are caught by handlers positioned along the thread's method invocation

stack. If the calling method isn't prepared to catch the exception, it throws the exception up to its

calling method, and so on. If one of the threads of your program throws an exception that isn't caught

by any method along the method invocation stack, that thread will expire. When you program in Java,

you must position catchers (the exception handlers) strategically, so your program will catch and

handle all exceptions from which you want your program to recover.

Exception classes

In Java, exceptions are objects. When you throw an exception, you throw an object. You can't throw

just any object as an exception, however -- only those objects whose classes descend from Throwable.

Throwable serves as the base class for an entire family of classes, declared in java.lang, that your

program can instantiate and throw. A small part of this family is shown in Figure 1.

As you can see in Figure 1, Throwable has two direct subclasses, Exception and Error. Exceptions

(members of the Exception family) are thrown to signal abnormal conditions that can often be handled

by some catcher, though it's possible they may not be caught and therefore could result in a dead

thread. Errors (members of the Error family) are usually thrown for more serious problems, such as

8

Page 10: MT0045

OutOfMemoryError, that may not be so easy to handle. In general, code you write should throw only

exceptions, not errors. Errors are usually thrown by the methods of the Java API, or by the Java virtual

machine itself.

Figure 1. A partial view of the Throwable family

In addition to throwing objects whose classes are declared in java.lang, you can throw objects of your

own design. To create your own class of throwable objects, you need only declare it as a subclass of

some member of the Throwable family. In general, however, the throwable classes you define should

extend class Exception. They should be "exceptions." The reasoning behind this rule will be explained

later in this article.

Whether you use an existing exception class from java.lang or create one of your own depends upon

the situation. In some cases, a class from java.lang will do just fine. For example, if one of your

methods is invoked with an invalid argument, you could throw IllegalArgumentException, a subclass of

RuntimeException in java.lang.

Other times, however, you will want to convey more information about the abnormal condition than a

class from java.lang will allow. Usually, the class of the exception object itself indicates the type of

abnormal condition that was encountered. For example, if a thrown exception object has class

IllegalArgumentException, that indicates someone passed an illegal argument to a method. Sometimes

9

Page 11: MT0045

you will want to indicate that a method encountered an abnormal condition that isn't represented by a

class in the Throwable family of java.lang.

As an example, imagine you are writing a Java program that simulates a customer of a virtual café drinking a cup of coffee. Consider the exceptional conditions that might occur while the customer sips. The class hierarchy of exceptions shown in Figure 2 represents a few possibilities.

Figure 2. Exception hierarchy for coffee sipping

If the customer discovers, with dismay, that the coffee is cold, your program could throw a

TooColdException. On the other hand, if the customer discovers that the coffee is overly hot, your

program could throw a TooHotException. These conditions could be exceptions because they are

(hopefully) not the normal situation in your café. (Exceptional conditions are not necessarily rare, just

outside the normal flow of events.) The code for your new exception classes might look like this:

// In Source Packet in file except/ex1/TemperatureException.java

class TemperatureException extends Exception {

}

// In Source Packet in file except/ex1/TooColdException.java

class TooColdException extends TemperatureException {

}

10

Page 12: MT0045

// In Source Packet in file except/ex1/TooHotException.java

class TooHotException extends TemperatureException {

}

This family of classes, the TemperatureException family, declares three new types of exceptions for

your program to throw. Note that each exception indicates by its class the kind of abnormal condition

that would cause it to be thrown: TemperatureException indicates some kind of problem with

temperature; TooColdException indicates something was too cold; and TooHotException indicates

something was too hot. Note also that TemperatureException extends Exception -- not Throwable,

Error, or any other class declared in java.lang.

Exceptions in Java

Throwable Class

The Throwable class provides a String variable that can be set by the subclasses to provide a detail

message that provides more information of the exception occurred. All classes of throwables define a

one-parameter constructor that takes a string as the detail message.

The class Throwable provides getMessage() function to retrieve an exception. It has a printStackTrace()

method to print the stack trace to the standard error stream. Lastly It also has a toString() method to

print a short description of the exception. For more information on what is printed when the following

messages are invoked, please refer the java docs.

Syntax

String getMessage()

void printStackTrace()

String toString()

Class Exception

11

Page 13: MT0045

The class Exception represents exceptions that a program faces due to abnormal or special conditions

during execution. Exceptions can be of 2 types: Checked (Compile time Exceptions)/ Unchecked (Run

time Exceptions).

Class RuntimeException

Runtime exceptions represent programming errors that manifest at runtime. For example

ArrayIndexOutOfBounds, NullPointerException and so on are all subclasses of the

java.lang.RuntimeException class, which is a subclass of the Exception class. These are basically

business logic programming errors.

Class Error

Errors are irrecoverable condtions that can never be caught. Example: Memory leak, LinkageError etc.

Errors are direct subclass of Throwable class.

Checked and Unchecked Exceptions

Checked exceptions are subclass’s of Exception excluding class RuntimeException and its subclasses.

Checked Exceptions forces programmers to deal with the exception that may be thrown. Example:

Arithmetic exception. When a checked exception occurs in a method, the method must either catch

the exception and take the appropriate action, or pass the exception on to its caller

Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses

also are unchecked. Unchecked exceptions , however, the compiler doesn’t force the programmers to

either catch the exception or declare it in a throws clause. In fact, the programmers may not even

know that the exception could be thrown. Example: ArrayIndexOutOfBounds Exception. They are

either irrecoverable (Errors) and the program should not attempt to deal with them, or they are logical

programming errors. (Runtime Exceptions). Checked exceptions must be caught at compile time.

Runtime exceptions do not need to be. Errors often cannot be.

Exception Statement Syntax

Exceptions are handled using a try-catch-finally construct, which has the Syntax

12

Page 14: MT0045

try {

<code>

} catch (<exception type1> <parameter1>) { // 0 or more

<statements>

}

} finally { // finally block

<statements>

}

try Block

The java code that you think may produce an exception is placed within a try block for a

suitable catch block to handle the error.

If no exception occurs the execution proceeds with the finally block else it will look for the

matching catch block to handle the error. Again if the matching catch handler is not found execution

proceeds with the finally block and the default exception handler throws an exception. If an exception

is generated within the try block, the remaining statements in the try block are not executed.

catch Block

Exceptions thrown during execution of the try block can be caught and handled in a catch block. On

exit from a catch block, normal execution continues and the finally block is executed

(Though the catch block throws an exception).

finally Block

A finally block is always executed, regardless of the cause of exit from the try block, or whether any

catch block was executed. Generally finally block is used for freeing resources, cleaning up, closing

connections etc. If the finally clock executes a control transfer statement such as a return or a break

statement, then this control statement determines how the execution will proceed regardless of any

return or control statement present in the try or catch.

The following program illustrates the scenario.

try { <code>} catch (<exception type1> <parameter1>) { // 0 or more <statements>

13

Page 15: MT0045

}} finally { // finally block <statements>}

Output

Computing Division.Exception : / by zeroFinally Block Executes. Exception Occurredresult : -1

August 2010

Master of Science in Information Technology (MScIT-NEW) – Semester 3

MT0045 –: Java– 2 Credits

(Book ID: B0831)

Assignment Set – 2 (20 Marks)

Each question carries 5 marks

1. What are the different methods used in Input stream class and output stream class.

The java.io package contains two classes, InputStream and OutputStream, from which most of

the other classes in the package derive.

14

Page 16: MT0045

Figure : InputStream class hierarchy (partial)

The InputStream class is an abstract superclass that provides a minimal programming interface and a

partial implementation of input streams. The InputStream class defines methods for reading bytes or

arrays of bytes, marking locations in the stream, skipping bytes of input, finding out the number of

bytes available for reading, and resetting the current position within the stream. An input stream is 15

Page 17: MT0045

automatically opened when you create it. You can explicitly close a stream with the close method, or

let it be closed implicitly when the InputStream is garbage collected. Remember that garbage

collection occurs when the object is no longer referenced.

Methods available in InputSteam:

int available()

Returns the number of bytes that can be read (or skipped over) from this input stream without blocking by the next caller of a method for this input stream.

void close()

Closes this input stream and releases any system resources associated with the stream.

void mark(int readlimit)

Marks the current position in this input stream.

boolean markSupported()

Tests if this input stream supports the mark and reset methods.

abstract int read()

Reads the next byte of data from the input stream.

int read(byte[] b)

Reads some number of bytes from the input stream and stores them into the buffer array b.

int read(byte[] b, int off, int len)

Reads up to len bytes of data from the input stream into an array of bytes.

void reset()

Repositions this stream to the position at the time the mark method was last called on this input stream.

long skip(long n)

Skips over and discards n bytes of data from this input stream.

16

Page 18: MT0045

Figure : OutputStream class hierarchy (partial)

The OutputStream class is an abstract superclass that provides a minimal programming interface and a

partial implementation of output streams. OutputStream defines methods for writing bytes or arrays

of bytes to the stream. An output stream is automatically opened when you create it. You can explicitly

close an output stream with the close method, or let it be closed implicitly when the OutputStream is

garbage collected, which occurs when the object is no longer referenced.

Methods available in InputSteam:

void close()

17

Page 19: MT0045

Closes this output stream and releases any system resources associated with this stream.

void flush()

Flushes this output stream and forces any buffered output bytes to be written out.

void write(byte[] b)

Writes b.length bytes from the specified byte array to this output stream.

void write(byte[] b, int off, int len)

Writes len bytes from the specified byte array starting at offset off to this output stream.

abstract void write(int b)

Writes the specified byte to this output stream.

The java.io package contains several subclasses of InputStream and OutputStream that implement

specific input or output functions. For example, FileInputStream and FileOutputStream are input and

output streams that operate on files on the native file system.

The first of the following two figures shows the class hierarchy for the input stream classes in the

java.io package. The second figure shows the class hierarchy for the output stream classes in the

java.io package.

read and write methods

InputStream class defines the following methods for reading bytes -

int read() throws IOException

int read(byte b[]) throws IOException

int read(byte b[], int offset, int length) throws IOException

Subclasses of InputStream implement the above mentioned methods.

OutputStream class defines the following methods for writing bytes -

void write(int b) throws IOException

void write(byte b[]) throws IOException

void write(byte b[], int offset, int length) throws IOException

Subclasses of OutputStream implement the above mentioned methods

18

Page 20: MT0045

2. What are Applets? What are different methods used to describe the life cycle

of an applet?

An applet is a special kind of Java program that a browser enabled with Java technology can download from the internet and run. An applet is typically embedded inside a web page and runs in the context of a browser. An applet must be a subclass of the java.applet.Applet class. The Applet class provides the standard interface between the applet and the browser environment.

Swing provides a special subclass of the Applet class called javax.swing.JApplet. The JApplet class should be used for all applets that use Swing components to construct their graphical user interfaces (GUIs).

The browser's Java Plug-in software manages the lifecycle of an applet.

An applet can react to major events in the following ways:

It can initialize itself. It can start running. It can stop running. It can perform a final cleanup, in preparation for being unloaded.

This section introduces a new applet, Simple, that uses all of these methods. Unlike Java applications, applets do not need to implement a main method.

Here is the Simple applet.

The following is the source code for the Simple applet. This applet displays a descriptive string whenever it encounters a major milestone in its life, such as when the user first visits the page the applet is on.

import java.applet.Applet;import java.awt.Graphics;

//No need to extend JApplet, since we don't add any components;//we just paint.public class Simple extends Applet {

StringBuffer buffer;

public void init() { buffer = new StringBuffer(); addItem("initializing... ");

19

Page 21: MT0045

}

public void start() { addItem("starting... "); }

public void stop() { addItem("stopping... "); }

public void destroy() { addItem("preparing for unloading..."); }

private void addItem(String newWord) { System.out.println(newWord); buffer.append(newWord); repaint(); }

public void paint(Graphics g) {//Draw a Rectangle around the applet's display area.

g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);

//Draw the current string inside the rectangle. g.drawString(buffer.toString(), 5, 15); }}

Here are the lifecycle methods of an Applet:

init(): This method is called to initialized an applet

start(): This method is called after the initialization of the applet.

stop(): This method can be called multiple times in the life cycle of an Applet.

destroy(): This method is called only once in the life cycle of the applet when applet is destroyed.

init () method: The life cycle of an applet is begin on that time when the applet is first loaded into

the browser and called the init() method. The init() method is called only one time in the life cycle

on an applet. The init() method is basically called to read the PARAM tag in the html file. The init ()

method retrieve the passed parameter through the PARAM tag of html file using get Parameter()

method All the initialization such as initialization of variables and the objects like image, sound file 20

Page 22: MT0045

are loaded in the init () method .After the initialization of the init() method user can interact with

the Applet and mostly applet contains the init() method.

Start () method: The start method of an applet is called after the initialization method init(). This

method may be called multiples time when the Applet needs to be started or restarted. For Example

if the user wants to return to the Applet, in this situation the start Method() of an Applet will be

called by the web browser and the user will be back on the applet. In the start method user can

interact within the applet.

Stop () method: The stop() method can be called multiple times in the life cycle of applet like the

start () method. Or should be called at least one time. There is only miner difference between the

start() method and stop () method. For example the stop() method is called by the web browser on

that time When the user leaves one applet to go another applet and the start() method is called on

that time when the user wants to go back into the first program or Applet.

destroy() method: The destroy() method is called only one time in the life cycle of Applet like init()

method. This method is called only on that time when the browser needs to Shut down.

3. What do you mean by java bean? What are the advantages of java beans?

JavaBeans are reusable software components for Java that can be manipulated visually in a builder

tool. Practically, they are classes written in the Java programming language conforming to a particular

convention. They are used to encapsulate many objects into a single object (the bean), so that they

can be passed around as a single bean object instead of as multiple individual objects. A JavaBean is a

Java Object that is serializable, has a nullary constructor, and allows access to properties using getter

and setter methods.

JavaBeans is Java's component model. It allows users to construct applications by piecing components

together either programmatically or visually (or both). Support of visual programming is paramount to

the component model; it's what makes component-based software development truly powerful.

The model is made up of architecture and an API (Application Programming Interface). Together, these

elements provide a structure whereby components can be combined to create an application. This

21

Page 23: MT0045

environment provides services and rules, the framework that allows components to participate

properly. This means that components are provided with the tools necessary to work in the

environment, and they exhibit certain behaviors that identify them as such. One very important aspect

of this structure is containment. A container provides a context in which components can interact. A

common example would be a panel that provides layout management or mediation of interactions for

visual components. Of course, containers themselves can be components.

TestPersonBean.java:

import beans.PersonBean; /** * Class <code>TestPersonBean</code>. */public class TestPersonBean { /** * Tester method <code>main</code> for class <code>PersonBean</code>. * @param args */ public static void main(String[] args) { PersonBean person = new PersonBean(); person.setName("Bob"); person.setDeceased(false); // Output: "Bob [alive]" System.out.print(person.getName()); System.out.println(person.isDeceased() ? " [deceased]" : " [alive]"); }}

testPersonBean.jsp:

<% // Use of PersonBean in a JSP. %><jsp:useBean id="person" class="beans.PersonBean" scope="page"/><jsp:setProperty name="person" property="*"/> <html><body>Name: <jsp:getProperty name="person" property="name"/><br/>Deceased? <jsp:getProperty name="person" property="deceased"/><br/><br/>

22

Page 24: MT0045

<form name="beanTest" method="POST" action="testPersonBean.jsp">Enter a name: <input type="text" name="name" size="50"><br/>Choose an option:<select name="deceased"> <option value="false">Alive</option> <option value="true">Dead</option></select><input type="submit" value="Test the Bean"></form></body></html>

Advantages of Java Beans

Software component architecture provides standard mechanisms to deal with software building

blocks. The following list enumerates some of the specific benefits that Java technology provides

for a component developer:

A Bean obtains all the benefits of Java's "write-once, run-anywhere" paradigm.

The properties, events, and methods of a Bean that are exposed to an application

builder tool can be controlled.

A Bean may be designed to operate correctly in different locales, which makes it

useful in global markets.

Auxiliary software can be provided to help a person configure a Bean. This software is

only needed when the design-time parameters for that component are being set. It

does not need to be included in the run-time environment.

The configuration settings of a Bean can be saved in persistent storage and restored

at a later time.

A Bean may register to receive events from other objects and can generate events that

are sent to other objects.

4. Explain 2-tier and N-tier architecture.

2-tier architecture:

23

Page 25: MT0045

In a two-tier system we have a client program and a server program. The main difference between the

two is that the server responds to requests from many different clients while the clients usually initiate

the requests for information from a single server.

Two-tier client/server architectures have 2 essential components

1. A Client PC and

2. A Database Server

2-Tier Considerations:

• Client program accesses database directly

o Requires a code change to port to a different database

o Potential bottleneck for data requests

o High volume of traffic due to data shipping

• Client program executes application logic

o Limited by processing capability of client workstation (memory, CPU)

o Requires application code to be distributed to each client workstation

24

Page 26: MT0045

Figure 7.1 Client/Server 2-Tier Architecture

Usually N-Tier Architecture begins as a 3-Tier model and is expanded. It provides finer granularity.

Granularity is the ability of a system, in this case, an application, to be broken down into smaller

components or granules. The finer the granularity, the greater the flexibility of a system. It can also be

referred to as a system’s modularity. Therefore, it refers to the pulling apart of an application into

separate layers or finer grains.

One of the best examples of N-Tier Architecture in web applications is the popular shopping-cart web

application. The client tier interacts with the user through GUIs (Graphic User Interfaces) and with the

application and the application server. In web applications, this client tier is a web browser. In addition

to initiating the request, the web browser also receives and displays code in dynamic HTML (Hypertext

Markup Language), the primary language of the World Wide Web. In a shopping cart web application,

the presentation tier displays information related to such services as browsing merchandise,

purchasing, and shopping cart contents. It communicates with other tiers by outputting results to the

browser/client tier and all other tiers in the network. This layer calls custom tags throughout the

network and to other networks. It also calls database stored procedures and web services, all in the

goal of providing a more sophisticated response. This layer glues the whole application together and

allows different nodes to communicate with each other and be displayed to the user through the

browser. It is located in the application server.

25

Page 27: MT0045

In N-Tier Architecture, the business logic tier is pulled out from the presentation tier and, as its own

layer, it controls an application’s functionality by performing detailed processing. For example, in our

shopping cart example, this tier completes credit card authorization and calculates things like shipping

costs and sales tax. The tools used to encapsulate an application’s business logic into its own layer

include web services, custom tags, and stored procedures.

The business tier can also be considered the integration layer. Encapsulation allows the application to

communicate with the data tier or the business logic tier in a way that is intelligible to all nodes.

Encapsulation is one of the principles of object-oriented programming (OOP) and refers to an object’s

ability to conceal its data and methods. Encapsulated objects only publish the external interface so any

user interacting with them only needs to understand the interface and can remain ignorant as to the

internal specifications. This way a user can call all sorts of services into action by calling the custom tag

without having to know the code details of what made communication or implementation possible.

The services just have to be accessible in the custom tag library. Encapsulation in the integration tier

also liberates the network from just one vendor. The integration tier allows N-Tier Architecture to be

vendor independent. In the shopping cart example, the application may have a simple custom tag for

searching inventory and providing the most up-to-date, detailed information.

See diagram of N-Tier Architecture for an overview of all these technologies and how they fit in .

26

Page 28: MT0045

The final application tier is the data tier. It usually consists of database servers. It keeps data neutral

and independent from application servers or business logic. Giving data its own tier also improves

scalability and performance. As it grows, it is easily moved to another, more powerful machine.

27

Page 29: MT0045

3-tier architecture:

A three-tier application we have a client a server and a database in which the server stores its data.

The flow of information is still essentially linear: a request comes from the client to the server; the

server requests or stores data in the database; the database returns information to the server; the

server returns information back to the client.

First, we must make a distinction between layers and tiers. Layers are the way to logically break code into components and tiers are the physical nodes to place the components on. This question explains

it better: http://stackoverflow.com/questions/120438/whats-the-difference-between-layers-and-tiers

A two layer architecture is usually just a presentation layer and data store layer. These can be on 1 tier

(1 machine) or 2 tiers (2 machines) to achieve better performance by distributing the work load.

A three layer architecture usually puts something between the presentation and data store layers

such as a business logic layer or service layer. Again, you can put this into 1, 2, or 3 tiers depending on how much money you have for hardware and how much load you expect.

Putting multiple machines in a tier will help with the robustness of the system by providing redundancy.

Below is a good example of a layered architecture:

28

Page 30: MT0045

An n-tier architecture, on the other hand, allows an unlimited number of programs to run

simultaneously, send information to one another, use different protocols to communicate, and

interact concurrently. This allows for a much more powerful application, providing many different

services to many different clients.

29