MC0078 SMU MCA SEM4 2011

40
July 2011 Master of Computer Application (MCA) – Semester 4 MC0078 – Java Programming (Book ID: B0831 & B0832) Assignment Set – 1 Q: 1. Write a program to perform the basic arithmetic operations: a) Addition b) Subtraction c) Multiplication d) Division Use 4 different methods for the above and invoke them as necessary from the main () method. Ans: Public class Test { /*Method to add two numbers */ Public void Add() { int a=10; int b=20; int c; c=a+b; System.out.println(“The sum of two numbers is:”+c) } /* Method to subtract two numbers*/ Public void Subtract() {

description

MC0078 SMU MCA SEM4 2011

Transcript of MC0078 SMU MCA SEM4 2011

Page 1: MC0078 SMU MCA SEM4 2011

July 2011

Master of Computer Application (MCA) – Semester 4

MC0078 – Java Programming

(Book ID: B0831 & B0832)

Assignment Set – 1

Q: 1. Write a program to perform the basic arithmetic operations: a) Addition b) Subtraction c) Multiplication d) Division

Use 4 different methods for the above and invoke them as necessary from the main () method.

Ans:

Public class Test{ /*Method to add two numbers */

Public void Add() { int a=10; int b=20; int c; c=a+b; System.out.println(“The sum of two numbers is:”+c) }

/* Method to subtract two numbers*/ Public void Subtract() { int a=10; int b=20; int c; c=b-a; System.out.println(“The difference of two numbers is:”+c) }

Page 2: MC0078 SMU MCA SEM4 2011

/* Method to Multiplication of two numbers*/ Public void Multiply() { int a=10; int b=20; int c; c=b*a; System.out.println(“The multiplication of two numbers is:”+c) }

/* Method to divide two numbers*/ Public void Division() { int a=10; int b=20; int c; c=b/a; System.out.println(“The reminder is:”+c) }

Public static void main(String arg[]) { Add(); Subtract(); Multiply(); Division();

}}

Q: 2. Discuss the following with suitable example programs for each:A) Data Types in JavaB) Variables in Java

Ans: A) Data Types in Java:

There are two kinds of data types in Java1· Primitives/standard data types.2· Abstract/derived data types.

1. Primitives Data Types

Primitive data types (also know as standard data types) are the data types that are built into the Java language. The Java compiler holds details instructions on each operation the data types that are built into the Java language. The Java compiler holds detailed instructions on each legal operation the data type supports. There are eight primitive data types in Java.

Page 3: MC0078 SMU MCA SEM4 2011

The data types – byte, short, int, long, float and double are numeric data types. The first four of these can hold only whole numbers whereas the last two (float and double) can hold decimal values like 5.05. All these data types can hold negative values. However, the keyword unsigned can be used to restrict the range of values to positive numbers. Amongst others, boolean can hold only the value true or false and char can hold only a single character.

2. Abstract/Derived Data Types

Abstract data types are based on primitives data types and have more functionality that the primitive data types. For example, String is an abstract data type that can store alphabets, digits and other characters like /, (); :$#. You cannot perform calculations on a variable of the string data type even if the data stored in it has digits.

B) Variables in Java:

When you learned algebraic equations in school, you used x and y to represent values in equations. Unlike pi which has a constant value of 3.14, the values of x and y are not constant in equations. Java provides constants and variables to store data in programs.

Java allocates memory to each variable and constant you use in your program. As in algebra, the values of variables may change in a program, but the values of constants, as the name suggests, do not change. You must assign unique names to variables and constants. Variable names are used in a program in much the same way as they are in ordinary Algebra.

Each variable used in a program must be declared. That is to say, the program must contain a statement specifying precisely what kind of information (data type) the variable will contain. This applies to every variable used in the program, regardless of the type.

Page 4: MC0078 SMU MCA SEM4 2011

Naming Variables

A program refers to a variable using its name. Certain rules and conventions govern the naming of variables. You must adhere to rules. Conventions help improve the readability of the program, but following them is not mandatory.

Rules for Naming Variables in Java

A variable name: · Must not be a keyword in Java.· Must not begin with a digit.· Must not contain embedded spaces.· Can contain characters from various alphabets, like Japanese, Greek, and Cyrillic.

Syntax for Defining Variables

All the attributes of a class are defined as data members. The syntax used to declare a class variable is:<data_type> <variable_name>

Q:3 What are the different types of control statements?

Ans:

Following statements are used to control the flow of execution in a program.1. Decision Making Statements· If-else statement· Switch – case statement2. Looping Statement· For loop· While loop· Do-while loop3. Other statement· Break· Continue· Label

If-else statement

