You are on page 1of 55

XML

1.What is XML? Extensible Markup Language (XML) is the universal language for data on the Web XML is a technology which allows us to create our own markup language. XML documents are universally accepted as a standard way of representing information in platform and language independent manner. XML is universal standard for information interchange. XML documents can be created in any language and can be used in any language.

2.What is the difference between XML and HTML? XML is no way clashes with HTML, since they are for two different purposes.

HTML HTML is for displaying purpose. HTML is used to mark up text so it can be displayed to users. HTML describes both structure (e.g. <p>, <h2>, <em>) and appearance (e.g. <br>, <font>, <i>) HTML uses a fixed, unchangeable set of tags

XML whereas XML is for data representation. XML is used to mark up data so it can be processed by computers. XML describes only content, or meaning

In XML, you make up your own tags

3.What are the benefits of XML? There are many benefits of using XML on the Web : Simplicity- Information coded in XML is easy to read and understand, plus it can be processed easily by computers. Openness- XML is a W3C standard, endorsed by software industry market leaders. Extensibility - There is no fixed set of tags. New tags can be created as they are needed. Self-description- In traditional databases, data records require schemas set up by the database administrator. XML documents can be stored without such definitions, because they contain meta data in the form of tags and attributes. Contains machine-readable context information- Tags, attributes and element structure provide context information that can be used to interpret the meaning of content, opening up new possibilities for highly efficient search engines, intelligent data mining, agents, etc. Separates content from presentation- XML tags describe meaning not presentation. The motto of HTML is: "I know how it looks", whereas the motto of XML is: "I know what it means, and you tell me how it should look." The look and feel of an XML document can be controlled by XSL style sheets, allowing the look of a document to be changed without touching the content of the document. Multiple views or presentations of the same content are easily rendered.

Supports multilingual documents and Unicode -This is important for the internationalization of applications. Facilitates the comparison and aggregation of data - The tree structure of XML documents allows documents to be compared and aggregated efficiently element by element. Can embed multiple data types - XML documents can contain any possible data type - from multimedia data (image, sound, video) to active components (Java applets, ActiveX). Can embed existing data - Mapping existing data structures like file systems or relational databases to XML is simple. XML supports multiple data formats and can cover all existing data structures and . Provides a 'one-server view' for distributed data - XML documents can consist of nested elements that are distributed over multiple remote servers. XML is currently the most sophisticated format for distributed data - the World Wide Web can be seen as one huge XML database.

4.What is a well-formed XML document? If a document is syntactically correct it can be called as well-formed XML documents. A well-formed document conforms to XML's basic rules of syntax: Every open tag must be closed. The open tag must exactly match the closing tag: XML is case-sensitive. All elements must be embedded within a single root element. Child tags must be closed before parent tags. A well-formed document has correct XML tag syntax, but the elements might be invalid for the specified document type.

5.What is a valid XML document? If a document is structurally correct then it can be called as valid XML documents. A valid document conforms to the predefined rules of a specific type of document: These rules can be written by the author of the XML document or by someone else. The rules determine the type of data that each part of a document can contain. Note:Valid XML document is implicitly well-formed, but well-formed may not be valid 6.What is the structure of XML document ?

Figure 1: XML Structure


7.What is a Processing Instruction in XML? A ProcessingIntruction is the information which we would like to give to application. Through a ProcessingInstruction an application would get idea about how to process the document. A ProcessingInstruction can appear anywhere and any no. of times in a document. 8.How does the XML structure is defined? XML document will have a structure which has to be defined before we can create the documents and work with them. The structural rules can be defined using many available technologies, but the following are popular way of doing soDocument Type Definition (DTD) Schema

9.What is DTD? A Document Type Definition (DTD) defines the legal building blocks of an XML document. It defines rules for a specific type of document, including: Names of elements, and how and where they can be used The order of elements Proper nesting and containment of elements Element attributes To apply a DTD to an XML document, you can: Include the DTD's element definitions within the XML document itself. Provide the DTD as a separate file, whose name you reference in the XML document.

10.What is XML Schema?

An XML Schema describes the structure of an XML instance document by defining what each element must or may contain.XML Schema is expressed in the form of a separate XML file. XML Schema provides much more control on element and attribute datatypes. Some datatypes are predefined and new ones can be created.
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema "> name="test"> <xsd:element

<xsd:complexType >

Figure 2: XML Schema


11.What are differences between DTDs and Schema? Schema Schema document is an XML document i.e., the structure of an XML document is specified by another XML document. Schema supports variety of dataTypes similar to programming language. In Schema, It is possible to inherit and create relationship among elements. DTD DTDs follow SGML syntax.

In DTD everything is treated as text. This is not possible in DTD without invalidating existing documents.

In Schema, It is possible to group elements Grouping of elements and attributes is not and attributes so that they can be treated possible in DTD.

as single logical unit. In Schemas, it is possible to specify an upper limit for the number of occurrences of an element It is not possible to specify an upper limit of an element in DTDs

12.What is a Complex Element? A complex element is an XML element that contains other elements and/or attributes. There are four kinds of complex elements: empty elements elements that contain only other elements elements that contain only text elements that contain both other elements and text

13.What is a Simple Element? A simple element is an XML element that can contain only text. A simple element cannot have attributes A simple element cannot contain other elements A simple element cannot be empty However, the text can be of many different types, and may have various restrictions applied to it

14.What are namespaces? Why are they important? A simple element is an XML element that can contain only text. Namespaces are a simple and straightforward way to distinguish names used in XML documents, no matter where they come from. XML namespaces are used for providing uniquely named elements and attributes in an XML instance They allow developers to qualify uniquely the element names and relationships and make these names recognizable, to avoid name collisions on elements that have the same name but are defined in different vocabularies. They allow tags from multiple namespaces to be mixed, which is essential if data is coming from multiple sources. Example: a bookstore may define the <TITLE> tag to mean the title of a book, contained only within the <BOOK> element. A directory of people, however, might define <TITLE> to indicate a person's position, for instance: <TITLE>President</TITLE>. Namespaces help define this distinction clearly. Note: a) Every namespace has a unique name which is a string. To maintain the uniqueness among namespaces a IRL is most preferred approach, since URLs are unique. b) Except for no-namespace Schemas, every XML Schema uses at least two namespaces:

1.the target namespace. 2. The XMLSchema namespace (http://w3.org/2001/XMLSchema) 15.What are the ways to use namespaces? There are two ways to use namespaces: Declare a default namespace Associate a prefix with a namespace, then use the prefix in the XML to refer to the namespace 16.What is the relevance of ElementFormDefault attribute in the Schema? ElementFormDefault indicates whether or not locally declared elements must be qualified by the target namespace in an instance document. ElementFormDefault attribute in the Schema has the following relevance: Qualified: Each and every element of the Schema must be qualified with the namespace in the instance document. Unqualified: means only globally declared elements must be qualified with there namespace and not the local elements.
Relate d Links

17.What is XML parser? An XML parser is a piece of software which can do following: Check for well-formedness Validate the document Allows us to read, create or modify existing XML documents Note: Parser is piece of software provided by vendors. An XML parser is built in Java runtime from JDK 1.4 onwards

18.What is DOM? The Document Object Model (DOM) is a platform and language-independent standard object model for representing XML and related formats. DOM is standard API which is not specific to any programming language. DOM represents an XML document as a tree model. The tree model makes the XML document hierarchal by nature. Each and every construct of the XML document is represented as a node in the tree. 19.What is SAX? SAX-Simple API for XML processing. SAX provides a mechanism for reading data from an XML document. It is a popular alternative to the Document Object Model (DOM).SAX provides an event based processing approach unlike DOM which is tree based. 20.What are the interfaces of SAX? The interfaces of SAX are: DocumentHandler- is used for getting event notification relating to a

document. DTDHandler- is implemented to get the notifications related to declarations in DTD like entities and notations EntityResolver- is used for reading external entities. ErrorHandler- is used for handling error related notifications.

21.What is the difference between SAX parser and DOM parser? SAX A SAX parser takes the occurrences of components of an input document as events (i.e., event based processing), and tells the client what it reads as it reads through the input document. No navigation possible (top to bottom only once) We cannot modify the document content in SAX A SAX parser serves the client application always only with pieces of the document at any given time. A SAX parser, however, is much more space efficient in case of a big input document Use SAX parser when Input document is too big for available memory. When only a part of the document is to be read and we create the data structures of our own. If you use SAX, you are using much less memory and performing much less dynamic memory allocation. DOM A DOM parser creates a tree structure in memory from an input document and then waits for requests from client. Whereas, we can navigate the DOM tree in any direction, any no. of times. We can modify the document content in DOM A DOM parser always serves the client application with the entire document no matter how much is actually needed by the client. A DOM parser is space inefficient when the document is huge. Use DOM when Your application has to access various parts of the document and using your own structure is just as complicated as the DOM tree. Your application has to change the tree very frequently and data has to be stored for a significant amount of time.

22.What is a CDATA section in XML? CDATA Sections are used to escape blocks of text containing characters which would otherwise be recognized as markup. All tags and entity references are ignored by an XML processor that treats them just like any character data. CDATA blocks have been provided as a convenience measure when you want to include large blocks of special characters as character data, but you do not want to have to use entity references all the time.

23.What is XSL? eXtensible Stylesheet Language(XSL) deals with most displaying the contents of XML documents.XSL consists of three parts: XSLT - a language for transforming XML documents XPath - a language for navigating in XML documents XSL-FO - a language for formatting XML documents

24.How is XSL different from Cascading Style Sheets? Why is a new Stylesheet language needed? XSL is compatible with CSS and is designed to handle the new capabilities of XML that CSS can't handle. XSL is derived from Document Style Semantics and Specification Language (DSSSL), a complex Stylesheet language with roots in the SGML community. The syntax of XSL is quite different from CSS, which could be used to display simple XML data but isn't general enough to handle all the possibilities generated by XML. XSL adds the capability to handle these possibilities. For instance, CSS cannot add new items or generated text (for instance, to assign a purchase order number) or add a footer (such as an order confirmation). XSL allows for these capabilities. 25.What is XSLT? eXtensible Stylesheet Language Transformation (XSLT) deals with transformation of one XML document into XHTML documents or to other XML documents. XSLT uses XPath for traversing an XML document and arriving at a particular node.

Figure 3: XSLT

26.What is the role of XSL transformer? An XSL transformer will transform in the following way: The source tree is obtained by parsing in a normal XML style The transformation is now applied to the source with the help of information available in Stylesheet.

27.What is the structure of XSLT?

Figure 4: XSLT Structure


28.What is XSL template? Template specifies transformation rules. A Stylesheet document can be made up of at least one template, which acts as an entry point. Every template uniquely identifies a particular node in the source tree. 29.What is XPath? XPath is an expression language used for addressing parts of an XML document. XPath is used to navigate through elements and attributes in an XML document. 30.What is XSL-FO? XSL-FO deals with formatting XML data. This can be used for generating output in a particular format like XML to PDF, XML to DOC, etc. 31.How XSL-FO Works (or) How would you produce PDF output using XSLs?

Figure 5: XSL-FO

Previous | 1 2 | Next

JDBC

1.What is the JDBC? Java Database Connectivity (JDBC) is a standard Java API to interact with relational databases form Java. JDBC has set of classes and interfaces which can use from Java application and talk to database without learning RDBMS details and using Database Specific JDBC Drivers. 2.What are the new features added to JDBC 4.0? The major features added in JDBC 4.0 include :

Auto-loading of JDBC driver class Connection management enhancements Support for RowId SQL type DataSet implementation of SQL using Annotations SQL exception handling enhancements SQL XML support

Learn more about JDBC 4.0 features

3.Explain Basic Steps in writing a Java program using JDBC? JDBC makes the interaction with RDBMS simple and intuitive. When a Java application needs to access database : Load the RDBMS specific JDBC driver because this driver actually communicates with the database (Incase of JDBC 4.0 this is automatically loaded). Open the connection to database which is then used to send SQL statements and get results back. Create JDBC Statement object. This object contains SQL query. Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a result of SQL query. Process the result set. Close the connection.

4.Exaplain the JDBC Architecture. The JDBC Architecture consists of two layers: The JDBC API, which provides the application-to-JDBC Manager connection. The JDBC Driver API, which supports the JDBC Manager-to-Driver Connection. The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. The location of the driver manager with respect to the JDBC drivers and the Java application is shown in Figure 1.

Figure 1: JDBC Architecture


5.What are the main components of JDBC ? The life cycle of a servlet consists of the following phases: DriverManager: Manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection. Driver: The database communications link, handling all communication with the database. Normally, once the driver is loaded, the developer need not call it explicitly. Connection : Interface with all methods for contacting a database.The connection object represents communication context, i.e., all communication with database is through connection object only. Statement : Encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed. ResultSet: The ResultSet represents set of rows retrieved due to query execution.

6.How the JDBC application works? A JDBC application can be logically divided into two layers: 1. Driver layer 2. Application layer Driver layer consists of DriverManager class and the available JDBC drivers. The application begins with requesting the DriverManager for the connection. An appropriate driver is choosen and is used for establishing the connection. This connection is given to the application which falls under the application layer.

The application uses this connection to create Statement kind of objects, through which SQL commands are sent to backend and obtain the results.

Figure 2: JDBC Application


7.How do I load a database driver with JDBC 4.0 / Java 6? Provided the JAR file containing the driver is properly configured, just place the JAR file in the classpath. Java developers NO longer need to explicitly load JDBC drivers using code like Class.forName() to register a JDBC driver.The DriverManager class takes care of this by automatically locating a suitable driver when the DriverManager.getConnection() method is called. This feature is backward-compatible, so no changes are needed to the existing JDBC code. 8.What is JDBC Driver interface? The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendor driver must provide implementations of the
java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver.

9.What does the connection object represents? The connection object represents communication context, i.e., all communication with database is through connection object only. 10.What is Statement ? Statement acts like a vehicle through which SQL commands can be sent. Through the connection object we create statement kind of objects. Through the connection object we create statement kind of objects.

Statement stmt

= conn.createStatement();

This method returns object which implements statement interface.

11.What is PreparedStatement? A prepared statement is an SQL statement that is precompiled by the database. Through precompilation, prepared statements improve the performance of SQL com mands that are executed multiple times (given that the database supports prepared statements). Once compiled, prepared statements can be customized prior to each execution by altering predefined SQL parameters.

PreparedStatement pstmt = conn.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?"); pstmt.setBigDecimal(1, 153833.00);

pstmt.setInt(2, 110592);
Here: conn is an instance of the Connection class and "?" represents parameters.These parameters must be specified before execution.

12.What is the difference between a Statement and a PreparedStatement? Statement A standard Statement is used to create a Java representation of a literal SQL statement and execute it on the database. Statement has to verify its metadata against the database every time. PreparedStatement A PreparedStatement is a precompiled statement. This means that when the PreparedStatement is executed, the RDBMS can just run the PreparedStatement SQL statement without having to compile it first. While a prepared statement has to verify its metadata against the database only once.

If you want to execute a single SQL statement multiple number of times, then go for If you want to execute the SQL statement once PREPAREDSTATEMENT. PreparedStatement go for STATEMENT objects can be reused with passing different values to the queries 13.What are callable statements ? Callable statements are used from JDBC application to invoke stored procedures and functions. 14.How to call a stored procedure from JDBC ? PL/SQL stored procedures are called from within JDBC programs by means of the prepareCall() method of the Connection object created. A call to this method takes variable bind parameters as input parameters as well as output variables and creates an object instance of the CallableStatement class. The following line of code illustrates this:

CallableStatement stproc_stmt = conn.prepareCall("{cal l procname(?,?,?)}");


Here conn is an instance of the Connection class. 15.What are types of JDBC drivers? There are four types of drivers defined by JDBC as follows: Type 1: JDBC/ODBCThese require an ODBC (Open Database Connectivity) driver for the database to be installed. This type of driver works by translating the submitted queries into equivalent ODBC queries and forwards them via native API calls directly to the ODBC driver. It provides no host redirection capability. Type2: Native API (partly-Java driver)This type of driver uses a vendor-specific driver or database API to interact with the database. An example of such an API is Oracle OCI (Oracle Call Interface). It also provides no host redirection. Type 3: Open Protocol-NetThis is not vendor specific and works by forwarding database requests to a remote database source using a net server component. How the net server component accesses the database is transparent to the client. The client driver communicates with the net server using a database-independent protocol and the net server translates this protocol into database calls. This type of driver can access any database.

Type 4: Proprietary Protocol-Net(pure Java driver)This has a same configuration as a type 3 driver but uses a wire protocol specific to a particular vendor and hence can access only that vendor's database. Again this is all transparent to the client. Note: Type 4 JDBC driver is most preferred kind of approach in JDBC. 16.Which type of JDBC driver is the fastest one? JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the JDBC calls into vendor specific protocol calls and it directly interacts with the database. 17.Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? No. You can open only one Statement object per connection when you are using the JDBC -ODBC Bridge. 18.Which is the right type of driver to use and when? Type I driver is handy for prototyping Type III driver adds security, caching, and connection control Type III and Type IV drivers need no pre-installation Note: Preferred by 9 out of 10 Java developers: Type IV. Click here to learn more about JDBC drivers. 19.What are the standard isolation levels defined by JDBC? The values are defined in the class java.sql.Connection and are: TRANSACTION_NONE TRANSACTION_READ_COMMITTED TRANSACTION_READ_UNCOMMITTED TRANSACTION_REPEATABLE_READ TRANSACTION_SERIALIZABLE Any given database may not support all of these levels. 20.What is resultset ? The ResultSet represents set of rows retrieved due to query execution.

ResultSet rs = stmt.executeQuery(sqlQuery);
21.What are the types of resultsets? The values are defined in the class java.sql.Connection and are:
TYPE_FORWARD_ONLY specifies

People who read this, also read:Core Java Questions JSF Questions

that a resultset is not scrollable, SCMAD Certification that is, rows within it can be advanced only in the forward Integrating Hibernate with Spring direction.
TYPE_SCROLL_INSENSITIVE

specifies that a resultset is scrollable in either direction but is insensitive to changes committed by other transactions or other statements in the same transaction. TYPE_SCROLL_SENSITIVE specifies that a resultset is scrollable in either direction and is affected by changes committed by other transactions or statements within the same transaction.

Struts Interview Questions

Note: A TYPE_FORWARD_ONLY resultset is always insensitive. 22.Whats the difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE? TYPE_SCROLL_INSENSITIVE An insensitive resultset is like the snapshot of the data in the database when query was executed. TYPE_SCROLL_SENSITIVE A sensitive resultset does NOT represent a snapshot of data, rather it contains points to those rows which satisfy the query condition.

After we get the resultset the changes made to After we obtain the resultset if the data is data are not visible through the resultset, and modified then such modifications are visible hence they are known as insensitive. through resultset. Performance not effected with insensitive. Since a trip is made for every get operation, the performance drastically get affected.

22.What is rowset? A RowSet is an object that encapsulates a set of rows from either Java Database Connectivity (JDBC) result sets or tabular data sources like a file or spreadsheet. RowSets support component based development models like JavaBeans, with a standard set of properties and an event notification mechanism. 24.What are the different types of RowSet ? There are two types of RowSet are there. They are: Connected - A connected RowSet object connects to the database once and remains connected until the application terminates. Disconnected - A disconnected RowSet object connects to the database, executes a query to retrieve the data from the database and then closes the connection. A program may change the data in a disconnected RowSet while it is disconnected. Modified data can be updated in the database after a disconnected RowSet reestablishes the connection with the database.

25.What is the need of BatchUpdates? The BatchUpdates feature allows us to group SQL statements together and send to database server in one single trip. 26.What is a DataSource? A DataSource object is the representation of a data source in the Java programming language. In basic terms, A DataSource is a facility for storing data. DataSource can be referenced by JNDI. Data Source may point to RDBMS, file System , any DBMS etc..

27.What are the advantages of DataSource? The few advantages of data source are : An application does not need to hardcode driver information, as it does with the
DriverManager.

The DataSource implementations can easily change the properties of data sources. For example: There is no need to modify the application code when making changes to the database details. The DataSource facility allows developers to implement a DataSource class to take advantage of features like connection pooling and distributed transactions.

28.What is connection pooling? what is the main advantage of using connection pooling? A connection pool is a mechanism to reuse connections created. Connection poolin can increase g performance dramatically by reusing connections rather than creating a new physical connection each time a connection is requested..

JNDI

Question: What protocols does JNDI provide an interface to? Answer: JNDI itself is independent of any specific directory access protocol. Individual service providers determine the protocols to support. JNDI supports popular protocols, such as LDAP (Light weight Directory Access Protocol) , NDS(Netscape Directory Service), DNS(Domain Naming Service), and NIS(Network Information Service), supplied by different vendors. Question: What is Context and InitialContext? Answer: A context represents a set of bindings within a naming service. A Context object provides the methods for binding names to objects and unbinding names from objects, for renaming objects, and for listing the bindings. JNDI performs all naming operations relative to a context. The JNDI specification defines an InitialContext class. This class is instantiated with properties that define the type of naming service in use (such as provider URL, security, ID and password to use when connecting). Question: What's the difference between JNDI lookup(), list(), listBindings(), and search()? Answer: lookup() attempts to find the specified object in the given context. I.e., it looks for a single, specific object and either finds it in the current context or it fails. list() attempts to return an enumeration of all of the NameClassPair's of all of the objects in the current context. I.e., it's a listing of all of the objects in the current context but only returns the object's name and the name of the class to which the object belongs. listBindings() attempts to return an enumeration of the Binding's of all of the objects in the current context. I.e., it's a listing of all of the objects in the current context with the object's name, its class name, and a reference to the object itself. search() attempts to return an enumeration of all of the objects matching a given set of search criteria. It can search across multiple contexts (or not). It can return whatever attributes of the objects that you desire. Etc. It's by far the most complex and powerful of these options but is also the most expensive. Question: Components of JNDI Answer: Naming Interface- The naming interface organizes information hierarchically and maps human -friendly names to addresses or objects that are machine-friendly. It allows access to named objects through multiple namespaces. Directory Interface- JNDI includes a directory service interface that provides access to directory objects, which can contain attributes, thereby providing attribute-based searching and schema support

What is a naming service?


Naming services map objects with names. It maps a reference to an object by a user friendly name. For example a machine maps its ip address..........
Read answer

What is a directory service?


Searching for files and directories done by providing Directory services. A directory service is a set of names. The user and resource information and machine addresses are summarized by directory service.............
Read answer

http://www.careerride.com/JNDI-Interview-Questions.aspx

What is LDAP?
LDAP stands for Lightweight Directory Access Protocol. This is a protocol for querying and modifying directory services over TCP/IP................
Read answer

How do we use LDAP to work with a directory service?


An LDAP directory can be distributed among many servers. Each server can have a replicated version of the total directory that is synchronized periodically. An LDAP server is called a Directory System Agent (DSA)...............
Read answer

Explain the importance of JNDI.


To centralize the information storage the enterprises uses LDAP. The information is of user names, passwords, email addresses, printers, determination of database access............
Read answer

Explain why we need JNDI if communication to systems via LDAP is possible.


Most of the operations are with databases and servers in LDAP. Using JNDI multiple dbms can be reduced by centralizing the information. The centralization of information storage is done by LDAP...............

What is the purpose of JNDI? JNDI provides a platform-independent Java interface to naming and directory services, such as LDAP, NDS, and Active Directory. With the help JNDI we can bind any objects. That means (java, dotnet..). By using RMI registry we can bind only java objects. JNDI is a platform indepent so we can intaract with any servers.

WEB SERVICE

http://www.javajotter.net/webservices/interview_questions/webservicesin terviewquestions.php

What is a Web service?

Many people and companies have debated the exact definition of Web services. At a minimum, however, a Web service is any piece of software that makes itself available over the Internet and uses a standardized XML messaging system. XML is used to encode all communications to a Web service. For example, a client invokes a Web service by sending an XML message, then waits for a corresponding XML response. Because all communication is in XML, Web services are not tied to any one operating system or programming language--Java can talk with Perl; Windows applications can talk with Unix applications. Beyond this basic definition, a Web service may also have two additional (and desirable)

properties: First, a Web service can have a public interface, defined in a common XML grammar. The interface describes all the methods available to clients and specifies the signature for each method. Currently, interface definition is accomplished via the Web Service Description Language (WSDL). (See FAQ number 7.) Second, if you create a Web service, there should be some relatively simple mechanism for you to publish this fact. Likewise, there should be some simple mechanism for interested parties to locate the service and locate its public interface. The most prominent directory of Web services is currently available via UDDI, or Universal Description, Discovery, and Integration. (See FAQ number 8.) Web services currently run a wide gamut from news syndication and stock-market data to weather reports and package-tracking systems. For a quick look at the range of Web services currently available, check out the XMethods directory of Web services.
What is new about Web services?

People have been using Remote Procedure Calls (RPC) for some time now, and they long ago discovered how to send such calls over HTTP. So, what is really new about Web services? The answer is XML. XML lies at the core of Web services, and provides a common language for describing Remote Procedure Calls, Web services, and Web service directories. Prior to XML, one could share data among different applications, but XML makes this so much easier to do. In the same vein, one can share services and code without Web services, but XML makes it easier to do these as well. By standardizing on XML, different applications can more easily talk to one another, and this makes software a whole lot more interesting.
I keep reading about Web services, but I have never actually seen one. Can you show me a real Web service in action?

If you want a more intuitive feel for Web services, try out the IBM Web Services Browser, available on the IBM Alphaworks site. The browser provides a series of Web services demonstrations. Behind the scenes, it ties together SOAP, WSDL, and UDDI to provide a simple plug-and-play interface for finding and invoking Web services. For example, you can find a stock-quote service, a traffic-report service, and a weather service. Each service is independent, and you can stack services like building blocks. You can, therefore, create a single page that displays multiple services--where the end result looks like a stripped-down version of my.yahoo or my.excite.
What is the Web service protocol stack?

The Web service protocol stack is an evolving set of protocols used to define, discover, and implement Web services. The core protocol stack consists of four layers: Service Transport: This layer is responsible for transporting messages between applications. Currently, this includes HTTP, SMTP, FTP, and newer protocols, such as Blocks Extensible Exchange Protocol (BEEP). XML Messaging: This layer is responsible for encoding messages in a common XML format so that messages can be understood at either end. Currently, this includes XML-RPC and SOAP. Service Description: This layer is responsible for describing the public interface to a specific Web service. Currently, service description is handled via the WSDL. Service Discovery: This layer is responsible for centralizing services into a common registry, and providing easy publish/find functionality. Currently, service discovery is handled via the UDDI. Beyond the essentials of XML-RPC, SOAP, WSDL, and UDDI, the Web service protocol

stack includes a whole zoo of newer, evolving protocols. These include WSFL (Web Services Flow Language), SOAP-DSIG (SOAP Security Extensions: Digital Signature), and USML (UDDI Search Markup Language). For an overview of these protocols, check out Pavel Kulchenko's article, Web Services Acronyms, Demystified, on XML.com. Fortunately, you do not need to understand the full protocol stack to get started with Web services. Assuming you already know the basics of HTTP, it is best to start at the XML Messaging layer and work your way up.
What is XML-RPC?

XML-RPC is a protocol that uses XML messages to perform Remote Procedure Calls. Requests are encoded in XML and sent via HTTP POST; XML responses are embedded in the body of the HTTP response. More succinctly, XML-RPC = HTTP + XML + Remote Procedure Calls. Because XML-RPC is platform independent, diverse applications can communicate with one another. For example, a Java client can speak XML-RPC to a Perl server. To get a quick sense of XML-RPC, here is a sample XML-RPC request to a weather service (with the HTTP Headers omitted): <?xml version="1.0" encoding="ISO-8859-1"?> <methodCall> <methodName>weather.getWeather</methodName> <params> <param><value>10016</value></param> </params> </methodCall> The request consists of a simple element, which specifies the method name (getWeather) and any method parameters (zip code). Here is a sample XML-RPC response from the weather service: <?xml version="1.0" encoding="ISO-8859-1"?> <methodResponse> <params> <param> <value><int>65</int></value> </param> </params> </methodResponse> The response consists of a single element, which specifies the return value (the current temperature). In this case, the return value is specified as an integer. In many ways, XML-RPC is much simpler than SOAP, and therefore represents the easiest way to get started with Web services. The official XML-RPC specification is available at XML-RPC.com. Dozens of XML-RPC implementations are available in Perl, Python, Java, and Ruby. See the XML -RPC home page for a complete list of implementations
What is SOAP?

SOAP is an XML-based protocol for exchanging information between computers. Although SOAP can be used in a variety of messaging systems and can be delivered via a variety of transport protocols, the main focus of SOAP is Remote Procedure Calls (RPC) transported via HTTP. Like XML -RPC, SOAP is platform independent, and therefore enables diverse applications to communicate with one another. To get a quick sense of SOAP, here is a sample SOAP request to a weather service (with the HTTP Headers omitted): <?xml version='1.0' encoding='UTF-8'?>

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/09/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema -instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SOAP-ENV:Body> <ns1:getWeather xmlns:ns1="urn:examples:weatherservice" SOAP-ENV:encodingStyle=" http://www.w3.org/2001/09/soap -encoding <zipcode xsi:type="xsd:string">10016</zipcode> </ns1:getWeather> </SOAP-ENV:Body> </SOAP-ENV:Envelope> As you can see, the request is slightly more complicated than XML-RPC and makes use of both XML namespaces and XML Schemas. Much like XML-RPC, however, the body of the request specifies both a method name (getWeather), and a list of parameters (zipcode). Here is a sample SOAP response from the weather service: <?xml version='1.0' encoding='UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/09/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema -instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SOAP-ENV:Body> <ns1:getWeatherResponse xmlns:ns1="urn:examples:weatherservice" SOAP-ENV:encodingStyle="http://www.w3.org/2001/09/soap -encoding"> <return xsi:type="xsd:int">65</return> </ns1:getWeatherResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> The response indicates a single integer return value (the current temperature). The World Wide Web Consortium (W3C) is in the process of creating a SOAP standard. The latest working draft is designated as SOAP 1.2, and the specification is now broken into two parts. Part 1 describes the SOAP messaging framework and envelope specification. Part 2 describes the SOAP encoding rules, the SOAP-RPC convention, and HTTP binding details.
What is WSDL?

The Web Services Description Language (WSDL) currently represents the service description layer within the Web service protocol stack. In a nutshell, WSDL is an XML grammar for specifying a public interfa ce for a Web service. This public interface can include the following: Information on all publicly available functions. Data type information for all XML messages. Binding information about the specific transport protocol to be used. Address information for locating the specified service. WSDL is not necessarily tied to a specific XML messaging system, but it does include built-in extensions for describing SOAP services.

Below is a sample WSDL file. This file describes the public interface for the weather service used in the SOAP example above. Obviously, there are many details to understanding the example. For now, just consider two points. First, the <message> elements specify the individual XML messages that are transferred between computers. In this case, we have a getWeatherRequest and a getWeatherResponse. Second, the element specifies that the service is available via SOAP and is available at a specific URL. <?xml version="1.0" encoding="UTF-8"?> <definitions name="WeatherService" targetNamespace="http://www.ecerami.com/wsdl/WeatherService.wsdl" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.ecerami.com/wsdl/WeatherService.wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <message name="getWeatherRequest"> <part name="zipcode" type="xsd:string"/> </message> <message name="getWeatherResponse"> <part name="temperature" type="xsd:int"/> </message> <portType name="Weather_PortType"> <operation name="getWeather"> <input message="tns:getWeatherRequest"/> <output message="tns:getWeatherResponse"/> </operation> </portType> <binding name="Weather_Binding" type="tns:Weather_PortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="getWeather"> <soap:operation soapAction=""/> <input> <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:weatherservice" use="encoded"/> </input> <output> <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:weatherservice" use="encoded"/> </output> </operation> </binding> <service name="Weather_Service"> <documentation>WSDL File for Weather Service</documentation> <port binding="tns:Weather_Binding" name="Weather_Port"> <soap:address location="http://localhost:8080/soap/servlet/rpcrouter"/> </port>

</service> </definitions> Using WSDL, a client can locate a Web service, and invoke any of the publicly available functions. With WSDL-aware tools, this process can be entirely automated, enabling applications to easily integrate new services with little or no manual code. For example, check out the GLUE platform from the Mind Electric. WSDL has been submitted to the W3C, but it currently has no official status within the W3C. See this W3C page for the latest draft.
What is UDDI?

UDDI (Universal Description, Discovery, and Integration) currently represents the discovery layer within the Web services protocol stack. UDDI was originally created by Microsoft, IBM, and Ariba, and represents a technical specification for publishing and finding businesses and Web services. At its core, UDDI consists of two parts. First, UDDI is a technical specification for building a distributed directory of businesses and Web services. Data is stored within a specific XML format, and the UDDI specification includes API details for searching existing data and publishing new data. Second, the UDDI Business Registry is a fully operational implementation of the UDDI specification. Launched in May 2001 by Microsoft and IBM, the UDDI registry now enables anyone to search existing UDDI data. It also enables any company to register themselves and their services. The data captured within UDDI is divided into three main categories: White Pages: This includes general information about a specific company. For example, business name, business description, and address. Yellow Pages: This includes general classification data for either the company or the service offered. For example, this data may include industry, product, or geographic codes based on standard taxonomies. Green Pages: This includes technical information about a Web service. Generally, this includes a pointer to an external specification, and an address for invoking the Web service. You can view the Microsoft UDDI site, or the IBM UDDI site. The complete UDDI specification is available at uddi.org. Beta versions of UDDI Version 2 are available at: Hewlett Packard IBM Microsoft SAP
How do I get started with Web Services? The easiest way to get started with Web services is to learn XML-RPC. Check out the XML-RPC specification or read my book, Web Services Essentials. O'Reilly has also recently released a book on Programming Web Services with XML-RPC by Simon St.Laurent, Joe Johnston, and Edd Dumbill. Once you have learned the basics of XML-RPC, move onto SOAP, WSDL, and UDDI. These topics are also covered in Web Services Essentials. For a comprehensive treatment of SOAP, check out O'Reilly's Programming Web Services with SOAP, by Doug Tidwell, James Snell, and Pavel Kulchenko. Does the W3C support any Web service standards?

The World Wide Web Consortium (W3C) is actively pursuing standardization of Web service protocols. In September 2000, the W3C established an XML Protocol Activity. The goal of the group is to establish a formal standard for SOAP. A draft version of SOAP 1.2 is currently under review, and progressing through the official W3C recommendation process. On January 25, 2002, the W3C also announced the formation of a Web Service Activity.

This new activity will include the current SOAP work as well as two new groups. The first new group is the Web Services Description Working Group, which will take up work on WSDL. The second new group is the Web Services Architecture Working Group, which will attempt to create a cohesive framework for Web service protocols.

Design Pattern
What is the design pattern?
If a problem occurs over and over again, a solution to that problem has been used effectively. That solution is described as a pattern. The design patterns are language-independent strategies for solving common object-oriented design problems. When you make a design, you should know the names of some common solutions. Learning design patterns is good for people to communicate each other effectively. In fact, you may have been familiar with some design patterns, you may not use well-known names to describe them. SUN suggests GOF (Gang Of Four--four pioneer guys who wrote a book named "Design Patterns"- Elements of Reusable Object-Oriented Software), so we use that book as our guide to describe solutions. Please make you be familiar with these terms and learn how other people solve the code problems.

Do I have to use the design pattern?


If you want to be a professional Java developer, you should know at least some popular solutions to coding problems. Such solutions have been proved efficient and effective by the experienced developers. These solutions are described as so-called design patterns. Learning design patterns speeds up your experience accumulation in OOA/OOD. Once you grasped them, you would be benefit from them for all your life and jump up yourselves to be a master of designing and developing. Furthermore, you will be able to use these terms to communicate with your fellows or assessors more effectively. Many programmers with many years experience don't know design patterns, but as an Object-Oriented programmer, you have to know them well, especially for new Java programmers. Actually, when you solved a coding problem, you have used a design pattern. You may not use a popular name to describe it or may not choose an effective way to better intellectually control over what you built. Learning how the experienced developers to solve the coding problems and trying to use them in your project are a best way to earn your experience and certification. Remember that learning the design patterns will really change how you design your code; not only will you be smarter but will you sound a lot smarter, too.

How many design patterns?


Many. A site says at least 250 existing patterns are used in OO world, including Spaghetti which refers to poor coding habits. The 23 design patterns by GOF are well known, and more are to be discovered on the way.

Note that the design patterns are not idioms or algorithms or components.

What is the relationship among these patterns?


Generally, to build a system, you may need many patterns to fit together. Different designer may use different patterns to solve the same problem. Usually:
y y y y y y

Some patterns naturally fit together One pattern may lead to another Some patterns are similar and alternative Patterns are discoverable and documentable Patterns are not methods or framework Patterns give you hint to solve a problem effectively

1) What is a software design pattern?