The if statement is Java’s conditional branch statement. It can be used to route program execution through two different paths. Here is the general form of the if statement:if (condition) statement1;else statement2;Here, each statement may be a single statement or a compound statement enclosed in curly braces (that is, a block). The condition is any expression that returns a boolean value. The else clause is optional.

Page 5: MC0078 SMU MCA SEM4 2011

Switch Statement

The switch statement is Java’s multi way branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression.As such, it often provides a better alternative than a large series of if-else-if statements.Here is the general form of a switch statement:switch (expression) {case value1:// statement sequencebreak;case value2:// statement sequencebreak;

.

.

.

case valueN:

// statement sequencebreak;default:// default statement sequence}The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a type compatible with the expression. Each case value must be a unique literal (that is, it must be a constant, not a variable). Duplicate case values are not allowed.The switch statement works like this: The value of the expression is compared with each of the literal values in the case statements. If a match is found, the code sequence following that case statement is executed. If none of the constants matches the value of the expression, then the default statement is executed. However, the default statement is optional. If no case matches and no default is present, then no further action is taken.The break statement is used inside the switch to terminate a statement sequence. When a break statement is encountered, execution branches to the first line of code that follows the entire switch statement. This has the effect of "jumping out" of the switch.

‘for’ Loop

The usage of for loop is as followsfor (initial statement; termination condition; increment instruction)statement;When multiple statements are to be included in the for loop, the statements are included inside flower braces. for (initial statement; termination condition; increment instruction)

Page 6: MC0078 SMU MCA SEM4 2011

{

statement1;

statement2;

}

While Statement

The while loop is Java’s most fundamental looping statement. It repeats a statement or block while its controlling expression is true. Here is its general form:while (condition) {// body of loop

}

The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true. When condition becomes false, control passes to the next line of code immediately following the loop. The curly braces are unnecessary if only a single statement is being repeated.

‘do….while’ statement

As you just saw, if the conditional expression controlling a while loop is initially false, then the body of the loop will not be executed at all. However, sometimes it is desirable to execute the body of a while loop at least once, even if the conditional expression is false to begin with. In other words, there are times when you would like to test the termination expression at the end of the loop rather than at the beginning. Fortunately, Java supplies a loop that does just that: the do-while. The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Its general form is

do {

// body of loop

} while (condition);

Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java’s loops, condition must be a boolean expression.

‘Break’ statement

By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop.

Page 7: MC0078 SMU MCA SEM4 2011

‘Continue’ Statement

Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop, but stop processing the remainder of the code in its body for this particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue statement performs such an action. In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop. In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression. For all three loops, any intermediate code is bypassed.

4. Describe the following with respect to Exception Handling:A) Exception Classes B) Common Exceptions

Ans:

A) Exception Classes

The class at the top of the exception classes hierarchy is called Throwable. Two classes are derived from the Throwable class- Error and Exception. The Exception class is used fro the exceptional conditions that have to be trapped in a program. The Error class defines a condition that does not occur under normal circumstances. In other words, the Error class is used for catastrophic failures such as VirtualMachineError. These classes are available in the java.lang package.

B) Common Exceptions

Java has several predefined exceptions. The most common exceptions that you may encounter are described below.

· Arithmetic Exception

This exception is thrown when an exceptional arithmetic condition has occurred. For example, a division by zero generates such an exception.

· NullPointer Exception

This exception is thrown when an application attempts to use null where an object is required. An object that has not been allocated memory holds a null value. The situations in which an exception is thrown include:

- Using an object without allocating memory for it.- Calling the methods of a null object.- Accessing or modifying the attributes of a null object.

· ArrayIndexOutOfBounds Exception

The exception ArrayIndexOutOfBounds Exception is thrown when an attempt is made to access an array element beyond the index of the array. For example, if you try to access the eleventh element of an array that’s has only ten elements, the exception will be thrown.

Page 8: MC0078 SMU MCA SEM4 2011

5.What is the difference between bound property and constraint property?

Ans:

Bound Properties

Bound properties support the PropertyChangeListener (in the API reference documentation) class. Sometimes when a Bean property changes, another object might need to be notified of the change, and react to the change. Whenever a bound property changes, notification of the change is sent to interested listeners. The accessor methods for a bound property are defined in the same way as those for simple properties. However, you also need to provide the event listener registration methods forPropertyChangeListener classes and fire a PropertyChangeEvent (in the API reference documentation) event to the PropertyChangeListener objects by calling their propertyChange methods The convenience PropertyChangeSupport (in the API reference documentation) class enables your bean to implement these methods. Your bean can inherit changes from the PropertyChangeSupportclass, or use it as an inner class. In order to listen for property changes, an object must be able to add and remove itself from the listener list on the bean containing the bound property. It must also be able to respond to the event notification method that signals a property change. The PropertyChangeEvent class encapsulates property change information, and is sent from the property change event source to each object in the pro.