A design pattern is a solution to a general software problem within a particular context. y y y Context : A recurring set of situations where the pattern applies. Problem : A system of forces (goals and constraints) that occur repeatedly in this context. Solution : A description of communicating objects and classes (collaboration) that can be applied to resolve those forces.

Design patterns capture solutions that have evolved over time as developers strive for greater flexibility in their software. Whereas class libraries are reusable source code, and components are reusable packaged objects, patterns are generic, reusable design descriptions that are customized to solve a specific problem. The study of design patterns provides a common vocabulary for communication and documentation, and it provides a framework for evolution and improvement of existing patterns.

2) Why is the study of patterns important?


As initial software designs are implemented and deployed, programmers often discover improvements which make the designs more adaptable to change. Design patterns capture solutions that have evolved over time as developers strive for greater flexibility in their software, and they document the solutions in a way which facilitates their reuse in other, possibly unrelated systems. Design patterns allow us to reuse the knowledge of experienced software designers. Moreover, the study of design patterns provides a common vocabulary for communication and documentation, and it provides a framework for evolution and improvement of existing patterns. As an analogy, consider that during a discussion among programmers, the words stack and tree can be used freely without explanation. Software developers understand fundamental data structures such as a stack because these data structures are well-documented in textbooks and are taught in computer science courses. The study of design patterns will have a similar (but more profound) effect by allowing designers to say composite pattern or observer pattern in a particular design context, without having to describe all classes, relationships, and collaborations which make up the pattern. Patterns raise the level of abstraction when discussing and documenting software designs.

3) How do I document a design pattern?


A pattern description must address the following major points: y Pattern Name and Classification : A short, meaningful name for the pattern, usually only one or two words. Names p rovide a vocabulary for patterns, and they have implied semantics choose names carefully. Following the GoF book, we can also group patterns into higher level classifications such as creational, structural, and behavioral patterns. Problem : A general description of the problem context and the goals and constraints that occur repeatedly in that context. A concrete motivational scenario can be used to help describe the problem. The problem description should provide guidance to assist others in recognizing situations where the pattern can be applied.

Solution : The classes and/or objects that participate in the design pattern, their structure (e.g., in terms of a UML class diagram), their responsibilities, and their collaborations. The solution provides a n abstract description that can be applied in many different situations. Sample Code in an object-oriented language can be used to illustrate a concrete realization of the pattern. Consequences : A discussion of the results and tradeoffs of applying the pattern. Variations and language-dependent alternatives should also be addressed. Known Uses : Examples of the pattern in real systems. Look for applications of the pattern in language libraries and frameworks, published system descriptions, text books, etc. Not every good solution represents a pattern. A general rule of thumb is that a candidate pattern (also called a proto-pattern) should be discovered in a minimum of three existing systems before it can rightfully be called a pattern.

The following qu ote by Robert Martin highlights the importance of providing pattern descriptions: The revolutionary concept of the GoF book is not the fact that there are patterns; it is the way in which those patterns are documented. ... Prior to the GoF book, the only good way to learn patterns was to discover them in design documentation, or (more probably) code.

4) Where can I learn more about design patterns?


The best place to start is the seminal work by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (collectively known as the Gang of Four or simply GoF) entitled Design Patterns: Elements of Reusable Object-Oriented Software (AddisonWesley, 1995). Warning: This book is not light reading. From the Preface: Don't worry if you don't understand this book completely on the first reading. We didn't understand it all on the first writing. It is, however, a book which wears well over time, and it is definitely worth the effort required to work through it. Beyond the GoF book, consider the list of references in the Design Patterns section of this bibliography on object technology, plus the following web links: y y y y Design Patterns Home Page Huston Design Patterns Brad Appleton's Software Patterns Links Cetus Patterns Links

5) What is an example of a design pattern?


Following the lead of the Gang of Four (GoF), design pattern descriptions usually contain multiple sections including y y y y y y Intent Motivation Applicability Structure Participants Collaborations

y y y y y

Consequences Implementation Sample Code Known Uses Related Patterns

A complete discussion of even a small pattern is beyond the scope of a simple FAQ entry, but it is possible to get the idea by examining an abbreviated discussion of one of the simplest and most easily understood patterns. Consider the Singleton pattern, whose intent reads as follows: Intent: Ensure that a class has one instance, and provide a global point of access to it. Almost every programmer has encountered this problem and formulated an approach for solving it in a general way some solutions are better than others. The solution offered by the GoF would look something like the following when coded in Java.

public class Singleton { private static Singleton instance = null; public static Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; } protected Singleton() { ... } // possibly a nother constructor form public void someMethod() { ... } //... other methods }
The programmer would access the single instance of this class by writing something similar to

Singleton.getInstance().someMethod()
or similar to

Singleton s = Si ngleton.getInstance(); s.method1();

... s.method2(); ...


For a more complete discussion of the Singleton pattern, see the chapter Singleton in the book Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four (Addison-Wesley, 1995), or the chapter Singleton in the book Patterns in Java, Volume 1 by Mark Grand (John Wiley & Sons, 1998). For information about variations on the Singleton Pattern, see the chapter entitled To Ki ll a Singleton in the book Pattern Hatching: Design Patterns Applied by John Vlissides or the article Implementing the Singleton Pattern in Java by Rod Waldhoff.

6) Calendar is an abstract class. The getInstance() method tries to instantiate GregorianCalendar() i.e., parent instantiating a derived class. This looks Non-OO? Ex: Calendar a=Calendar.getInstance(); Can somebody explain why is it so?
The Calender class is an abstact class, true, however,the point you missed is that the getInstance() returns the " Calendar using the default timezone and locale. " , in your case, the GregorianCalender a class that IS a Calender (a Suzuki IS a car, a 747 IS a plane..the standard OO terminology. So what you get is a class that does some specialized work based on the default locale. Other methods

public static synchronized Calendar getInstance(TimeZone zone,Locale aLocale) public static synchronized Calendar getInstance(TimeZone zone)
return Calenders for specific timezones and locales. The closest parallel is possibly the Factory Method design pattern.

7) What major patterns do the Java APIs utilize?


Design patterns are used and supported extensively throughout the Java APIs. Here are some examples: y y y The Model-View-Controll er design pattern is used extensively throughout the Swing API. The getInstance() method in java.util.Calendar is an example of a simple form of the Factory Method design pattern. The classes java.lang.System and java.sql.DriverManager are examples of the Singleton pattern, although they are not implemented using the approach recommended in the GoF book but with static methods. The Prototype pattern is supported in Java through the clone() method defined in class Object and the use of java.lang.Cloneable interface to grant permission for cloning. The Java Swing classes support the Command pattern by providing an Action

y y y y

interface and an AbstractAction class. The Java 1.1 event model is based on the observer pattern. In addition, the interface java.util.Observable and the class java.util.Observer provide support for this pattern. The Adapter pattern is used extensively by the adapter classes in java.awt.event. The Proxy pattern is used extensively in the implementation of Java's Remote Method Invocation (RMI) and Interface Definition Language (IDL) features. The structure of Component and Container classes in java.awt provide a good example of the Composite pattern. The Bridge pattern can be found in the separation of the components in java.awt (e.g., Button and List), and their counterparts in java.awt.peer.

8) How can I make sure at most one instance of my class is ever created?
This is an instance where the Singleton design pattern would be used. You need to make the constructor private (so nobody can create an instance) and provide a static method to get the sole instance, where the first time the instance is retrieved it is created:

public class Mine { private static Mine singleton; private Mine() { } public static synchronized M ine getInstance() { if (singleton == null) { singleton = new Mine(); } return singleton; } // other stuff... }

9) When would I use the delegation pattern instead of inheritence to extend a class's behavior?
Both delegation and inheritance are important concepts in object-oriented software design, but not everyone would label them as patterns. In particular, the seminal book on design patterns by the Gang of Four contains a discussion of inheritance and delegation, but the authors do not treat these topics as specific patterns. It is reasonable to think of them as design concepts which are more general than specific design patterns. Inheritance is a relationship between two classes where one class, called a subclass in this context, inherits the attributes and operations of another class, called its superclass. Inheritance can be a powerful design/reuse technique, especially when it is used in the context of the Liskov Substitution Principle. (The article by Robert Martin at http://www.objectmentor.com/publications/lsp.pdf provides an excellent explanation of the ideas behind Barbara Liskovs original paper on using inheritance correctly.) The

primary advantages of inheritance are 1. it is directly supported by object-oriented languages, and 2. it provides the context for polymorphism in strongly -typed object-oriented languages such as C++ and Java. But since the inheritance relationship is defined at compile-time, a class cant change its superclass dynamically during program execution. Moreover, modifications to a superclass automatically propagate to the subclass, providing a two -edged sword for software maintenance and reuse. In summary, inheritance creates a strong, static coupling between a superclass and its subclasses. Delegation can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation can also a powerful design/reuse technique. The primary advantage of delegation is run -time flexibility the delegate can easily be changed at run-time. But unlike inheritance, delegation is not directly supported by most popular object -oriented languages, and it doesnt facilitate dynamic polymorphism. As a simple example, consider the relationship between a Rectangle class and a Window class. With inheritance, a Window class would inherit its rectangular properties from class Rectangle. With delegation, a Window object would maintain a reference or pointer to a Rectangle object, and calls to rectangle-like methods of the Window object would be delegated to corresponding methods of the Rectangle object. Now lets consider a slightly more complex example. Suppose employees can classified based on how they are paid; e.g., hourly or salaried. Using inheritance, we might design three classes: an Employee class which encapsulates the functionality common to all employees, and two subclasses HourlyEmployee and SalariedEmployee which encapsulates pay-specific details. While this design might be suitable for some applications, we would encounter problems in a scenario where a person changes, say from hourly to salaried. The class of an object and the inheritance relationship are both static, and objects cant change their class easily (but see the State pattern for tips on how to fake it). A more flexible design would involve delegation an Employee object could delegate pay-related method calls to an object whose responsibilities focused solely on how the employee is paid. In fact, we might still use inheritance here in a slightly different manner by creating an abstract class (or interface) called PayClassification with two subclasses HourlyPayClassification and SalariedPayClassification which implement classification-specific computations. Using delegation as shown, it would be much easier to change the pay classification of an existing Employee object. This second example illustrates an important point: In implementing delegation, we often want the capability to replace the delegate with another object, possibly of a different class. Therefore delegation will often use inheritance and polymorphism, with classes of potential delegates being subclasses of an abstract class which encapsulates general delegate responsibilities. One final point. Someti mes, the choice between delegation and inheritance is driven by external factors such as programming language support for multiple inheritance or design constraints requiring polymorphism. Consider threads in Java. You can associate a class with a thread in one of two ways: either by extending (inheriting) directly from class Thread, or by implementing the Runnable interface and then delegating to a Thread object. Often the approach taken is based on the restriction in Java that a class can only

extend one class (i.e., Java does not support multiple inheritance). If the class you want to associate with a thread already extends some other class in the design, then you would have to use delegation; otherwise, extending class Thread would usually be the simpler approach.

10) Which patterns were used by Sun in designing the Enterprise JavaBeans model?
Many design patterns were used in EJB, and some of them are clearly identifiable by their naming convention. Here are several: 1. Factory Method: Define a interface for creating classes, let a subclass (or a helper class) decide which class to instantiate. This is used in EJB creation model. EJBHome defines an interface for creating the EJBObject implementations. They are actually created by a generated container class. See InitialContextFactory interface that returns an InitialContext based on a properties hashtable. 2. Singleton: Ensure a class has only one instance, and provide a global point of access to it. There are many such classes. One example is javax.naming.NamingManager 3. Abstract Factory: Provide an interface for creating families of relegated or dependent objects without specifying their concrete classes. We have interfaces called InitialContext, InitialContextFactory. InitialContextFactory has methods to get InitialContext. 4. Builder: Separate the construction of a complex factory from its representation so that the same construction process can create different representations. InitialContextFactoryBuilder can create a InitialContextFactory. 5. Adapter: Convert the interface of a class into another interface clients expect. In the EJB implementation model, we implement an EJB in a class that extends SessionBean or a EntityBean. We don't directly implement the EJBObject/home interfaces. EJB container generates a class that adapts the EJBObject interface by forwarding the calls to the enterprise bean class and provides declarative transaction, persistence support. 6. Proxy: Provide a surrogate for other object to control access to it. We have remote RMI-CORBA proxies for the EJB's. 7. Memento: Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later. Certainly this pattern is used in activating/passivating the enterprise beans by the container/server.

11) What is an analysis pattern?


An analysis pattern is a software pattern not related to a language or implementation problem, but to a business domain, such as accounting or health care. For example, in health care, the patient visit activity would be subject to a number of patterns. There is a good overview from an OOPSLA '96 presentation at http://www.jeffsutherland.org/oopsla96/fowler.html A good text would be: Martin Fowler's Martin Analysis Patterns : Reusable Object Models, ISBN: 0201895420, published by Addison -Wesley. In summary, analysis patterns are useful for discovering and capturing business processes.

12) What are the differences between analysis patterns and design patterns?
Analysis pattern are for domain architecture, and design pattern are for implementation mechanism for some aspect of the domain architecture. In brief, analysis pattern are more high level and more (end-user) functional oriented.

13) How does "Extreme Programming" (XP) fit with patterns?


Extreme Programming has a large emphasis on the concept of refactoring: Writing code once and only once. Patterns, particularly the structural patterns mentioned by the Gang of Four, can give good pointers about how to acheive that goal. (XP states when and where factoring should happen, patterns can show you how.)

14) What is the disadvantage of using the Singleton pattern? It is enticing to use this pattern for all the classes as it makes it easy to get the reference of the singleton object.
The intent of the Singleton pattern is to ensure a class has only one instance and to provide a global point of access to it. True, the second part about providing a global point of access is enticing, but the primary disadvantage of using the Singleton pattern for all classes is related to the first part of the intent; i.e., that it allows only one instance of the class. For most classes in an application, you will need to create multiple instances. What purpose would a Customer class serve if you could create only one Customer object?

15) How do you write a Thread-Safe Singleton?


I have written plenty of non-thread-safe Singletons but it wasn't until recently when I tracked it down that I realized that thread-safety could be a big problem.

The problem is that in the typical Singleton implementation (at least the ones I've seen) there is the ability to create multiple versions of the single instance...I know, "But How?". Well, in the getInstance() call the instance is checked for null, and then immediately constructed if it is null, and then the instance is returned. The problem is that the thread (Ta) making the call could swap -out immediately after checking for a null. A subsequent thread (Tb) could then make a call to get the instance and construct an instance of the Singleton. When the original thread (Ta) is then swapped back in, it would construct and return a completely separate object. BAD KITTY! The following code snippet shows an example of a thread -safe Singleton.

package com.jgk.patterns.singleton; public class JGKSingleton { /* Here is the instance of the Singleton */ private static JGKSingleton instance_; /* Need the following object to synchronize */ /* a block */ private static Object syncObject_; /* Prevent direct access to th e constructor private JGKSingleton() { super(); } public static JGKSingleton getInstance() { /* in a non-thread-safe version of a Singleton */ /* the following line could be executed, and the */ /* thread could be imme diately swapped out */ if (instance_ == null) { synchronized(syncObject_) { if (instance_ == null) { instance_ = new JGKSingleton(); } } } return instance_; } }
NOTE: The 2nd check for construct. is needed to avoid making another unnecessary

if (instance_ == null)

Don't let this byte you! ;-)

16) What is the Reactor pattern?


The new book "Pattern-oriented Software Architecture Volume 2" ISBN 0471606952 has a chapter on the Reactor pattern. It falls under the general category of "Event Handling Patterns". To quote the leading bit of the chapter, "The Reactor architectural pattern allows event-driven applications to demultiplex and dispatch service requests that are delivered to an application from one or more clients" It is used in a synchronous manner, so that if the callback you delegate the event to takes a while to complete you will run into problems with scalability.

17) What are Process Patterns?


Basically process patterns define a collection of best practices, techniques, methods for developing object-oriented software. A good reference site is by Scott Ambler. He also has two books on the topic plus a white paper on the subject you can download. http://www.ambysoft.com/processPatternsPage.html.

18) How and where did the concept of design patterns get started?
Work on patterns has been influenced by the works of Christopher Alexander who published on topics related to urban planning and building arch itecture in the late 1970s. The history of patterns for software design began in the late 1980s and reached an important milestone with the publishing of the first book fully dedicated to this subject by the "Gang of Four", Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns - Elements of Reusable Object-Oriented Software). In conjunction, the emergence of object-oriented software development fostered the work on other topics related to design patterns such as application frameworks, analysis patterns, language idioms, and so on.

19) Where can I find good examples of the Prototype pattern?


The prototype pattern is actually quite simple to implement in Java. Recall that the idea of prototype is that you are passed an object and use that object as a template to create a new object. Because you might not know the implementation details of the object, you cannot create a new instance of the object and copy all of its data. (Some of the data may not be accessible via methods). So you ask the object itself to give you a copy of itself. Java provides a simple interface named Cloneable that provides an implementation of the Prototype pattern. If you have an object that is Cloneable, you can call its clone() method to create a new instance of the object with the same values.

The trick here is that you must override the clone() method to increase its visibility, and just call super.clone(). This is because the implementation of clone(), defined in java.lang.object, is protected. For example:

public class CopyMe implements Cloneable { public Object clone() { return super.clone(); } }
Note that Cloneable is an empty interface! It merely acts as a tag to state that you really want instance of the class to be cloned. If you don't implement Cloneable, the super.clone() implementation will throw a CloneNotSupportedException. The Object implementation of clone() performs a shallow copy of the object in question. That is, it copies the values of the fields in the object, but no t any actual objects that may be pointed to. In other words, the new object will point to the same objects the old object pointed to. As an example of using the cloning:

CopyMe thing = new Copyme(); CopyMe anotherThing = (Copyme)thing.clone();


This example is pretty trivial, but the real power comes when you don't know what you're actually cloning. For example, suppose you define an interface that represents a customer:

public interface Customer extends Cloneable { public Object clone(); // req uire making it public! public String getName(); public void setName(String name); ... }
You might have several different implementations of this interface, possibly storing data in a file, database, or using EJB Entity beans. If a shallow copy of the data is sufficient to represent a copy of the object, Java's clone() method works great. You might have a method that needs to make a copy of the data to store it in a Hashtable, for example:

public void storeCustomer(Customer customer) {

Customer copy = (Customer)customer.clone(); dataStore.put(copy); }


Note that this method knows nothing about what type of customer we're getting. This pattern will work for any actual type of Customer, no matter how the data is stored. For example:

FileBasedCustomer c1 = new FileBasedCustomer(...); RDBMSBasedCustomer c2 = new RDBMSBasedCustomer(...); EJBBasedCustomer c3 = new EJBBasedCustomer(...); manager.storeCustomer(c1); manager.storeCustomer(c2); manager.storeCustomer(c3);

20) What are Anti-Patterns?


There isn't really a "clean-cut" definition out there just yet, unlike Design Patterns. Basically, as Design Patterns (and more particularly, Process Patterns) try to codify a standard vocabulary for working solutions to problems that reappe ar frequently, AntiPatterns represent an effort to define and classify reoccuring non-solutions, i.e., things that lots of projects do that fail to yield a solution, or actually prevent a project from working or being finished. The most basic example I can think of is "The Hammer", inspired by the old addage, "If your only tool is a hammer, everything looks like a nail" (or the variation, "If your only tool is a hammer, everything looks like your left thumb." Hammer describes a regular, reoccuring problem in inexperienced engineers (particularly those who've only used one language for the bulk of their carreer so far), that of trying to force -feed all problems into the solutions they already know.

21) What patterns are particularly useful in building networked applications?


I suggest starting with Pattern-Oriented Software Architecture: Patterns for Concurrent and Networked Objects (POSA2). POSA2 specifically brings together 17 interrelated patterns addressing Service Access and Configuration, Event Handling, Synchronization, and Concurrency. The patterns and many of the examples in POSA2 come primarily from the design and implementation of the ACE framework.

22) Are there any good Java-specific patterns books available?


The Java-specific patterns books are:

y y y y y

Java Design Patterns: A Tutorial Patterns in Java, Volume 1 Patterns in Java, Volume 2 Concurrent Programming in Java , Second Edition: Design Principles and Patterns SanFrancisco Design Patterns

As far as the good part of the question.... Doug Lea's Concurrent Programming book is probably the best of the bunch. However, its patterns are specific to concurrent programming. Many people don't like the quality of Mark Gr and's two Patterns in Java books. [They are rated 3 and 2 stars at Amazon, respectively]. The first printing of the Cooper tutorial book was riddled with errors. If you get that, be sure to get at least the second printing. [Look on last line of page befor e TOC.] The SanFrancisco book is definitely good, but I'm not sure how good if you aren't using SF.

23) What are Collaboration Patterns?


Collaboration Patterns are repeatable techniques used by teams of people to help them work together (collaborate). Ellen Gottesdiener of EBG Consulting has created these patterns in order to help facilitate good teamwork. These patterns really have nothing to do with object-oriented development or Java, besides the fact that they can help with requirements gathering or CRC design sessions. In a nutshell, Collaboration Patterns are techniques to help make meetings useful.

24) Is it correct from a design point of view to make an object both an Observer and Observable at the same time?
Yes, and this can be the preferred pattern in some cases. For example, suppose you were writing a supply chain management system for a retail chain. Each store object in your system generates item-sold events; when the chain generates enough of these for a particular product, a buyer object generates a purchase order for more of the product. However, the buyer object has no particular interest in individual item sold events. Instead, the buyer (Observer) registers to receive out-ofstock events from the warehouse (Observable); the warehouse, as Observer, registers with the individual stores (Observables) to receive item-sold events. Thus, the warehouse is both Observer and Observable. (Please note that this is a synthetic example, and probably not the way to organize a supply chain.) Another reason to use one or more central Observer-Observable object in between ultimate Observers and Observables is to fully decouple the two. In some cases, Observer and Observable may exist on different machines, and may rely on the central Observer-Observable to hide this complication. A good source for more details is the Publisher -Subscriber section of Buschmann et al., Pattern-Oriented Software Architecture: A System of Patterns.

25) How can I maintain a single instance of an object in an applet?


In start(), instead of always creating a new object, return the existing one if it exists or create a new one if it doesn't.

26) What is the best way to generate a universally unique object ID? Do I need to use an external resource like a file or database, or can I do it all in memory?
I need to generate unique id's that will be used for node 'ID' attribute values within XML documents. This id must be unique system -wide. The generator must be available to a number of servlets that add various node structures to my XML docs as a service. What is the best way to tackle this? The 'possible' ways I can see: y Keep the maximum ID value in a flat-file where the service would read it upon start-up and increment it. Upon shutdown or failure, it would write the latest max id to the file. Calculate the max id by searching the XML itself. This will be tougher since X ML requires an alpha-numeric value (not strictly numeric). Use a database (MySQL) with a two-field table where one field is the incremental counter.

y y

I just have this feeling that none of the above are the most efficient ways of doing this. Regards, -Andy] There is an additional way to do that that doesn't rely on an external file (or database) like the one you have presentred. If has been presented in the EJB Design Patterns book, written by Floyd Marinescu, and available in a pdf format for free from the given link. The suggested solution is based on the UUID for EJB pattern, that comes out from this question: How can universally unique primary keys can be generated in menory without requiring a database or a singleton? Without enetring in the specifics ( you can fully check out the pattern by reading the appropriate chapter), the solution is to generate a 32 digit key, encoded in hexadecimal composed as follows: 1. Unique down to the millisecond . Digits 1-8 are are the hex encoded lower 32 bits of the System.currentTimeMillis() call. 2. Unique across a cluster. Digits 9-16 are the encoded representation of the 32 bit integer of the underlying IP address. 3. Unique down to the object in a JVM . Digits 17-24 are the hex representation of the call to System.identityHashCode(), which is guaranteed to return distinct integers for distinct objects within a JVM. 4. Unique within an object within a millisecond . Finally digits 25-32 represent a random 32 bit integer generated on every method call using the cryptographically strong java.security.SecureRandom class.

27) Is there some kind of Design pattern which would make it possible to use the Same code base in EJB and non EJB context?
A good suggestion would be using Delegation

class PieceOfCode { public Object myMethod () {} } class EJBImpl ... { PieceOfCode poc = new PieceOfCode(); public Object myMethod() { return poc.myMethod(); } }
This should not be a violation of EJB specs, since EJBs can use simple java classes for their use. Think about Dependant Objects and so on.

28) What is session facade?


Session facade is one design pattern that is often used while developing enterprise applications. It is implemented as a higher level component (i.e.: Session EJB), and it contains all the iteractions between low level components (i.e.: Entity EJB). It then provides a single interface for the functionality of an application or part of it, and it decouples lower level components simplifying the design. Think of a bank situation, where you have someone that would like to transfer money from one account to another. In this type of scenario, the client has to check that the user is authorized, get the status of the two accounts, check that there are enough money on the first one, and then call the transfer. The entire transfer has to be done in a single transaction otherwise is something goes south, the situation has to be restored. As you can see, multiple server-side objects need to be accessed and possibly modified. Multiple fine-grained invocations of Entity (or even Session) Beans add the overhead of network calls, even multiple transaction. In other words, the risk is to have a solution that has a high network overhead, high coupling, poor reusability and mantainability. The best solution is then to wr ap all the calls inside a Session Bean, so the clients will have a single point to access (that is the session bean) that will take care of handling all the rest. Obviously you need to be very careful when writing Session Facades, to avoid the abusing of i t (often called "God-Bean"). For a detailed description of this pattern, check this page: Core J2EE Patterns - Session Facade or get Floyd Marinescu's EJB Design Patterns, in PDF format.

29) How is JDO different from VO ?


JDO is a persistence technology that competes against entity beans in enterprise application development. It allows you to create POJOs (plain old java objects) and persist them to the database - letting JDO take care of the storage. Value objects, on the other hand, represent an abstract design pattern used in conjuction with entity beans, jdbc, and possibly even JDO to overcome commonly found isolation and transactional problems in enterprise apps. Value objects alone do not allow you to persist objects - they are simple data holders used to transfer data from the database to the client and back to the database. Side note: I know that many books out there still refer to these data holders as value objects but the correct term is DTO: data transfer objects. Value objects refer to objects that hold a value. A good example of this java.lang.Integer object which holds an int.

30) How can I implement the MVC design pattern using JSP?
The MVC (Model View Controller) design pattern is a pattern/architecture that can be used by GUI's. It seperates the application's data, user interface and control logic into three separate entities. This ensures the system will be more maintainable in the future as changes to one component will not have an affect on the others. The MVC pattern also conforms with the JSP Model 2 architecture. The MVC pattern can be easily implemented in web applications using JSTL core, JSP, Servlets and JavaBeans.JSTL makes it easy for HTML designers to use dynamic data in their pages without having to learn in depth java. The tags are in a recognizable HTML like format meaning a smaller learning curve than taking on the JSP specification after taking on the Java specification. JSTL also makes it easy for web developers who are developing all aspects of the application in helping you keep the content separate from the display by keeping your JSP clean from any Java code. Since JSTL and its EL (expression Language) are really only suited for accessing data, it forces you to use a MVC pattern so long as you keep all JSP and Java syntax/code out of the JSP pages. A common scenario might look like this, a user sends a request to a server. The request is handled by a Servlet (the controller) which will initialize any JavaBeans (the model) required to fulfill the user's request. The Servlet (the controller) will then forward the request, which contains the JavaBeans (the model), to a JSP (the view) page which contains only HTML and JSTL syntax. The JSTL will format the data into a human readable format before being sent back to the user. Thus completing the full MVC process. JSTL also has a tag library for XML processing, this could be used in an MVC environment as you could replace the JavaBeans with an XML document to describe your data, so long as the XML is still constructed in a controller such as a Servlet before being passed to the JSP (the view). JSTL also has a tag library for database access, using this in your JSP (the view) pages would NOT comply to the MVC pattern as there will be no separation betw een the model and the view.

ORACLE
http://www.sqlauthority.com http://www.sqlauthority.com

SQL Interview Questions with Answers


http://www.sqlauthority.com
What is RDBMS? Relational Data Base Management Systems (RDBMS) are database management systems that maintaindata records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers. This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage. What is normalization? Database normalization is a data design and organization process applied to data structures based on rules that help build relational databases. In relational database design, the process of organizing data to minimize redundancy. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables. The objective is to isolate data so that additions, deletions, and modifications of a field can be made in just one table and then propagated thr ough the rest of the database via the defined relationships. What are different normalization forms? 1NF: Eliminate Repeating Groups Make a separate table for each set of related attributes, and give each table a primary key. Each fieldcontains at most one value from its attribute domain. 2NF: Eliminate Redundant Data If an attribute depends on only part of a multi -valued key, remove it to a separate table. 3NF: Eliminate Columns Not Dependent On Key If attributes do not contribute to a description of the key, remove them to a separate table. All attributes must be directly dependent on the primary key BCNF: Boyce-Codd Normal Form If there are non-trivial dependencies between candidate key attributes, separate them out into distinct tables. 4NF: Isolate Independent Multiple Relationships No table may contain two or more 1:n or n:m relationships that are not directly related. 5NF: Isolate Semantically Related Multiple Relationships There may be practical constrains on information that justify separating logic ally related many-to-many relationships. ONF: Optimal Normal Form A model limited to only simple (elemental) facts, as expressed in Object Role Model notation. DKNF: Domain-Key Normal Form A model free from all modification anomalies. Remember, these normalization guidelines are cumulative. For a database to be in 3NF, it must first fulfill all the criteria of a 2NF and 1NF database. What is Stored Procedure? A stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. And when the procedure is modified, all clients automatically get the