Constrained Properties

A bean property is constrained if the bean supports the Vetoable ChangeListener(in the API reference documentation) and Property ChangeEvent(in the API reference documentation) classes, and if the set method for this property throws a PropertyVetoException(in the API reference documentation). Constrained properties are more complicated than bound properties because they also support property change listeners which happen to be vetoers. The following operations in the setXXX method for the constrained property must be implemented in this order: 1. Save the old value in case the change is vetoed. 2. Notify listeners of the new proposed value, allowing them to veto the change. 3. If no listener vetoes the change (no exception is thrown), set the property to the new value. The accessor methods for a constrained property are defined in the same way as those for simple properties, with the addition that the setXXX method throws a PropertyVetoException exception. The syntax is as follows:                     public void setPropertyName(PropertyType pt)                    throws PropertyVetoException {code}

Page 9: MC0078 SMU MCA SEM4 2011

6. Define RMI. Define the architecture of RMI invocation. Ans:

RMI:RMI applications often comprise two separate programs, a server and a client. A typical server program creates some remote objects, makes references to these objects accessible, and waits for clients to invoke methods on these objects. A typical client program obtains a remote reference to one or more remote objects on a server and then invokes methods on them. RMI provides the mechanism by which the server and the client communicate and pass information back and forth. Such an application is sometimes referred to as a distributed object application.

Architecture of RMI:

Locate remote objects: Applications can use various mechanisms to obtain references to remote objects. For example, an application can register its remote objects with RMI’s simple naming facility, the RMI registry. Alternatively, an application can pass and return remote object references as part of other remote invocations.

Communicate with remote objects: Details of communication between remote objects are handled by RMI. To the programmer, remote communication looks similar to regular Java method invocations.

Load class definitions for objects that are passed around: Because RMI enables objects to be passed back and forth, it provides mechanisms for loading an object’s class definitions as well as for transmitting an object’s data.

The following illustration depicts an RMI distributed application that uses the RMI registry to obtain a reference to a remote object. The server calls the registry to associate (or bind) a name with a remote object. The client looks up the remote object by its name in the server’s registry and then invokes a method on it. The illustration also shows that the RMI system uses an existing web server to load class definitions, from server to client and from client to server, for objects when needed.

Page 10: MC0078 SMU MCA SEM4 2011

7. Define the following terms:A) Socket B) Port C) DatagramDescribe the steps in reading and writing data from sockets.

Ans:A)Socket:A network socket is a lot like an electrical socket.

A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.

An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its two endpoints. That way you can have multiple connections between your host and the server.

The java.net package in the Java platform provides a class, Socket, that implements one side of a two-way connection between your Java program and another program on the network. The Socket class sits on top of a platform-dependent implementation, hiding the details of any particular system from your Java program. By using the java.net.Socket class instead of relying on native code, your Java programs can communicate over the network in a platform-independent fashion.

Additionally, java.net includes the ServerSocket class, which implements a socket that servers can use to listen for and accept connections to clients. This lesson shows you how to use the Socket and ServerSocket classes.

If you are trying to connect to the Web, the URL class and related classes (URLConnection, URLEncoder) are probably more appropriate than the socket classes.

C) Port:

Generally speaking, a computer has a single physical connection to the network. All data destined for a particular computer arrives through that connection. However, the data may be intended for different applications running on the computer. So how does the computer know to which application to forward the data? Through the use of ports.

Data transmitted over the Internet is accompanied by addressing information that identifies the computer and the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the right application.

In connection-based communication such as TCP, a server application binds a socket to a specific port number. This has the effect of registering the server with the system to receive all data destined for that port. A client can then rendezvous with the server at the server’s port, as illustrated here:

Page 11: MC0078 SMU MCA SEM4 2011

The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer.

In datagram-based communication such as UDP, the datagram packet contains the port number of its destination and UDP routes the packet to the appropriate application, as illustrated in this figure:

Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers ranging from 0 – 1023 are restricted; they are reserved for use by well-known services such as HTTP and FTP and other system services. These ports are called well-known ports. Your applications should not attempt to bind to them.

D) Datagram:

Clients and servers that communicate via a reliable channel, such as a TCP socket, have a dedicated point-to-point channel between themselves, or at least the illusion of one. To communicate, they establish a connection, transmit the data, and then close the connection. All data sent over the channel is received in the same order in which it was sent. This is guaranteed by the channel.

In contrast, applications that communicate via datagrams send and receive completely independent packets of information. These clients and servers do not have and do not need a dedicated point-to-point channel. The delivery of datagrams to their destinations is not guaranteed. Nor is the order of their arrival.

A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed.

Page 12: MC0078 SMU MCA SEM4 2011

The java.net package contains three classes to help you write Java programs that use datagrams to send and receive packets over the network: DatagramSocket. DatagramPacket, and MulticastSocket An application can send and receive DatagramPackets through a DatagramSocket. In addition, DatagramPackets can be broadcast to multiple recipients all listening to a MulticastSocket.

8. What is the advantage of CORBA over EJB?

Ans: CORBA stands for Common Object Request Broker Architecture. CORBA is a distributed computing technology where the participating objects need not only be written in Java. Java IDL is a technology for distributed objects-that is, objects interacting on different platforms across a network. Java IDL is similar to RMI (Remote Method Invocation), which supports distributed objects written entirely in the Java programming language. However, Java IDL enables objects to interact regardless of whether they’re written in the Java programming language or another language such as C, C++, COBOL, or others.Java IDL is based on the Common Object Request Brokerage Architecture (CORBA), an industry-standard distributed object model. CORBA products provide a framework for the development and execution of distributed applications. CORBA defines an architecture for distributed objects. The basic CORBA paradigm is that of a request for services of a distributed object. Everything else defined by the OMG is in terms of this basic paradigm.

The services that an object provides are given by its interface. Interfaces are defined in OMG’s Interface Definition Language (IDL). Distributed objects are identified by object references, which are typed by IDL interfaces.

CORBA is a networking protocol for building distributed applications. It will provide you with a lookup service, and a nice abstraction for sending objects across a network connection, but that's it.

EJB is a application server designed to take over significant portions of your code, including thread management, transactions, caching, and database mapping. It so happens that EJB is also designed to be distributed, and therefor is built using CORBA to lookup the services available from the application server.

There is a CORBA specifiction for a application server called CCM (CORBA Component Model) that is a mirror image of the EJB spec (it, in fact, demands that any Java implementation of the CCM spec. have full EJB support) but this specification doesn't appear to be well-supported yet.

Page 13: MC0078 SMU MCA SEM4 2011

July 2011

Master of Computer Application (MCA) – Semester 4

MC0078 – Java Programming

(Book ID: B0831 & B0832)

Assignment Set – 2

Q: 1. Write a complete program for each of the following: Decision Making Statements Looping Statements

Ans:

Decision Making Statements:· If-else statement· Switch – case statement

If-else statement

The if statement is Java’s conditional branch statement. It can be used to route program execution through two different paths. Here is the general form of the if statement:if (condition) statement1;else statement2;Here, each statement may be a single statement or a compound statement enclosed in curly braces (that is, a block). The condition is any expression that returns a boolean value. The else clause is optional.The if works like this: If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is executed. In no case will both statements be executed. For example, consider the following:

Page 14: MC0078 SMU MCA SEM4 2011

Switch Statement