new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database. e.g. sp_helpdb, sp_renamedb, sp_depends etc. What is Trigger? A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE) occurs. Triggers are stored in and managed by the DBMS.Triggers are used to maintain the referential http://www.sqlauthority.com http://www.sqlauthority.com integrity of data by changing the data in a systematic fashion. A trigger cannot be called or executed; the DBMS automatically fires the trigger as a result of a data modification to the associated table. Triggers can be viewed as similar to stored procedures in that both consist of procedural logic that is stored at the database level. Stored procedures, however, are not event-drive and are not attached to a specific table as triggers are. Stored procedures are explicitly executed by invoking a CALL to the procedure while triggers are implicitly executed. In addition, triggers can also execute stored procedures. Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when the trigger is fired because of data modification it can also cause another data modification, thereby firing another trigger. A trigger that contains data modification logic within itself is called a nested trigger. What is View? A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the view was created with. It should also be noted that as data in the original table changes, so does data in the view, as views are the way to look at part of the original tabl e. The results of using a view are not permanently stored in the database. The data accessed through a view is actually constructed using standard T-SQL select command and can come from one to many different base tables or even other views. What is Index? An index is a physical structure containing pointers to the data. Indices are created in an existing table to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes, they are just used to speed up queries. Effective indexes are one of the best ways to improve performance in a database application. A table scan happens when there is no index available to help a query. In a table scan SQL Server examines every row in the table to satisfy the query results. Table scans are sometimes unavoidable, but on large tables, scans have a terrific impact on performance. Clustered indexes define the physical sorting of a database tables rows in the storage media. For this reason, each database table may have only one clustered index. Non-clustered indexes are created outside of the database table and contain a sorted list of references to the table itself. What is the difference between clustered and a non-clustered index? A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages. A nonclustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.

What are the different index configurations a table can have? A table can have one of the following index configurations: No indexes A clustered index A clustered index and many nonclustered indexes A nonclustered index Many nonclustered indexes What is cursors? Cursor is a database object used by applications to manipulate data in a set on a row by-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time. http://www.sqlauthority.com http://www.sqlauthority.com In order to work with a cursor we need to perform some steps in the following order: Declare cursor Open cursor Fetch row from the cursor Process fetched row Close cursor Deallocate cursor What is the use of DBCC commands? DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks. E.g. DBCC CHECKDB - Ensures that tables in the db and the indexes are correctly linked. DBCC CHECKALLOC - To check that all pages in a db are correctly allocated. DBCC CHECKFILEGROUP - Checks all tables file group for any damage. What is a Linked Server? Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements. With a linked server, you can create very clean, easy to follow, SQL statements that allow remote data to be retrieved, joined and combined with local data. Storped Procedure sp_addlinkedserver, sp_addlinkedsrvlogin will be used add new Linked Server. What is Collation? Collation refers to a set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence, with options for specifying casesensitivity, accent marks, kana character types and character width. What are different type of Collation Sensitivity? Case sensitivity A and a, B and b, etc. Accent sensitivity a and , o and , etc. Kana Sensitivity When Japanese kana characters Hiragana and Katakana are treated differently, it is called Kana sensitive. Width sensitivity When a single-byte character (half-width) and the same character when represented as a double-byte character (full-width) are treated differently then it is width sensitive. What's the difference between a primary key and a unique key? Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only. How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships. One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships. Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table. What is a NOLOCK? http://www.sqlauthority.com http://www.sqlauthority.com Using the NOLOCK query optimiser hint is generally considered good practice in order to improve concurrency on a busy system. When the NOLOCK hint is included in a SELECT statement, no locks are taken when data is read. The result is a Dirty Read, which means that another process could be updating the data at the exact time you are reading it. There are no guarantees that your query will retrieve the most recent data. The advantage to performance is that your reading of data will not block updates from taking place, and updates will not block your reading of data. SELECT statements take Shared (Read) locks. This means that multiple SELECT statements are allowed simultaneous access, but other processes are blocked from modifying the data. The updates will queue until all the reads have completed, and reads requested after the update will wait for the updates to complete. The result to your system is delay(blocking). What is difference between DELETE & TRUNCATE commands? Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command. TRUNCATE TRUNCATE is faster and uses fewer system and transaction log resources than DELETE. TRUNCATE removes the data by deallocating the data pages used to store the tables data, and only the page deallocations are recorded in the transaction log. TRUNCATE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint. Because TRUNCATE TABLE is not logged, it cannot activate a trigger. TRUNCATE can not be Rolled back. TRUNCATE is DDL Command. TRUNCATE Resets identity of the table. DELETE DELETE removes rows one at a time and records an entry in the transaction log for each deleted row. If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement. DELETE Can be used with or without a WHERE clause DELETE Activates Triggers. DELETE Can be Rolled back. DELETE is DML Command. DELETE does not reset identity of the table. Difference between Function and Stored Procedure? UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be. UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables. Inline UDF's can be though of as views that take parameters and can be used in JOINs and other Rowset operations. When is the use of UPDATE_STATISTICS command?

This command is basically used when a large processing of data has occurred. If a large amount of deletions any modification or Bulk Copy into the tables has occurred, it has to update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly. What types of Joins are possible with Sql Server? Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table. Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS. http://www.sqlauthority.com http://www.sqlauthority.com What is the difference between a HAVING CLAUSE and a WHERE CLAUSE? Specifies a search condition for a group or an aggregate. HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function i n a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query. What is sub-query? Explain properties of sub-query. Sub-queries are often referred to as sub-selects, as they allow a SELECT statement to be executed arbitrarily within the body of another SQL statement. A sub-query is executed by enclosing it in a set of parentheses. Sub-queries are generally used to return a single row as an atomic value, though they may be used to compare values against multiple rows with the IN keyword. A subquery is a SELECT statement that is nested within another T-SQL statement. A subquery SELECT statement if executed independently of the T-SQL statement, in which it is nested, will return a result set. Meaning a subquery SELECT statement can standalone and is not depended on the statement in which it is nested. A subquery SELECT statement can return any number of values, and can be found in, the column list of a SELECT statement, a FROM, GROUP BY, HAVING, and/or ORDER BY clauses of a T-SQL statement. A Subquery can also be used as a parameter to a function call. Basically a subquery can be used anywhere an expression can be used. Properties of Sub-Query A subquery must be enclosed in the parenthesis. A subquery must be put in the right hand of the comparison operator, and A subquery cannot contain a ORDER-BY clause. A query can contain more than one sub-queries. What are types of sub-queries? Single-row subquery, where the subquery returns only one row. Multiple-row subquery, where the subquery returns multiple rows,.and Multiple column subquery, where the subquery returns multiple columns. What is SQL Profiler? SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of Microsoft SQL Server. You can capture and save data about each event to a file or SQL Server table to analyze later. For example, you can monitor a production environment to see which stored procedures are hampering performance by executing too slowly. Use SQL Profiler to monitor only the events in which you are interested. If traces are becoming too large, you can filter them based on the information you want, so that only a subset of the event data is collected. Monitoring too many events adds overhead to the server and the monitoring process and can cause the trace file or trace table to grow very large, especially when the monitoring process takes place over a long period of time.

What is User Defined Functions? User-Defined Functions allow to define its own T -SQL functions that can accept 0 or more parameters and return a single scalar data value or a table data type. What kind of User-Defined Functions can be created? There are three types of User-Defined functions in SQL Server 2000 and they are Scalar, Inline Table-Valued and Multi -statement Table-valued. Scalar User-Defined Function A Scalar user-defined function returns one of the scalar data types. Text, ntext, image and timestamp data types are not supported. These are the type of user-defined functions that most developers are used to in other programming languages. You pass in 0 to many parameters and you get a return value. http://www.sqlauthority.com http://www.sqlauthority.com Inline Table-Value User-Defined Function An Inline Table-Value user-defined function returns a table data type and is an exceptional alternative to a view as the user-defined function can pass parameters into a T-SQL select command and in essence provide us with a parameterized, non-updateable view of the underlying tables. Multi-statement Table-Value User-Defined Function A Multi-Statement Table-Value user-defined function returns a table and is also an exceptional alternative to a view as the function can support multiple T -SQL statements to build the final result where the view is limited to a single SELECT statement. Also, the ability to pass parameters into a TSQL select command or a group of them gives us the capability to in essence create a parameterized, non-updateable view of the data in the underlying tables. Within the create function command you must define the table structure that is being returned. After creating this type of user -defined function, It can be used in the FROM clause of a T-SQL command unlike the behavior found when using a stored procedure which can also return record sets. Which TCP/IP port does SQL Server run on? How can it be changed? SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP properties > Port number.both on client and the server. What are the authentication modes in SQL Server? How can it be changed? Windows mode and mixed mode (SQL & Windows). To change authentication mode in SQL Server click Start, Programs, Microsoft SQL Server and click SQL Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL Server program group. Select the server then from the Tools menu select SQL Server Configuration Properties, and choose the Security page. Where are SQL server users names and passwords are stored in sql server? They get stored in master db in the sysxlogins table. Which command using Query Analyzer will give you the version of SQL server and operating system? SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')

What is SQL server agent? SQL Server agent plays an important role in the day-to-day tasks of a database administrator (DBA). It is often overlooked as one of the main tools for SQL Server management. Its purpose is to ease the implementation of tasks for the DBA, with its full-function scheduling engine, which allows you to schedule your own jobs and scripts. Can a stored procedure call itself or recursive stored procedure? How many level SP nesting possible?

Yes. Because Transact-SQL supports recursion, you can write stored procedures that call themselves. Recursion can be defined as a method of problem solving wherein the solution is arrived at by repetitively applying it to subsets of the problem. A common application of recursive logic is to perform numeric computations that lend themselves to repetitive evaluation by the same processing steps. Stored procedures are nested when one stored procedure calls another or executes managed code by referencing a CLR routine, type, or aggregate. You can nest stored procedures and managed code references up to 32 levels. What is @@ERROR? The @@ERROR automatic variable returns the error code of the last Transact-SQL statement. If there was no error, @@ERROR returns zero. Because @@ERROR is reset after each TransactSQL statement, it must be saved to a variable if it is needed to process it further after checking it. http://www.sqlauthority.com http://www.sqlauthority.com What is Raiseerror? Stored procedures report errors to client applications via the RAISERROR command. RAISERROR doesn't change the flow of a procedure; it merely displays an error message, sets the @@ERROR automatic variable, and optionally writes the message to the SQL Server error log and the NT application event log. What is log shipping? Log shipping is the process of automating the ba ckup of database and transaction log files on a production SQL server, and then restoring them onto a standby server. Enterprise Editions only supports log shipping. In log shipping the transactional log file from one server is automatically updated into the backup database on the other server. If one server fails, the other server will have the same db can be used this as the Disaster Recovery plan. The key feature of log shipping is that is will automatically backup transaction logs throughout the day an d automatically restore them on the standby server at defined interval. What is the difference between a local and a global variable? A local temporary table exists only for the duration of a connection or, if defined inside a compound statement, for the duration of the compound statement. A global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection are closed, the data in the global temporary table disappears. However, the table definition remains with the database for access when database is opened next time. What command do we use to rename a db? sp_renamedb oldname , newname If someone is using db it will not accept sp_renmaedb. In that case first bring db to single user using sp_dboptions. Use sp_renamedb to rename database. Use sp_dboptions to bring database to multi user mode. What is sp_configure commands and set commands?