The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression.As such, it often provides a better alternative than a large series of if-else-if statements.Here is the general form of a switch statement:switch (expression) {case value1:// statement sequencebreak;case value2:// statement sequencebreak;default:// default statement sequence}

Example

Looping Statement

· For loop· While loop· Do-while loop

Page 15: MC0078 SMU MCA SEM4 2011

‘for’ Loop

The usage of for loop is as followsfor (initial statement; termination condition; increment instruction)statement;When multiple statements are to be included in the for loop, the statements are included inside flower braces. for (initial statement; termination condition; increment instruction){statement1;statement2;}The example below prints numbers from 1 to 10

While Statement

The while loop is Java’s most fundamental looping statement. It repeats a statement or block while its controlling expression is true. Here is its general form:while (condition) {// body of loop}The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true. When condition becomes false, control passes to the next line of code immediately following the loop. The curly braces are unnecessary if only a single statement is being repeated.

Example

Page 16: MC0078 SMU MCA SEM4 2011

‘do….while’ statement

As you just saw, if the conditional expression controlling a while loop is initially false, then the body of the loop will not be executed at all. However, sometimes it is desirable to execute the body of a while loop at least once, even if the conditional expression is false to begin with. In other words, there are times when you would like to test the termination expression at the end of the loop rather than at the beginning. Fortunately, Java supplies a loop that does just that: the do-while. The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Its general form is

do {

// body of loop

} while (condition);

Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java’s loops, condition must be a boolean expression.

Example

Page 17: MC0078 SMU MCA SEM4 2011

Q: 2. How do you implements inheritance in java?

Ans:

Inheritance

Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. In the terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the superclass and add its own, unique elements.The philosophy behind inheritance is to portray things as they exist in the real world. For instance, a child inherits properties from both the parents. Inheritance means that a class derives a set of attributes and related behaviors from another class.Inheritance helps you to:· Reduce redundancy in code. Code redundancy means writing the same code in different places, leading to unnecessary replication of code. Inheritance helps you to reuse code.· Maintain code easily, as the code resides at one place (superclass). Any changes made to the superclass automatically change the behavior automatically.· Extend the functionality of an existing class by adding more methods to the subclass.

Implementing Inheritance in Java

The extends keyword is used to derive a class from a superclass, or in other words, extend the functionality of a superclass.

Syntax

public class <subclass_name>extends<superclass_name>

Page 18: MC0078 SMU MCA SEM4 2011

Example

public class confirmed extends ticket{}// Create a superclass.class A {int i, j;void showij() {System.out.println("i and j: " + i + " " + j);}}// Create a subclass by extending class A.class B extends A {int k;void showk() {System.out.println("k: " + k);}void sum() {System.out.println("i+j+k: " + (i+j+k));}}class SimpleInheritance {public static void main(String args[]) {A superOb = new A();B subOb = new B();// The superclass may be used by itself.superOb.i = 10;superOb.j = 20;System.out.println("Contents of superOb: ");superOb.showij();System.out.println();/* The subclass has access to all public members ofits superclass. */subOb.i = 7;subOb.j = 8;subOb.k = 9;System.out.println("Contents of subOb: ");subOb.showij();subOb.showk();System.out.println();System.out.println("Sum of i, j and k in subOb:");subOb.sum();}}The output from this program is shown here:Contents of superOb:i and j: 10 20Contents of subOb:i and j: 7 8k: 9

Page 19: MC0078 SMU MCA SEM4 2011

Sum of i, j and k in subOb:i+j+k: 24

Q:3 Draw and explain the JDBC Application Architecture?

Ans:

The JDBC API can access any kind of tabular data, especially data stored in a Relational Database. It works on top of ODBC which was the driver for database connectivity. Since JDBC works on top of ODBC we have something called as a JDBC-ODBC bridge to access the database.

ODBC

ODBC is an abbreviation of Open Database Connectivity, a standard database access method developed by Microsoft Corporation. The goal of ODBC is to make it possible to access any data from any application, regardless of which database management system (DBMS) is handling the data. ODBC manages this by inserted a middle layer, called a driver, between an application and the DBMS. The purpose of this layer is to translate the queries of the application into commands that the DBMS understands. For this to work, both the application and the DBMS must be ODBC-compliant-that is, the application must be capable of issuing ODBC commands and the DBMS must be capable of responding to them.

JDBC

JDBC provides a database-programming interface for Java programs. Since the ODBC is written in ‘C’ language, a Java program cannot directly communicate with an ODBC driver.

JavaSoft created the JDBC-ODBC Bridge driver that translates the JDBC API to the ODBC API. It is used with ODBC drivers.

JDBC Driver Manager

The JDBC driver manager is the backbone of the JDBC architecture. The function of the JDBC driver manager is to connect a Java application to the appropriate driver.

JDBC-ODBC Bridge

The JDBC-ODBC bridge allows you to use the ODBC driver as JDBC drivers.

JDBC Application Architecture

Page 20: MC0078 SMU MCA SEM4 2011

Connection to a Database

The java.sql package contains classes that help in connecting to a database, sending SQL statements to the database, and processing query results.

The Connection Objects

The Connection object represents a connection with a database. You may have several Connection objects in an application that connects to one or more databases.

Loading the JDBC-ODBC Bridge and Establishing Connection

To establish a connection with a database, you need to register the ODBC-JDBC Driver by calling the forName () method from the Class class and then calling the getConnection () method from the DriverManager class.The getConnection () method of the DrverManager class attempts to locate the driver that can connect to the database represented by the JDBC URL passed to the getConnection () method.

The JDBC URL

The JDBC URL is a string that provides a way of identifying a database. A JDBC URL is divided into three parts:<protocol>:<subprotocol>:<subname>· <protocol> in a JDBC URL is always jdbc.· <subprotocol> is the name of the database connectivity mechanism. If the mechanism of retrieving the data is ODBC-JDBC Bridge, the subprotocol must be odbc.· <subname> is used to identify the database.

Example: JDBC URL

String url = “jdbc:odbc:MyDataSource”;Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver “);Connection con = DriverManager.getConnection (url);

Using the Statement Object

You can use the statement object to send simple queries to the database as shown in the sample QueryApp program.

Page 21: MC0078 SMU MCA SEM4 2011

Q:4 What are the difference between an interface and an abstract class?

Ans:

1. Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.

2. Variables declared in a Java interface is by default final. An  abstract class may contain non-final variables.

3. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..

4. Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.

5. An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.

6. A Java class can implement multiple interfaces but it can extend only one abstract class.7. Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be

instantiated, but can be invoked if a main() exists.8. In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.

5.Explain the working of struts with an example?

Ans: Struts is based on the time-proven Model-View-Controller (MVC) design pattern. The MVC pattern is widely recognized as being among the most well-developed and mature design patterns in use. By using the MVC design pattern, processing is broken into three distinct sections aptly named the Model, the View, and the Controller. These are described in the following subsections:

Model Components

Model components provide a "model" of the business logic or data behind a Struts program. For example, in a Struts application that manages customer information, it may be appropriate to have a "Customer" Model component that provides program access to information about customers.

It’s very common for Model components to provide interfaces to databases or back-end systems. For example, if a Struts application needs to access employee information that is kept in an enterprise HR information system, it might be appropriate to design an "Employee" Model component that acts as an interface between the Struts application and the HR information system.

Page 22: MC0078 SMU MCA SEM4 2011

Model components are generally standard Java classes. There is no specifically required format for a Model component, so it may be possible to reuse Java code written for other projects.

View Components

View components are those pieces of an application that present information to users and accept input. In Struts applications, these correspond to Web pages.

View components are used to display the information provided by Model components. For example, the "Customer" Model component discussed above would need a View component to display its information. Usually, there will one or more View components for each Web page in a Struts application.

View components are generally built using JavaServer Page (JSP) files. Struts provides a large number of "JSP Custom Tags" (sometimes referred to as Struts Tags) which extend the normal capabilities of JSP and simplify the development of View components.

Controller Components

Controller components coordinate activities in the application. This may mean taking data from the user and updating a database through a Model component, or it may mean detecting an error condition with a back-end system and directing the user through special error processing. Controller components accept data from the users, decide which Model components need to be updated, and then decide which View component needs to be called to display the results.

One of the major contributions of Controller components is that they allow the developer to remove much of the error handling logic from the JSP pages in their application. (After all, if errors in processing occur, the Controller component forwards to an error-processing View component, not the primary results View component.) This can significantly simplify the logic in the pages and make them easier to develop and maintain.

Controller components in Struts are Java classes and must be built using specific rules. They are usually referred to as "Action classes."

Example:

Login Application Using Action Form

In this example we will see how to create a login application using ActionForm. The following files are required for the login application.

login.jsp success.jsp failure.jsp web.xml struts-config.xml LoginAction.java

Page 23: MC0078 SMU MCA SEM4 2011

LoginForm.java ApplicationResource.properties

web.xml

The first page that will be called in the login application is the login.jsp page. This configuration should be done in web.xml as shown below.1.<welcome-file-list>2.<welcome-file>login.jsp</welcome-file>3.</welcome-file-list>login.jsp

We use Struts HTML Tags to create login page. The form has one text field to get the user name and one password field to get the password. The form also has one submit button, which when clicked calls the login action. <html:errors /> tag is used to display the error messages to the user.01.<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>02.<html>03.<head>04.<title>Login Page</title>05.</head>06.<body>07.<div style="color:red">08.<html:errors />09.</div>10.<html:form action="/Login" >11.User Name :<html:text name="LoginForm" property="userName" />12.Password :<html:password name="LoginForm" property="password" />13.<html:submit value="Login" />14.</html:form>15.</body>16.</html>

The user enters the user name and password and clicks the login button. The login action is invoked.struts-config.xml

The validate method in the LoginForm class is called when the Form is submitted. If any errors are found then the control is returned back to the input page where the errors are displayed to the user. The input page is configured in the action tag of strut-config file. <html:errors /> tag is used to display the errors in the jsp page.01.<struts-config>02.<form-beans>03.<form-bean name="LoginForm" type="com.vaannila.LoginForm"/>04.</form-beans>05. 06.<action-mappings>07.<action input="/login.jsp" name="LoginForm" path="/Login" scope="session" type="com.vaannila.LoginAction">08.<forward name="success" path="/success.jsp" />09.<forward name="failure" path="/failure.jsp" />10.</action>11.</action-mappings>

Page 24: MC0078 SMU MCA SEM4 2011

12.</struts-config>

Here the action is "/Login" , the input page is "login.jsp" and the corresponding action class is LoginAction.java. Now the validate method in the LoginForm class will be invoked.LoginForm.java

Inside the validate method, we check whether the user name and password is entered. If not the corresponding error message is displayed to the user. The error messages are configured in the ApplicationResource.properties file.01.public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {02.ActionErrors errors = new ActionErrors();03.if (userName == null || userName.length() < 1) {04.errors.add("userName", new ActionMessage("error.userName.required"));05.}06.if (password == null || password.length() < 1) {07.errors.add("password", new ActionMessage("error.password.required"));08.}09.return errors;10.}ApplicationResource.properties

The ApplicationResource.properties file contains the error messages. The key "error.userName.required" is used in the validate function to add a new error. Since the error messages are configured in a seperate properties file they can be changed anytime without making any changes to the java files or the jsp pages.1.error.userName.required = User Name is required.2.error.password.required = Password is required.

If either user name or password is not entered then the corresponding error message will be added to the ActionErrors. If any errors are found then the control is returned back to the input jsp page, where the error messages are displayed using the <html:errors /> tag. The validate method is used to perform the client-side validations. Once when the input data is valid the execute method in the LoginAction class is called.LoginAction.java

The execute method contains the business logic of the application. Here first we typecast the ActionForm object to LoginForm, so that we can access the form variables using the getter and setter methods. If the user name and password is same then we forward the user to the success page else we forward to the failure page.01.public class LoginAction extends org.apache.struts.action.Action {02. 03.private final static String SUCCESS = "success";04.private final static String FAILURE = "failure";05. 06.public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {07.LoginForm loginForm = (LoginForm) form;08.if (loginForm.getUserName().equals(loginForm.getPassword())) {09.return mapping.findForward(SUCCESS);10.} else {11.return mapping.findForward(FAILURE);12.}

Page 25: MC0078 SMU MCA SEM4 2011

13.}14.}

Lets enter the user names and password as "Eswar". Since the user name and password is same the execute method will return an ActionForward "success". The corresponding result associated with the name "success" will be shown to the user. This configuration is done in struts-config.xml file.1.<action-mappings>2.<action input="/login.jsp" name="LoginForm" path="/Login" scope="session" type="com.vaannila.LoginAction">3.<forward name="success" path="/success.jsp" />4.<forward name="failure" path="/failure.jsp" />5.</action>6.</action-mappings>

6. Write a program in Java to demonstrate the complete life cycle of a Servlet.Ans:

Every servlet have their own life cycle in which they perform their task. Every servlet calls init(), service(), and destroy() method in their life cycle.import java.io.IOException;import java.io.PrintWriter;

import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

public class ServletLifeCycleExample extends HttpServlet {\// Servlet init() method

public void init() {System.out.println("\n\n Servlet Init() Method");System.out.println("Servlet Initialised by init() method");

}

public void init(ServletConfig config) {try {

super.init(config);System.out.println("\n\nServlet init(config)method\n");System.out.println("Servlet Initialised by init(context) method");

} catch (ServletException e) {// TODO Auto-generated catch blocke.printStackTrace();

Page 26: MC0078 SMU MCA SEM4 2011

}}

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

PrintWriter out = response.getWriter();response.setContentType("text/html");out.println("Servlet Life Cycle Example");System.out.println("Inside doGet() method");

}

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

doGet(request, response);}

public void destroy() {System.out.println("\n\nServlet destroyed \n");System.out.println("Servlet Finalising by destroy() method");

}}

7. Explain the life cycle of a Servlet?

Ans:

Servlet Life Cycle

Now that you have seen the basic structure of a servlet, let’s review the process by which a server invokes a servlet. This process can be broken down into the nine steps as follows:1. The server loads the servlet when it is first requested by the client or if configured to do so, at server start-up. The servlet may be loaded from either a local or a remote location using the standard Java class loading facility.This step is equivalent to the following code:

Class c=Class.forName(“com.sourcestream.MyServlet”);

It should be noted that when referring to servlets, the term load often refers to the process of both loading and instantiating the servlet.2. The server creates one or more instances of the servlet class. Depending on implementation. The server may create a single instance that services all requests through multiple threads or create a pool of instances from which one chosen to service each new request. This step is equivalent to the following Java code:Servlet s=(Servlet) c.newInstance (); where ‘c’ is the same Class object created in previous step.

Page 27: MC0078 SMU MCA SEM4 2011

3. The server constructs a ServerConfig object that provides initialization information to the servlet.4. The server calls the servlet’s init () method, passing the object constructed in step 3 as a parameter. The init () method is guaranteed to finish execution prior to the servlet processing the first request. If the server has created multiple servlet instances (step 2), the init () method is called one time for each instance.5. The server constructs a ServletRequest or HttpServletRequest object from the data included in the client’s request. It also constructs a ServletResponse or HttpServletResponse object that provides methods for customizing the server’s response. The type of object passed in these two parameters depends on whether the servlet extends the GenericServlet class or the HttpServlet class, respectively.6. The server calls the servlet’s service() method passing the objects constructed in step 5 as parameters. When concurrent requests arrive, multiple service() methods can run in separate threads.7. The service () method processes the client request by evaluating the ServletRequest or HttpServletRequest object and responds using ServletResponse or HttpServletResponse object.8. If the server receives another request for this servlet, the process begins again at step 5.9. When instructed to unload the servlet, perhaps by the server administrator or programmatically by the servlet itself, the server calls the servlet’s destroy() method. The servlet is then eligible for garbage collection.The above mentioned nine steps illustrate the entire lifecycle of a servlet. The following figure shows the flow of the servlet lifecycle.