Use sp_configure to display or change server-level settings. To change database-level settings, use ALTER DATABASE. To change settings that affect only the current user session, use the SET statement. What are the different types of replication? Explain. The SQL Server 2000-supported replication types are as follows: y Transactional y Snapshot y Merge Snapshot replication distributes data exactly as it appears at a specific moment in time and does not monitor for updates to the data. Snapshot replication is best used as a method for replicating data that changes infrequently or where the most up-to-date values (low latency) are not a requirement. When synchronization occurs, the entire snapshot is generated and sent to Subscribers. Transactional replication, an initial snapshot of data is applied at Subscribers, and then when data modifications are made at the Publisher, the individual transactions are captured and propagated to Subscribers. Merge replication is the process of distributing data from Publisher to Subscribers, allowing the Publisher and Subscribers to make updates while connected or disconnected , and then merging the updates between sites when they are connected. What are the OS services that the SQL Server installation adds? MS SQL SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac co -ordinator) What are three SQL keywords used to change or set someones permissions? http://www.sqlauthority.com http://www.sqlauthority.com GRANT, DENY, and REVOKE. What does it mean to have quoted_identifier on? What are the implications of having it off? When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double quotation marks, and literals must be delimited by single quotation marks. When SET QUOTED_IDENTIFIER is OFF, identifiers cannot be quoted and must follow all Transact -SQL rules for identifiers. What is the STUFF function and how does it differ from the REPLACE function? STUFF function to overwrite existing characters. Using this syntax, STUFF(string_expression, start, length, replacement_characters), string_expression is the string that will have characters substituted, start is the starting position, length is the number of characters in the string that are substituted, and replacement_characters are the new characters interjected into the string. REPLACE function to replace existing characters of all occurance. Using this syntax REPLACE(string_expression, search_string, replacement_string), where every incidence of search_string found in the string_expression will be replaced with replacement_string. Using query analyzer, name 3 ways to get an accurate count of the number of records in a table? SELECT * FROM table1 SELECT COUNT(*) FROM table1 SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2

How to rebuild Master Database? Shutdown Microsoft SQL Server 2000, and then run Rebuildm.exe. This is located in the Program Files\Microsoft SQL Server\80\Tools\Binn directory. In the Rebuild Master dialog box, click Browse. In the Browse for Folder dialog box, select the \Data folder on the SQL Server 2000 compact disc or in the shared network directory from which SQL Server 2000 was installed, and then click OK. Click Settings. In the Collation Settings dialog box, verify or change settings used for the master database and all other databases. Initially, the default collation settings are shown, but these may not match th e collation selected during setup. You can select the same settings used during setup or select new collation settings. When done, click OK. In the Rebuild Master dialog box, click Rebuild to start the process. The Rebuild Master utility reinstalls the master database. To continue, you may need to stop a server that is running. Source: http://msdn2.microsoft.com/en-us/library/aa197950(SQL.80).aspx What is the basic functions for master, msdb, model, tempdb databases? The Master database holds information for all databases located on the SQL Server instance and is the glue that holds the engine together. Because SQL Server cannot start without a functioning master database, you must administer this database with care. The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping. The tempdb holds temporary objects such as global and local temporary tables and stored procedures. The model is essentially a template database used in the creation of any new user database created in the instance. What are primary keys and foreign keys? Primary keys are the unique identifiers for each row. They must contain unique values and cannot be null. Due to their importance in relational databases, Primary keys are the most fundamental of all keys and constraints. A table can have only one Primary key. Foreign keys are both a method of ensuring data integrity and a manifestation of the relationship between tables. What is data integrity? Explain constraints? Data integrity is an important feature in SQL Server. When used properly, it ensures that data is http://www.sqlauthority.com http://www.sqlauthority.com accurate, correct, and valid. It also acts as a trap for otherwise undetectable bugs within applications. A PRIMARY KEY constraint is a unique identifier for a row within a database table. Every table should have a primary key constraint to uniquely identify each row and only one primary key constraint can be created for each table. The primary key constraints are used to enforce entity integrity.

A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no duplicate values are entered. The unique key constraints are used to enforce entity integrity as the primary key constraints. A FOREIGN KEY constraint prevents any actions that would destroy links between tables with the corresponding data values. A foreign key in one table p oints to a primary key in another table. Foreign keys prevent actions that would leave rows with foreign key values when there are no primary keys with that value. The foreign key constraints are used to enforce referential integrity. A CHECK constraint is used to limit the values that can be placed in a column. The check constraints are used to enforce domain integrity. A NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to enforce domain integrity, as the check constraints. What are the properties of the Relational tables? Relational tables have six properties: y Values are atomic. y Column values are of the same kind. y Each row is unique. y The sequence of columns is insignificant. y The sequence of rows is insignificant. y Each column must have a unique name. What is De-normalization? De-normalization is the process of attempting to optimize the performance of a database by adding redundant data. It is sometimes necessary because current DBMSs implement the relational model poorly. A true relational DBMS would allow for a fully normalized database at the logical level, while providing physical storage of data that is tuned for high performance. De -normalization is a technique to move from higher to lower normal forms of database modeling in order to speed up database access. How to get @@error and @@rowcount at the same time? If @@Rowcount is checked after Error checking statement then it will have 0 as the value of @@Recordcount as it would have been reset. And if @@Recordcount is checked before the error -checking statement then @@Error would get reset. To get @@error and @@rowcount at the same time do both in same statement and store them in local variable. SELECT @RC = @@ROWCOUNT, @ER = @@ERROR What is Identity? Identity (or AutoNumber) is a column that automatically generates numeric values. A start and increment value can be set, but most DBA leave these at 1. A GUID column also generates numbers, the value of this cannot be controled. Identity /GUID columns do not need to be indexed. What is a Scheduled Jobs or What is a Scheduled Tasks? Scheduled tasks let user automate processes that run on regular or predictable cycles. User can schedule administrative tasks, such as cube processing, to run during times of slow business activity.

User can also determine the order in which tasks run by creating job steps within a SQL Server Agent job. E.g. Back up database, Update Stats of Tables. Job steps give user control over flow of execution. http://www.sqlauthority.com http://www.sqlauthority.com If one job fails, user can configure SQL Server Agent to continue to run the remaining tasks or to stop execution. What is a table called, if it does not have neither Cluster nor Non -cluster Index? What is it used for? Unindexed table or Heap. Microsoft Press Books and Book On Line (BOL) refers it as Heap. A heap is a table that does not have a clustered index and, therefore, the pages are not linked by pointers. The IAM pages are the only structures that link the pages in a table together. Unindexed tables are good for fast storing of data. Many times it is better to drop all indexes from table and than do bulk of inserts and to restore those indexes after that. What is BCP? When does it used? BulkCopy is a tool used to copy huge amount of data from tables and views. BCP does not copy the structures same as source to destination. How do you load large data to the SQL server database? BulkCopy is a tool used to copy huge amount of data from tables. BULK INSERT command helps to Imports a data file into a database table or view in a user-specified format. Can we rewrite subqueries into simple select statements or with joins? Subqueries can often be re-written to use a standard outer join, resulting in faster performance. As we may know, an outer join uses the plus sign (+) operator to tell the database to return all non-matching rows with NULL values. Hence we combine the outer join with a NULL test in the WHERE clause to reproduce the result set without using a sub -query. Can SQL Servers linked to other servers like Oracle? SQL Server can be lined to any server provided it has OLE-DB provider from Microsoft to allow a link. E.g. Oracle has a OLE-DB provider for oracle that Microsoft provides to add it as linked server to SQL Server group. How to know which index a table is using? SELECT table_name,index_name FROM user_constraints How to copy the tables, schema and views from one SQL server to another? Microsoft SQL Server 2000 Data Transformation Services (DTS) is a set of graphical tools and programmable objects that lets user extract, transform, and consolidate data from disparate sources into single or multiple destinations. What is Self Join? This is a particular case when one table joins to itself, with one or two aliases to avoid confusion. A self join can be of any type, as long as the joined tables are the same. A self join is rather unique in that it involves a relationship with only one table. The common example is when company have a hierarchal

reporting structure whereby one member of staff reports to another. What is Cross Join? A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table. The common example is when company wants to combine each product with a pricing table to analyze each pr oduct at each price. Which virtual table does a trigger use? Inserted and Deleted. List few advantages of Stored Procedure. y Stored procedure can reduced network traffic and latency, boosting application performance. y Stored procedure execution plans can be reused, staying cached in SQL Server's memory, http://www.sqlauthority.com http://www.sqlauthority.com reducing server overhead. y Stored procedures help promote code reuse. y Stored procedures can encapsulate logic. You can change stored procedure code without affecting clients. y Stored procedures provide better security to your data. What is DataWarehousing? y Subject-oriented, meaning that the data in the database is organized so that all the data elements relating to the same real-world event or object are linked together; y Time-variant, meaning that the changes to the data in the database are tracked and recorded so that reports can be produced showing changes over time; y Non-volatile, meaning that data in the database is never over-written or deleted, once committed, the data is static, read-only, but retained for future reporting; y Integrated, meaning that the database contains data from most or all of an organization's operational applications, and that this data is made consistent. What is OLTP(OnLine Transaction Processing)? In OLTP - online transaction processing systems relational database design use the discipline of data modeling and generally follow the Codd rules of data normalization in order to ensure absolute data integrity. Using these rules complex information is broken down into its most simple structures (a table) where all of the individual atomic level elements relate to each other and satisfy the normalization rules. How do SQL server 2000 and XML linked? Can XML be used to a ccess data? FOR XML (ROW, AUTO, EXPLICIT) You can execute SQL queries against existing relational databases to return results as XML rather than standard rowsets. These queries can be executed directly or from within stored procedures. To retrieve XML results, use the FOR XML clause of the SELECT statement and specify an XML mode of RAW, AUTO, or EXPLICIT. OPENXML

OPENXML is a Transact-SQL keyword that provides a relational/rowset view over an inmemory XML document. OPENXML is a rowset provider similar to a table or a view. OPENXML provides a way to access XML data within the Transact-SQL context by transferring data from an XML document into the relational tables. Thus, OPENXML allows you to manage an XML document and its interaction with the relational environment. What is an execution plan? When would you use it? How would you view the execution plan? An execution plan is basically a road map that graphically or textually shows the data retrieval methods chosen by the SQL Server query optimizer for a stored procedure or ad-hoc query and is a very useful tool for a developer to understand the performance characteristics of a query or stored procedure since the plan is the one that SQL Server will place in its cache and use to execute the stored procedure or query. From within Query Analyzer is an option called "Show Execution Plan" (located on the Query drop-down menu). If this option is turned on it will display query execution plan in separate window when query is ran again.

You might also like