Page 29: MC0078 SMU MCA SEM4 2011

8. Explain the importance, applications and working of Java Struts.

Ans:

Struts is an application development framework that is designed for and used with the popular J2EE (Java 2, Enterprise Edition) platform. It cuts time out of the development process and makes developers more productive by providing them a series of tools and components to build applications with. It is non-proprietary and works with virtually any J2EE-compliant application server. Struts falls under the Jakarta subproject of the Apache Software Foundation and comes with an Open Source license (meaning it has no cost and its users have free access to all its internal source code).

In addition to helping you work faster and having no cost, Struts also helps make your end work products better. The main reason for this, to quote from Eric Raymond’s "The Cathedral and the Bazaar" (a classic book on open source development), is that "(g)iven a large enough beta-tester and co-developer base, almost every problem will be characterized quickly and the fix obvious to someone." In other words, so many people are using and developing Struts that bugs are found and get fixed quickly.

"Struts is a Web Application ‘Framework’?"

The dictionary calls a framework "A structure for supporting or enclosing something else, especially a skeletal support used as the basis for something being constructed." This perfectly describes Struts–a collection of Java code designed to help you build solid applications while saving time. It provides the basic skeleton and plumbing; you focus on the layout and look of each room.

Interestingly, the dictionary offers an alternative definition of a framework: "A set of assumptions, concepts, values, and practices that constitutes a way of viewing reality." This describes Struts as well–it’s a way of looking at things. Struts saves you time by allowing you to view complex applications as a series of basic components: Views, Action Classes, and Model components.

"… And Frameworks Are Important Because?"

Using a framework means that you don’t have to spend time building your entire application. You can focus on coding the business logic and the presentation layer of the application–not the overhead pieces like figuring out how to capture user input or figuring out how to generate drop-down boxes on a Web page.

Using a framework also helps you encode best practices. The framework developers have put a lot of thought into the best approaches to application building – why reinvent this yourself?

Another benefit of using a framework is that it allows your code (at least in the case of Struts) to be highly platform independent. For example, the same Struts code should work under Tomcat on an old Windows machine as runs using Weblogic on Linux or Solaris in production. And this can be accomplished without even recompiling in many cases–the same Web application (or ". war" file) can simply be copied from one server to another.

Another extremely important benefit–especially if you’re relatively new to Web development–is that it gives you a place to start. Any developer will tell you it’s easier to take a basic application and modify it than it is to build something from scratch. This feature of Struts can save you days or weeks of planning and development.

Page 30: MC0078 SMU MCA SEM4 2011

How Does Struts Work

Struts is based on the time-proven Model-View-Controller (MVC) design pattern. The MVC pattern is widely recognized as being among the most well-developed and mature design patterns in use. By using the MVC design pattern, processing is broken into three distinct sections aptly named the Model, the View, and the Controller. These are described in the following subsections:

Model Components

Model components provide a "model" of the business logic or data behind a Struts program. For example, in a Struts application that manages customer information, it may be appropriate to have a "Customer" Model component that provides program access to information about customers.

It’s very common for Model components to provide interfaces to databases or back-end systems. For example, if a Struts application needs to access employee information that is kept in an enterprise HR information system, it might be appropriate to design an "Employee" Model component that acts as an interface between the Struts application and the HR information system.

Model components are generally standard Java classes. There is no specifically required format for a Model component, so it may be possible to reuse Java code written for other projects.

View Components

View components are those pieces of an application that present information to users and accept input. In Struts applications, these correspond to Web pages.

View components are used to display the information provided by Model components. For example, the "Customer" Model component discussed above would need a View component to display its information. Usually, there will one or more View components for each Web page in a Struts application.

View components are generally built using JavaServer Page (JSP) files. Struts provides a large number of "JSP Custom Tags" (sometimes referred to as Struts Tags) which extend the normal capabilities of JSP and simplify the development of View components.

Controller Components

Controller components coordinate activities in the application. This may mean taking data from the user and updating a database through a Model component, or it may mean detecting an error condition with a back-end system and directing the user through special error processing. Controller components accept data from the users, decide which Model components need to be updated, and then decide which View component needs to be called to display the results.

One of the major contributions of Controller components is that they allow the developer to remove much of the error handling logic from the JSP pages in their application. (After all, if errors in processing occur, the Controller component forwards to an error-processing View component, not the primary results View component.) This can significantly simplify the logic in the pages and make them easier to develop and maintain.

Page 31: MC0078 SMU MCA SEM4 2011

Controller components in Struts are Java classes and must be built using specific rules. They are usually referred to as "Action classes."