JDBC Resources and Connection Pool : Explain

JDBC Resources

A JDBC resource (data source) provides applications with a means of connecting to a database. Typically, the administrator creates a JDBC resource for each database accessed by the applications deployed in a domain. (However, more than one JDBC resource can be created for a database.)

 

JDBC Resources

To store, organize, and retrieve data, most applications use relational databases. J2EE applications access relational databases through the JDBC API.

To create a JDBC resource, specify a unique JNDI name that identifies the resource. (See the section JNDI Names and Resources.) Expect to find the JNDI name of a JDBC resource in java:comp/env/jdbc subcontext. For example, the JNDI name for the resource of a payroll database could be java:comp/env/jdbc/payrolldb. Because all resource JNDI names are in the java:comp/env subcontext, when specifying the JNDI name of a JDBC resource in the Admin Console, enter only jdbc/name. For example, for a payroll database specify jdbc/payrolldb.

JDBC Connection Pools

To create a JDBC resource, specify the connection pool with which it is associated. Multiple JDBC resources can specify a single connection pool.

A JDBC connection pool is a group of reusable connections for a particular database. Because creating each new physical connection is time consuming, the server maintains a pool of available connections to increase performance. When an application requests a connection, it obtains one from the pool. When an application closes a connection, the connection is returned to the pool.

The properties of connection pools can vary with different database vendors. Some common properties are the database’s name (URL), user name, and password.

How JDBC Resources and Connection Pools Work Together

To store, organize, and retrieve data, most applications use relational databases. Java EE applications access relational databases through the JDBC API. Before an application can access a database, it must get a connection.

At runtime, here’s what happens when an application connects to a database:

  1. The application gets the JDBC resource (data source) associated with the database by making a call through the JNDI API.

    Given the resource’s JNDI name, the naming and directory service locates the JDBC resource. Each JDBC resource specifies a connection pool.

  2. Via the JDBC resource, the application gets a database connection.

    Behind the scenes, the application server retrieves a physical connection from the connection pool that corresponds to the database. The pool defines connection attributes such as the database name (URL), user name, and password.

  3. Now that it’s connected to the database, the application can read, modify, and add data to the database.

    The applications access the database by making calls to the JDBC API. The JDBC driver translates the application’s JDBC calls into the protocol of the database server.

  4. When it’s finished accessing the database, the application closes the connection.

    The application server returns the connection to the connection pool. Once it’s back in the pool, the connection is available for the next application.

    Sun Java System JDBC Driver for Oracle 8.1.7 and 9.x Databases

    The JAR files for this driver are smbase.jar, smoracle.jar, and smutil.jar. Configure the connection pool using the following settings:

    • Name: Use this name when you configure the JDBC resource later.

    • Resource Type: Specify the appropriate value.

    • Database Vendor: Oracle

    • DataSource Classname: com.sun.sql.jdbcx.oracle.OracleDataSource

    • Properties:

      • serverName – Specify the host name or IP address of the database server.

      • portNumber – Specify the port number of the database server.

      • SID – Set as appropriate.

      • user – Set as appropriate.

      • password – Set as appropriate.

    • URL: jdbc:sun:oracle://serverName[:portNumber][;SID=databaseName]


    Sun Java System JDBC Driver for Microsoft SQL Server Databases

    The JAR files for this driver are smbase.jar, smsqlserver.jar, and smutil.jar. Configure the connection pool using the following settings:

    • Name: Use this name when you configure the JDBC resource later.

    • Resource Type: Specify the appropriate value.

    • Database Vendor: mssql

    • DataSource Classname: com.sun.sql.jdbcx.sqlserver.SQLServerDataSource

    • Properties:

      • serverName – Specify the host name or IP address and the port of the database server.

      • portNumber – Specify the port number of the database server.

      • user – Set as appropriate.

      • password – Set as appropriate.

      • selectMethod – Set to cursor.

    • URL: jdbc:sun:sqlserver://serverName[:portNumber]

Explain JIT

Just-In-Time Compilers

The simplest tool used to increase the performance of your application is the Just-In-Time (JIT) compiler. A JIT is a code generator that converts Java bytecode into native machine code. Java programs invoked with a JIT generally run much faster than when the bytecode is executed by the interpreter. The Java Hotspot VM removes the need for a JIT compiler in most cases however you may still find the JIT compiler being used in earlier releases.

The JIT compiler was first made available as a performance update in the Java Development Kit (JDK) 1.1.6 software release and is now a standard tool invoked whenever you use the java interpreter command in the Java 2 platform release. You can disable the JIT compiler using the -Djava.compiler=NONE option to the Java VM. This is covered in more detail at the end of the JIT section.

How do JIT Compilers work?

JIT compilers are supplied as standalone platform-dependent native libraries. If the JIT Compiler library exists, the Java VM initializes Java Native Interface (JNI) native code hooks to call JIT functions available in that library instead of the equivalent function in the interpreter.

The java.lang.Compiler class is used to load the native library and start the initialization inside the JIT compiler.

When the Java VM invokes a Java method, it uses an invoker method as specified in the method block of the loaded class object. The Java VM has several invoker methods, for example, a different invoker is used if the method is synchronized or if it is a native method.

The JIT compiler uses its own invoker. Sun production releases check the method access bit for value ACC_MACHINE_COMPILED to notify the interpreter that the code for this method has already been compiled and stored in the loaded class.

When does the code become JIT compiled code?

When a method is called the first time the JIT compiler compiles the method block into native code for this method and stored that in the code block for that method.

Once the code has been compiled the ACC_MACHINE_COMPILED bit, which is used on the Sun platform, is set.

How Synchronization impacts performance

  • Avoid synchronization where possible.
  • ArrayList is faster than Vector
  • Only List and Map have efficient thread-safe implementations: the Vector and Hashtable classes respectively.
  • Synchronized methods are slower than the identical non-synchronized one.
  • Consider using non-synchronized classes and synchronized-wrappers.
  • FastVector is faster than Vector by making the elementData field public, thus avoiding (synchronized) calls to elementAt().
  • Use threads. Prioritize threads. Use notify instead of notifyAll. Use synchronization sparingly.
  • use methods in order: static > final > instance > interface > synchronized
  • Because synchronization synchronizes thread memory with main memory, there is a cost to synchronization beyond simply acquiring a lock.
  • Make synchronized blocks as short as possible.
  • Spread synchronizations over more than one lock.
  • Minimizing synchronization may take work, but can pay off well.
  • Minimize the synchronized block in the service method.

How to improve Servlet performance

  • Use the servlet init() method to cache static data, and release them in the destroy() method.
  • Use StringBuffer rather than using + operator when you concatenate multiple strings.
  • Use the print() method rather than the println() method.
  • Use a ServletOutputStream rather than a PrintWriter to send binary data.
  • Initialize the PrintWriter with the optimal size for pages you write.
  • Flush the data in sections so that the user can see partial pages more quickly.
  • Minimize the synchronized block in the service method.
  • Implement the getLastModified() method to use the browser cache and the server cache.
  • Use the application server’s caching facility.
  • Session mechanisms from fastest to slowest are: HttpSession, Hidden fields, Cookies, URL rewriting, the persistency mechanism.
  • Remove HttpSession objects explicitly in your program whenever you finish the session.
  • Set the session time-out value as low as possible.
  • Use transient variables to reduce serialization overheads.
  • Disable the servlet auto reloading feature.
  • Tune the thread pool size.

How to Improve JSP Page performance

  • Use the jspInit() method to cache static data, and release them in the jspDestroy() method.
  • Use the jspInit() method to cache static data.
  • Use StringBuffer rather than using + operator when you concatenate multiple strings.
  • Use the print() method rather than the println() method.
  • Use a ServletOutputStream rather than a PrintWriter to send binary data.
  • Initialize the PrintWriter with the optimal size for pages you write.
  • Flush the data in sections so that the user can see partial pages more quickly.
  • Minimize the synchronized block in the service method.
  • Avoid creating a session object with the directive <%@ page session=”false” %>
  • Increase the buffer size of System.out with the directive <%@ page buffer=”12kb” %>
  • Use the include directive instead of the include action when you want to include another page.
  • Minimize the scope of the ‘useBean’ action.
  • Custom tags incur a performance overhead. Use as few as possible.
  • Use the application server’s caching facility, and the session and application objects (using getAttribute()/setAttribute()). There are also third-party caching tags available.
  • Session mechanisms from fastest to slowest are: session, Hidden fields, Cookies, URL rewriting, the persistency mechanism.
  • Remove ’session’ objects explicitly in your program whenever you finish the session.
  • Reduce the session time-out as low as possible.
  • Use ‘transient’ variables to reduce serialization overheads.
  • Disable the JSP auto reloading feature.
  • Tune the thread pool size.

Design Patterns : Performance

  • use the flyweight pattern to reduce object creation [The flyweight pattern uses a factory instead of 'new' to reuse objects rather than always create new ones].
  • The Singleton pattern and the Flyweight (object factory) pattern are useful to limit numbers of objects of various types and to assist with object reuse and reduce garbage collection.
  • Use the Data Access Object pattern to decouple business logic from data access logic, allowing for optimizations to be made in how data is managed.
  • Use the Fast-Lane Reader pattern to accelerate read-only data access by not using enterprise beans.
  • Use the Front Controller pattern to centralize incoming client requests, allowing optimizations to be made in aggregating the resulting view.
  • Use the Front Controller pattern to channel all client requests through a single decision point, which allows the application to be balanced at runtime.
  • Use the Page-by-Page Iterator pattern to efficiently access a large, remote list by retrieving its elements one sublist of value objects at a time.
  • Use the Session Facade pattern to provide a unified, workflow-oriented interface to a set of enterprise beans, thus minimizing client calls to server EJBs.
  • Use a Session Facade to provide a simple interface to a complex subsystem of enterprise beans, and to reduce network communication requirements
  • Use the Value Object pattern to efficiently transfer remote, fine-grained data by sending a coarse-grained view of the data.
  • Use the factory pattern to enable reuse or cloning of objects
  • The Abstract Factory design pattern uses a single class to create more than one kind of object.
  • An alternative to the Flyweight pattern is the Prototype pattern, which allows polymorphic copies of existing objects. The Object.clone() method signature provides support for the Prototype pattern.
  • Prototypes are useful when object initialization is expensive, and you anticipate few variations on the initialization parameters. Then you could keep already-initialized objects in a table, and clone an existing object instead of expensively creating a new one from scratch.
  • Immutable objects can be returned directly when using Prototyping, avoiding the copying overhead.
  • Combine multiple remote calls for state information into one call using a value object to wrap the data (the Value Object pattern, superceded by local interfaces in EJB 2.0).
  • Where long lists of data are returned by queries, use the Page-by-Page Iterator pattern: a server-side object that holds data on the server and supplies batches of results to the client.
  • When the client would request many small data items which would require many remote calls to satisfy, combine the multiple calls into one call which results in a single Value Object which holds all the data required to be transferred. Use the Value Object to send a single coarse-grained object from the server to the client(s).
  • For read-only access to a set of data that does not change rapidly, use the Fast Lane Reader pattern which bypasses the EJBs and uses a (possibly non-transactional) data access object which encapsulates access to the data. Use the Fast Lane Reader to read data from the server and display all of them in one shot.
  • Wrap multiple entity beans in a session bean to change multiple EJB remote calls into one session bean remote call and several local calls (pattern called SessionFacade).
  • Cache EJBHome references to avoid JNDI lookup overhead (pattern called ServiceLocator).
  • The ServiceLocator/EJBHomeFactory Pattern reduces the expensive JNDI lookup process by caching EJBHome objects.
  • The SessionFacade Pattern reduces network calls by combining accesses to multiple Entity beans into one access to the facade object.
  • The MessageFacade/ServiceActivator Pattern moves method calls into a separate object which can execute asynchronously.
  • The ValueObject Pattern combines remote data into one serializable object, thus reducing the number of network transfers required to access multiple items of remote data.
  • The ValueObjectFactory/ValueObjectAssembler Pattern combines remote data from multiple remote objects into one serializable object, thus reducing the number of network transfers required to access multiple items of remote data.
  • The ValueListHandler Pattern: avoids using multiple Entity beans to access the database, using Data Access Objects which explicitly query the database; and returns the data to the client in batches (which can be terminated) rather than in one big chunk, according to the Page-by-Page Iterator pattern.
  • The CompositeEntity Pattern reduces the number of actual entity beans by wrapping multiple java objects (which could otherwise be Entity beans) into one Entity bean.
  • The Recycler pattern fixes only the broken parts of a failed object, to minimize the replacement cost.
  • Use a factory class instead of directly calling the “new” operator, to allow easier reuse of objects.
  • Instead of making lots of remote requests for data attributes of an object, combine the attributes into another object and send the object to the client. Then the attributes can be queried efficiently locally (this is called the Value Object pattern). Consider caching the value objects where appropriate.
  • The Proxy design pattern
    • Using a proxy, you can delay image loading until the image is required.
    • The Proxy pattern often instantiates its real object, the Decorator pattern (which can also use proxy objects) rarely does.
    • The java.lang.reflect package provides three classes to support the Proxy and Decorator patterns: Proxy, Method, and InvocationHandler.

How to Improve the Java JDBC Performance

  • Use prepared statements. Use parametrized SQL.
  • Tune the SQL to minimize the data returned (e.g. not ‘SELECT *’).
  • Minimize transaction conflicts (e.g. locked rows).
  • Use connection pooling.
  • Try to combine queries and batch updates.
  • Use stored procedures.
  • Cache data to avoid repeated queries.
  • Close resources (Connections, Statements, ResultSets) when finished with.
  • Select the fastest JDBC driver.
  • If you are not using stored procedures or triggers, turn off autocommit. All transaction levels operate faster with autocommit turned off, and doing this means you must code commits.
  • Use connection pooling, either explicitly with your own implementation, or implicitly via a product that supports connection pooling.
  • Use batch updates (sending multiple rows to the database in one call).
  • Use the type-correct get() method, rather than getObject().
  • Avoid n-way database joins: every join has a multiplicative effect on the amount of work the database has to do. The performance degradation may not be noticeable until large datasets are involved.
  • Avoid bringing back thousands of rows of data: this can use a disproportionate amount of resources.
  • Run an application server and any database servers on separate server machines.
  • One of the most time-consuming procedures of a database application is establishing a connection to the database. Use connection pooling to minimize this overhead
  • Use the same connection to execute multiple statements
  • Avoid distributed transactions (transactions that span mutliple connections).
  • Use scrollable ResultSet (JDBC 2.0).
  • Oracle 9i includes queryable snapshots of the main database which can offload the query to run against the clients local snapshot.
  • Performance should be considered at the start of a project
  • Given a simple SQL statement and a stored procedure call that accomplishes the same task, the simple SQL statement will always execute faster because the stored procedure executes the same SQL statement but also has the overhead of the procedure call itself. On the other hand complex tasks requiring several SQL statements can be faster using stored procedures as fewer network trips and data transfers will be needed.
  • Performance can be better if changes to the database are batched: turn off autocommit; add multiple SQL statements using the Statement.addBatch() method; execute Statement.executeBatch().
  • The ConnectionPoolDataSource (from JDBC3.0) and PooledConnection interfaces provide built-in support for connection pools.
  • Use Connection.setReadOnly(true) to optimize read-only database interactions.
  • Use Connection.nativeSQL() to see how the SQL query will execute in the database to help ensure that the SQL is optimized.
  • Use Connection.nativeSQL() to see how the SQL query will execute in the database to help ensure that the SQL is optimized.
  • Commit the data after the transaction completes rather than after each method call
  • Use the fastest driver available to the database: normally type 4 (preferably) or type 3.
  • Use the Page-by-Page Iterator pattern to repeatedly pass small amounts of data rather than huge chunks.
  • Reusing connections allows a prepared statement to be reused.
  • Database connection pools can take one of two strategies: a limited size pool, where attempts to make connections beyond the pool size must wait for a connection to become idle; or a flexible sized pool with a preferred size which removes idle connections as soon as the preferred size is exceeded (i.e. temporarily able to exceed the preferred size). The fixed size pool is generally considered to be the better choice.
  • Avoid the following common mistakes: Failure to close JDBC result sets, statements, and connections; Failure to remove unused stateful session beans; Failure to invalidate HttpSession.
  • CachedRowSet provides cached result sets that do not require continuous connection to the database, allowing connections to be reused more efficiently.
  • Reuse database connections using a connection pool.
  • Obtain and release pooled conections within each method that requires the resource if the connection is very short (termed “Quick Catch-and-Release Strategy” in the article). However do not release the connection only to use it again almost immediately, instead hold the connection until it will not be immediately needed.
  • Response time increasing too much when database is over populated probably indicates lack of or inappropriate indexing on the database.
  • Use SQL clause with EXPLAIN or similar (e.g. “Explain select * from table where tablefield = somevalue”) to ensure that the database is doing an indexed search rather than a linear searches of large datasets.

dojo Charts: addSeries()

<html >
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
<title>Untitled 1</title>
<script type=”text/javascript” src= “../js/dojo/dojo/dojo.js” djConfig=”isDebug: true”></script>
<script type=”text/javascript”>
dojo.require(“dojox.charting.Chart2D”);
makeCharts = function(){
var chart1 = new dojox.charting.Chart2D(“simplechart”);
chart1.addPlot(“default”, {type: “Lines”});
chart1.addPlot(“other”, {type: “Areas”, hAxis: “other x”, vAxis: “other y”});
chart1.addPlot(“Grid”, {type: “Grid”, hAxis: “other x”,    vAxis: “other y”,hMajorLines: true,    hMinorLines: false,    vMajorLines: true,    vMinorLines: false});
chart1.addAxis(“x”, {
    labels: [{value: 1, text: "Jan"}, {value: 2, text: "Feb"},
        {value: 3, text: "Mar"}, {value: 4, text: "Apr"},
        {value: 5, text: "May"}, {value: 6, text: "Jun"},
        {value: 7, text: "Jul"}, {value: 8, text: "Aug"},
        {value: 9, text: "Sep"}, {value: 10, text: "Oct"},
        {value: 11, text: "Nov"}, {value: 12, text: "Dec"}]
    });
chart1.addAxis(“y”, {vertical: true});
chart1.addAxis(“other x”, {leftBottom: false});
chart1.addAxis(“other y”, {vertical: true,
    leftBottom: false,
    max: 7,
    stroke: “green”,
    font: “normal normal bold 14pt Tahoma”,
    fontColor: “red”,
    majorTick: {color: “red”, length: 6},
    minorTick: {stroke: “black”, length: 3}
});
chart1.addSeries(“Series 1″, [1, 2, 4, 5, 5, 7], {stroke: {color: “blue”, width: 2},
    fill: “lightblue”});
    chart1.addSeries(“Series 2″, [1, 1, 4, 2, 1, 6, 4, 3],
        {plot: “other”, stroke: {color:”blue”}, fill: “lightblue”}
);

chart1.render();

};
dojo.addOnLoad(makeCharts);
</script>
</head>
<body>
<div id=”simplechart” style=”width: 250px; height: 150px;”></div>
</body>
</html>

Output:

image

dojo Charts: Add Grids

<html >

<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
<title>Untitled 1</title>
<script type=”text/javascript” src= “../js/dojo/dojo/dojo.js” djConfig=”isDebug: true”></script>
<script type=”text/javascript”>
dojo.require(“dojox.charting.Chart2D”);
makeCharts = function(){
var chart1 = new dojox.charting.Chart2D(“simplechart”);
chart1.addPlot(“default”, {type: “Lines”});
chart1.addPlot(“other”, {type: “Areas”, hAxis: “other x”, vAxis: “other y”});
chart1.addPlot(“Grid”, {type: “Grid”, hAxis: “other x”,    vAxis: “other y”,hMajorLines: true,    hMinorLines: false,    vMajorLines: true,    vMinorLines: false});
chart1.addAxis(“y”, {vertical: true});
chart1.addAxis(“other x”, {leftBottom: false});
chart1.addAxis(“other y”, {vertical: true,
    leftBottom: false,
    max: 7,
    stroke: “green”,
    font: “normal normal bold 14pt Tahoma”,
    fontColor: “red”,
    majorTick: {color: “red”, length: 6},
    minorTick: {stroke: “black”, length: 3}
});
chart1.addSeries(“Series 1″, [1, 2, 2, 3, 4, 5, 5, 7]);
chart1.addSeries(“Series 2″, [1, 1, 4, 2, 1, 6, 4, 3],
        {plot: “other”, stroke: {color:”blue”}, fill: “lightblue”}
);
chart1.render();

};
dojo.addOnLoad(makeCharts);
</script>
</head>
<body>
<div id=”simplechart” style=”width: 250px; height: 150px;”></div>
</body>
</html>

Output:

image

dojo Charts: Coloring Axis

<html>

<head runat=”server”>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
<title>Untitled 1</title>
<script type=”text/javascript” src= “../js/dojo/dojo/dojo.js” djConfig=”isDebug: true”></script>
<script type=”text/javascript”>
dojo.require(“dojox.charting.Chart2D”);
makeCharts = function(){
var chart1 = new dojox.charting.Chart2D(“simplechart”);
chart1.addPlot(“default”, {type: “Lines”});
chart1.addPlot(“other”, {type: “Areas”, hAxis: “other x”, vAxis: “other y”});
chart1.addAxis(“x”);
chart1.addAxis(“y”, {vertical: true});
chart1.addAxis(“other x”, {leftBottom: false});
chart1.addAxis(“other y”, {vertical: true,
    leftBottom: false,
    max: 7,
    stroke: “green”,
    font: “normal normal bold 14pt Tahoma”,
    fontColor: “red”,
    majorTick: {color: “red”, length: 6},
    minorTick: {stroke: “black”, length: 3}
});
chart1.addSeries(“Series 1″, [1, 2, 2, 3, 4, 5, 5, 7]);
chart1.addSeries(“Series 2″, [1, 1, 4, 2, 1, 6, 4, 3],
        {plot: “other”, stroke: {color:”blue”}, fill: “lightblue”}
);
chart1.render();

};
dojo.addOnLoad(makeCharts);
</script>
</head>
<body>
<div id=”simplechart” style=”width: 250px; height: 150px;”></div>
</body>
</html>

Output:

image

dojo Charts: addAxis()

<html>

<head runat=”server”>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
<title>Untitled 1</title>
<script type=”text/javascript” src= “../js/dojo/dojo/dojo.js” djConfig=”isDebug: true”></script>
<script type=”text/javascript”>
dojo.require(“dojox.charting.Chart2D”);
makeCharts = function(){
var chart1 = new dojox.charting.Chart2D(“simplechart”);
chart1.addPlot(“default”, {type: “Lines”});
chart1.addPlot(“other”, {type: “Areas”, hAxis: “other x”, vAxis: “other y”});
chart1.addAxis(“x”);
chart1.addAxis(“y”, {vertical: true});
chart1.addAxis(“other x”, {leftBottom: false});
chart1.addAxis(“other y”, {vertical: true, leftBottom: false});
chart1.addSeries(“Series 1″, [1, 2, 2, 3, 4, 5, 5, 7]);
chart1.addSeries(“Series 2″, [1, 1, 4, 2, 1, 6, 4, 3],
        {plot: “other”, stroke: {color:”blue”}, fill: “lightblue”}
);
chart1.render();

};
dojo.addOnLoad(makeCharts);
</script>
</head>
<body>
<div id=”simplechart” style=”width: 250px; height: 150px;”></div>
</body>
</html>

Output:

image

dojo Charts: Multiple Plots

<html>

<head runat=”server”>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
<title>Untitled 1</title>
<script type=”text/javascript” src= “../js/dojo/dojo/dojo.js” djConfig=”isDebug: true”></script>
<script type=”text/javascript”>
dojo.require(“dojox.charting.Chart2D”);
makeCharts = function(){
    var chart1 = new dojox.charting.Chart2D(“simplechart”);
chart1.addPlot(“default”, {type: “Lines”});
chart1.addPlot(“other”, {type: “Areas”});
chart1.addAxis(“x”);
chart1.addAxis(“y”, {vertical: true});
chart1.addSeries(“Series 1″, [1, 2, 2, 3, 4, 5, 5, 7]);
chart1.addSeries(“Series 2″, [1, 1, 4, 2, 1, 6, 4, 3], {plot: “other”, stroke: {color:”blue”}, fill: “lightblue”});
chart1.render();
};
dojo.addOnLoad(makeCharts);
</script>
</head>
<body>
<div id=”simplechart” style=”width: 250px; height: 150px;”></div>
</body>
</html>

Output:

image

dojo Charts: Advanced Line Chart

<html>

<head runat=”server”>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
<title>Untitled 1</title>
<script type=”text/javascript” src= “../js/dojo/dojo/dojo.js” djConfig=”isDebug: true”></script>
<script type=”text/javascript”>
dojo.require(“dojox.charting.Chart2D”);
makeCharts = function(){
    var chart1 = new dojox.charting.Chart2D(“simplechart”);
    chart1.addPlot(“default”, {type: “Lines”, markers: true, tension:3, shadows: {dx: 2, dy: 2, dw: 2}});
    chart1.addAxis(“x”);
    chart1.addAxis(“y”, {vertical: true});
    chart1.addSeries(“Series 1″, [1, 2, 2, 3, 4, 5, 5, 7]);
    chart1.render();
};
dojo.addOnLoad(makeCharts);
</script>
</head>
<body>
<div id=”simplechart” style=”width: 250px; height: 150px;”></div>
</body>
</html>

Output:

image

dojo Charts: Area Chart

<html>

<head runat=”server”>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
<title>Untitled 1</title>
<script type=”text/javascript” src= “../js/dojo/dojo/dojo.js” djConfig=”isDebug: true”></script>
<script type=”text/javascript”>
dojo.require(“dojox.charting.Chart2D”);
makeCharts = function(){
    var chart1 = new dojox.charting.Chart2D(“simplechart”);
    chart1.addPlot(“default”, {type: “Areas”});
    chart1.addAxis(“x”);
    chart1.addAxis(“y”, {vertical: true});
    chart1.addSeries(“Series 1″, [1, 2, 2, 3, 4, 5, 5, 7]);
    chart1.render();
};
dojo.addOnLoad(makeCharts);
</script>
</head>
<body>
<div id=”simplechart” style=”width: 250px; height: 150px;”></div>
</body>
</html>

output:

image

dojo Charts: Line Chart

 

<html>

<head runat=”server”>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
<title>Untitled 1</title>
<script type=”text/javascript” src= “../js/dojo/dojo/dojo.js” djConfig=”isDebug: true”></script>
<script type=”text/javascript”>
dojo.require(“dojox.charting.Chart2D”);
makeCharts = function(){
    var chart1 = new dojox.charting.Chart2D(“simplechart”);
    chart1.addPlot(“default”, {type: “Lines”});
    chart1.addAxis(“x”);
    chart1.addAxis(“y”, {vertical: true});
    chart1.addSeries(“Series 1″, [1, 2, 2, 3, 4, 5, 5, 7]);
    chart1.render();
};
dojo.addOnLoad(makeCharts);
</script>
</head>
<body>
<div id=”simplechart” style=”width: 250px; height: 150px;”></div>
</body>
</html>

 

Output:

 

image

Web Page Performance : How To Improve it

Code Reviews : Different Types

Automated Reviews

Automate the review where possible. A review conducted by a computer has several benefits:

  • Reduced manual cost of code reviews
  • Fast, consistent, and repeatable
  • Removes emotion from the reviews: pride, ego, and ownership need to be constantly recognized when conducting a review. When offering a critique you should take care to not to step on the author’s feelings. Using an automated process abdicates this responsibility.
  • In some cases you have tools that allow for real-time reviews, such as the Eclipse plug-in CodePro Analytix. These tools perform an examination of the code as it is being written. This is the holy grail of fixing broken windows.

The benefits notwithstanding, it must be acknowledged that the scope of automated reviews is limited to rules and conventions and are hard to extend to study business logic. The latter have to be handled by manual (or peer) examination.

Manual Reviews

From the prior sections you have seen that interactive and build-time tools at your disposal, while a great boon to the review process, cannot substitute for manual review for a certain class of problems. You have to manually review for certain types of improper coding practices. Tools cannot highlight errors of omission as described in the earlier section. Given that, let’s see how a manual review must be conducted.

Participants: The review must focus on different facets of code correctness. Therefore, the participants of a code review must be chosen to satisfy a diverse set of roles.

  • Technical lead: S/he plays the role of the facilitator and moderator
  • The author(s)
  • Quality Assurance: This role focuses on ensuring that the code under examination satisfies the set standards
  • Functional expert: The person who is an expert in the business domain being reviewed

How to conduct: The technical lead will work with the authors to coordinate the review. This process includes:

  • Identifying the participants in the review
  • Determining the amount of preview time
  • Providing the participants the necessary information
    • Requirement/bug fix that was implemented
    • CVS location of the files affected. The lines in the file that were affected by this change.
    • Project reports with coverage and complexity details
    • Review time duration
  • Setting up a meeting to discuss the results of the preview
    • Moderate the meeting – During the actual review the authors will describe the intent of the code and provide an overview of the implementation before the code is examined
    • Capture comments
    • Repeat above steps if necessary

Code Reviews : Purpose

Adherence to coding standards Writing to standards has several benefits, such as a shared vocabulary, which makes the code easier to reuse and maintain. One of the primary focuses of a code review is to ensure abidance with these norms. As you’ll see later, this benefit of a review is best derived in an automated manner. Such an approach has the dual benefit of a machine’s thoroughness while circumventing the cost of a manual review.

Addressing the requirements One of the key goals of a code review is to ensure that the code under scrutiny is feature-complete. Beautiful code that fails to meet user requirements is useless. The review must ensure that the logic does what it is called upon to do.

Code correctness Ensure that the authors are following proper programming techniques as appropriate:

  • Object orientation: Be on the lookout for monolithic, jack-of-all-trades methods.
  • Code reuse: Promote the use of tried and tested (and debugged) APIs and avoid code duplication by recommending the use of available APIs.
  • Adequate and proper documentation: Ensure that the code is amply commented. This is especially important when the logic is complex. Such inline documentation must explain what is being done and not how it is being done.
  • Defensive coding practices: See any number of online resources.
  • Maintainability: The ability to maintain the code is assessed from documentation and code organization.

Errors and omissions A well-written code fragment that abides by all the departmental norms, satisfies requirements, and otherwise “stays within the lines” could still be in error. It is the task of the reviewer to make sure that the code does not make incorrect business/usage assumptions and that all possible usage scenarios are taken into account. A business process expert helping with the review will be quick to spot logic that presupposes the state of the application while the logic is executed. For example, an application that allows guest users cannot be guaranteed to know the current user’s identity.

Test for coverage. Test coverage is a measure of the quality of testing. Tools like Maven and CruiseControl simplify the process of testing and auditing coverage reports. The reviewer must understand the significance of branch and path coverage.

Silo-busting pedagogical aid This tool exposes others in the team to the code. The reviewer gets to read, analyze, and discuss someone else’s work. Such cross-pollination is an excellent way to raise the skill of the entire group. This approach has the added tangential benefit of busting silos of expertise that projects tend to unwittingly foster.

Code Reviews : How To

  1. Ask questions rather than make statements. A statement is accusatory. “You didn’t follow the standard here” is an attack—whether intentional or not. The question, “What was the reasoning behind the approached you used?” is seeking more information. Obviously, that question can’t be said with a sarcastic or condescending tone; but, done correctly, it can often open the developer up to stating their thinking and then asking if there was a better way.
  2. Avoid the “Why” questions. Although extremely difficult at times, avoiding the”Why” questions can substantially improve the mood. Just as a statement is accusatory—so is a why question. Most “Why” questions can be reworded to a question that doesn’t include the word “Why” and the results can be dramatic. For example, “Why didn’t you follow the standards here…” versus “What was the reasoning behind the deviation from the standards here…”
  3. Remember to praise. The purposes of code reviews are not focused at telling developers how they can improve, and not necessarily that they did a good job. Human nature is such that we want and need to be acknowledged for our successes, not just shown our faults. Because development is necessarily a creative work that developers pour their soul into, it often can be close to their hearts. This makes the need for praise even more critical.
  4. Make sure you have good coding standards to reference. Code reviews find their foundation in the coding standards of the organization. Coding standards are supposed to be the shared agreement that the developers have with one another to produce quality, maintainable code. If you’re discussing an item that isn’t in your coding standards, you have some work to do to get the item in the coding standards. You should regularly ask yourself whether the item being discussed is in your coding standards.
  5. Make sure the discussion stays focused on the code and not the coder. Staying focused on the code helps keep the process from becoming personal. You’re not interested in saying the person is a bad person. Instead, you’re looking to generate the best quality code possible.
  6. Remember that there is often more than one way to approach a solution. Although the developer might have coded something differently from how you would have, it isn’t necessarily wrong. The goal is quality, maintainable code. If it meets those goals and follows the coding standards, that’s all you can ask for.

dojo : Debugging

 

1. Use Firebug or Firebug Lite

Firebug, an open source debugging extension for Firefox, is essential for JavaScript, HTML and CSS debugging. You can download it from the Firebug web site.

2. Logging

In Dojo logging, you can associate messages with severity, just like in log4j. The following code illustrates the five severity levels:

console.log(“Nothing happening”);
console.debug(“Checking to make sure nothing happened”);
console.info(“Something might happen.”);
console.warn(“Something happened, but it’s no big deal.”);
console.error(“Cough cough!”);

 

3. The “debugger” Statement

Alternatively you can set a “poor person’s breakpoint” in the code. Just insert the debugger; statement, which is a legal JavaScript reserved word.

debugger;
this.domNode.style.width = dojo.newWidth;

This statement stops the code and brings you to a Firebug command prompt.

dojo: Send Data by POST

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”
    “http://www.w3.org/TR/html4/strict.dtd”>
<html>
    <head>
        <title>Dojo</title>   
    <!– load the dojo toolkit base –>
    <script type=”text/javascript” src= “dojo/dojo/dojo.js”
        djConfig=”parseOnLoad:true, isDebug:true”></script>
    <script type=”text/javascript”>
       // Load Dojo’s code relating to the Button widget
       dojo.require(“dijit.form.Button”);
    </script>

<script>
       function helloCallback(data,ioArgs) {
          alert(data);
       }      
       function helloError(data, ioArgs) {
          alert(‘Error when retrieving data from the server!’);
       }
</script>

<form id=”myForm” method=”POST”>
      Please enter your name: <input type=”text” name=”name”>
    </form>

<button dojoType=”dijit.form.Button” id=”helloButton”>
        Click here to read data from the server!!
      <script type=”dojo/method” event=”onClick”>
      dojo.xhrPost({
        url: ‘SendRequestbyPOST.jsp’,
        load: helloCallback,
        error: helloError,
        form: myForm
   });
        </script>
    </button>
    <br>

    <style type=”text/css”>
    /* CSS  */ 
    .testClass {
    background-color:red;
}
    </style>   
    </head>
    <body>
        <h1 id=”testHeading”>Dojo Send Data by POST</h1>       
        <div id=”contentNode”>
        <p></p>
    </div>
    </body>
</html>

///NOTE: Create a simple jsp page to read Query String parameter : Name.
///something like: <%= request.getParameter(“name”) %>
// and name it as : SendRequestbyPOST.jsp

dojo: Send Data to the Server using Get (Query String)

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”
    “http://www.w3.org/TR/html4/strict.dtd”>
<html>
    <head>
        <title>Dojo</title>   
    <!– load the dojo toolkit base –>
    <script type=”text/javascript” src= “dojo/dojo/dojo.js”
        djConfig=”parseOnLoad:true, isDebug:true”></script>
    <script type=”text/javascript”>
       // Load Dojo’s code relating to the Button widget
       dojo.require(“dijit.form.Button”);
    </script>

<script>
       function helloCallback(data,ioArgs) {
          alert(data);
       }      
       function helloError(data, ioArgs) {
          alert(‘Error when retrieving data from the server!’);
       }
</script>

<button dojoType=”dijit.form.Button” id=”helloButton”>
        Click here to read data from the server!!
      <script type=”dojo/method” event=”onClick”>
        dojo.xhrGet({
           url: ‘ReadDojoGetResponse.aspx’,
           load: helloCallback,
           error: helloError,
           content: {name: dojo.byId(‘name’).value }
        });
        </script>
    </button>
    <br>
name: <input type=”text” id=”name”>

    <style type=”text/css”>
    /* CSS  */ 
    .testClass {
    background-color:red;
}
    </style>   
    </head>
    <body>
        <h1 id=”testHeading”>Dojo Click Button – Widgets</h1>       
        <div id=”contentNode”>
        <p></p>
    </div>
    </body>
</html>

///NOTE: Create a simple jsp page to read Query String parameter : Name.
///something like: <%= request.getParameter(“name”) %>

dojo: Read Data from Server using GET

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”
    “http://www.w3.org/TR/html4/strict.dtd”>
<html>
    <head>
        <title>Dojo</title>   
    <!– load the dojo toolkit base –>
    <script type=”text/javascript” src= “dojo/dojo/dojo.js”
        djConfig=”parseOnLoad:true, isDebug:true”></script>
    <script type=”text/javascript”>
       // Load Dojo’s code relating to the Button widget
       dojo.require(“dijit.form.Button”);
    </script>

<script>
       function helloCallback(data,ioArgs) {
          alert(data);
       }      
       function helloError(data, ioArgs) {
          alert(‘Error when retrieving data from the server!’);
       }
</script>

<button dojoType=”dijit.form.Button” id=”helloButton”>
        Click here to read data from the server!!
       <script type=”dojo/method” event=”onClick”>
   dojo.xhrGet({
        url: ‘response.txt’,
        load: helloCallback,
        error: helloError
   });
</script>
    </button>
    <style type=”text/css”>
    /* CSS  */ 
    .testClass {
    background-color:red;
}
    </style>   
    </head>
    <body>
        <h1 id=”testHeading”>Dojo Click Button – Widgets</h1>       
        <div id=”contentNode”>
        <p></p>
    </div>
    </body>
</html>

dojo: Connecting an Event to the Widget

 

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”
    “http://www.w3.org/TR/html4/strict.dtd”>
<html>
    <head>
        <title>Dojo</title>   
    <!– load the dojo toolkit base –>
    <script type=”text/javascript” src= “dojo/dojo/dojo.js”
        djConfig=”parseOnLoad:true, isDebug:true”></script>
    <script type=”text/javascript”>
       // Load Dojo’s code relating to the Button widget
       dojo.require(“dijit.form.Button”);
    </script>

<button dojoType=”dijit.form.Button” id=”helloButton”>
        Hello World!
        <script type=”dojo/method” event=”onClick”>
           alert(‘You pressed the button’);
        </script>
    </button>
    <style type=”text/css”>
    /* CSS  */ 
    .testClass {
    background-color:red;
}
    </style>   
    </head>
    <body>
        <h1 id=”testHeading”>Dojo Click Button – Widgets</h1>       
        <div id=”contentNode”>
        <p></p>
    </div>
    </body>
</html>

Dojo : Animation

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”
    “http://www.w3.org/TR/html4/strict.dtd”>
<html>
    <head>
        <title>Dojo</title>   
    <!– load the dojo toolkit base –>
    <script type=”text/javascript” src= “dojo/dojo/dojo.js”
        djConfig=”parseOnLoad:true, isDebug:true”></script>
    <script type=”text/javascript”>
dojo.addOnLoad(function(){
    var animArgs = {
    node: “testHeading”,
    duration: 1000, // ms to run animation
    delay: 250 // ms to stall before playing
    };
    dojo.fadeOut(animArgs).play();
});

    </script>
    <style type=”text/css”>
    /* CSS  */ 
    .testClass {
    background-color:red;
}
    </style>   
    </head>
    <body>
        <h1 id=”testHeading”>Dojo Animation!!</h1>       
        <div id=”contentNode”>
        <p></p>
    </div>
    </body>
</html>

Dojo : connect()

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”
    “http://www.w3.org/TR/html4/strict.dtd”>
<html>
    <head>
        <title>Dojo</title>   
    <!– load the dojo toolkit base –>
    <script type=”text/javascript” src= “dojo/dojo/dojo.js”
        djConfig=”parseOnLoad:true, isDebug:true”></script>
    <script type=”text/javascript”>
dojo.addOnLoad(function(){
    var node = dojo.byId(“testHeading”);
    dojo.connect(node,”onclick”,function(){
    node.innerHTML = “Click! Click!!”;       
    });       
});   

    </script>
    <style type=”text/css”>
    /* CSS  */ 
    .testClass {
    background-color:red;
}
    </style>   
    </head>
    <body>
        <h1 id=”testHeading”>Click Here!!</h1>       
        <div id=”contentNode”>
        <p></p>
    </div>
    </body>
</html>

Dojo : query()

 

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”
    “http://www.w3.org/TR/html4/strict.dtd”>
<html>
    <head>
        <title>Dojo</title>   
    <!– load the dojo toolkit base –>
    <script type=”text/javascript” src= “dojo/dojo/dojo.js”
        djConfig=”parseOnLoad:true, isDebug:true”></script>
    <script type=”text/javascript”>
   dojo.require(“dojo.NodeList-fx”);
  dojo.addOnLoad(function(){
    // our dom is ready, get the node:
    dojo.query(“#testHeading”)
         // add “testClass” to its class=”" attribute
        .addClass(“testClass”)
         // and fade it out after 500 ms
        .fadeOut({ delay:500 }).play();
});

    </script>
    <style type=”text/css”>
    /* CSS  */ 
    .testClass {
    background-color:red;
}
    </style>   
    </head>
    <body>
        <h1 id=”testHeading”>Dojo test</h1>       
        <div id=”Node”>
        <p></p>
    </div>
    </body>
</html>

Dojo : require()

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”
    “http://www.w3.org/TR/html4/strict.dtd”>
<html>
    <head>
        <title>Dojo</title>   
    <!– load the dojo toolkit base –>
    <script type=”text/javascript” src= “dojo/dojo/dojo.js”
        djConfig=”parseOnLoad:true, isDebug:true”></script>
    <script type=”text/javascript”>
        dojo.require(“dijit.form.Button”);
        dojo.require(“dijit.TitlePane”);
        dojo.addOnLoad(function(){
          dojo.byId(“testHeading”).innerHTML = “See!! New Heading is here”;
          console.log(“Execution Sequence: 1. require()  2. onLoad “);
         }); 

    </script>
    <style type=”text/css”>
    /* CSS  */   
    </style>   
    </head>
    <body>
        <h1 id=”testHeading”>Dojo test</h1>       
        <div id=”contentNode”>
        <p></p>
    </div>
    </body>
</html>

Dojo : HelloWorld

dojotest.html

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”
    “http://www.w3.org/TR/html4/strict.dtd”>
<html>
    <head>
        <title>Dojo</title>   
    <!– load the dojo toolkit base –>
    <script type=”text/javascript” src= “dojo/dojo/dojo.js”
        djConfig=”parseOnLoad:true, isDebug:true”></script>

    <script type=”text/javascript”>
     // a very common method of loading code onLoad
    var init = function(){
            console.log(“Hello World in Dojo!!”);   
    };
    dojo.addOnLoad(init);

    // and/or pass an anonymous function
    dojo.addOnLoad(function(){
            console.log(“Dojo Test!! “);
    });

    </script>

    <style type=”text/css”>
    /* CSS  */   
    </style>   
    </head>
    <body>
        <h1 id=”testHeading”>Dojo test</h1>       
        <div id=”contentNode”>
        <p></p>
    </div>
    </body>
</html>

DOJO : Introduction

Dojo is structured in 4 main projects: Dojo Core, Dijit, DojoX, and Dojo Utilities. Simply including the standard dojo.js gives you:

  • A very fast, lean (26KB gzipped) core packed full of APIs for XHR, events, DOM, query, animations, namespacing, and other highly used convenience functions.
  • Optional modules for dates, colors, back button/history, currency, and more

The Dojo core also includes additional code that may be optionally included such as a behavior system, common regular expressions, date and currency APIs, and more.

Dijit is both a widget system and a collection of common widgets, meaning that you get a nice set of widgets to use by default, and a powerful system for creating your own. All widgets in Dijit are fully accessible, internationalizable, and can be instantiated either through markup in an unobtrusive manner, or through a simple JavaScript instantiation. Dijit includes common form element upgrades, a calendar, editor, tree, sliders, and more.

Everything in Dojo and Dijit are deemed production-ready and API compatibility will be one of our higher priorities as we work towards Dojo 2.0.

DojoX, or Dojo extensions, contain features that are less widely, complex, or not yet production quality. Examples include encryption, additional Dojo data stores, dojo.gfx for native vector graphics support, charting, offline, grids and other widgets, and much more. Features in DojoX are not guaranteed to be backwards compatible across 1.x releases. DojoX contains a significant code base with great new additions arriving on a regular basis, most recently an XMPP client, JSON-Schema, JSON-Referencing, and a secure Ajax module, all of which will ship with Dojo 1.2 and are available in the current nightly builds.

Dojo Utilities offers, as its name suggests, a number of useful utilities for JavaScript developers, including

  • A highly-flexible build system for combining JavaScript files, satisfying dependencies, and merging HTML and CSS files, based on a slightly customized version of Rhino
  • ShrinkSafe, a compression tool that removes comments, extraneous whitespace, and more, which also makes use of Rhino
  • DocTool, a highly advanced system for generating API documentation from source code, that also can resolve complex mixin inheritance structures and more
  • DOH, the Dojo Objective Harness, a unit test tool that works both in the browser and on the command-line

Dojo is organized in a very modular manner, making it easy to just get the features you need so you don’t expend system resources for everything else in Dojo.

CVSNT and JDeveloper Integration : Step by Step Approach

1. Install CVSNT from http://www.march-hare.com/cvspro/#free and Select Complete Install and Install it on your Windows XP box.

2. Create CVS directories
Create two directories on the target machine, c:\cvsrepos and c:\cvsrepos\cvstemp. If you have a separate disk partition to spare for CVS then use that instead. The important point here is that the disk where the repository is located on is NTFS.
3. Directory security and permissions
Give c:\cvsrepos\cvstemp security settings that allows full control for all accounts including SYSTEM.
Important:
The cvstemp directory must NOT be located in either c:\WINNT\Temp or anywhere in the "C:\Documents and Settings" tree because these locations have imposed restrictions on user access!

2.

3. Shut down the CVSNT service
Check that the CVSNT Service is not running (Start button is enabled). This is the initial screen showing that both services are running:

clip_image002[1]

4. Repository creation
The tab will initially look like this:

clip_image004[1]

5. Add repository
Now you will add a repository to the server. This is done using the "Add" button. When you click this a dialogue shows up where you will define your repository.

clip_image006[1]

clip_image008[1]

6. Name repository
Now fill in the description and the name of the repository as well.
NOTE:
Do NOT
accept the suggested name, which is the same as the folder path!
Instead only use the bare folder name with a leading / like this:

clip_image010[1]

7. Initializing the repository
When you click the OK button there will be a dialog where CVSNT offers to initialize the new repository.
When you click Yes then the new folder will be converted to a real repository:

clip_image012[1]

8. First repository added!
Now the list of repositories has been populated with the first repository:

9. clip_image014[1]

You can add as many as you like (almost) but please do not fall for the temptation to use one repository for each and every project! There are a lot of possibilities to streamline the development process using CVSNT, but many of these use the virtual modules concept and this is only possible within a single repository.

10. Server Settings
Now go on to the Server Settings tab.
Here the default settings are all right for now, except the Temporary Directory setting.

clip_image016[1]

NOTICE about Domains:
You can set the Default domain entry to either the CVSNT server PC name (as in the example above) or the domain name to which the CVSNT server belongs. CVSNT will strip the domain part from all accounts that log on using the default domain before processing. All other logons will be processed using their complete names (DOMAIN\username). The result of this is that all users that "belong" to the domain specified in this box will be logged using only the account name, likewise these usernames will be supplied to the administrative scripts without the domain name. All others will have a domain name added. This must be accounted for in any admin script used.
The CVSROOT/users file is one such admin file that needs to be handled with care concerning domain and non-domain entries.
Temp dir: Use the ellipsis button to browse for the folder prepared for this purpose above:

clip_image018[1]

11. Compatibility
On the next tab (Compatibility Options) there is nothing you need to change for now:

clip_image020[1]

12. Plugins and protocols
The Plugins tab define a lot of the extra features of CVSNT including some aspects of the connection protocols. The sceen list the available plugins and when you select a line you will be able to configure this plugin by clicking the configure button:

Keep default settings…

clip_image022[1]

13. Advanced settings
The final tab on the Control Panel deals with advanced configuration settings and you need not change anything here.

Keep Default Settings….

clip_image024[1]

14. Apply configuration changes
Now click the Apply button! This is really important, nothing will happen unless you do this! Note that after you have done this the Apply button is disabled.
15. Start the CVSNT service
Go back to the first tab and click the Start button. After a few moments the Stop button will be highlighted.
Now CVSNT runs (success!)

15.Restart the server
In order for you to be able to use the command line cvs you need to have the path variable set to include the location of the cvs.exe just installed (c:\programs\cvsnt). Since the installer will have put this into the system path variable it will work if you restart the server.
You can check this by going to a command window and typing the command:
cvs –ver

Adding and managing CVS users for pserver

1. Creating CVS accounts on the server
In order for pserver and sserver to work you have to define CVS users, but before you can do this you need to create two real accounts on the server. These accounts will be used by the CVS users as the working accounts.
You need one account which will be a CVS administrative account and one which will be a normal user account. Note that the CVS administrator need not be a server administrator!

clip_image026[1]

The two accounts are added through the Users dialog in Computer Management.
I have used the account names cvsadmin and cvsuser as shown above.

2. Adding CVS users
Open a command window and do the following (replace items <text> with the real values from your system).

clip_image028[1]

clip_image030[1]

Here don’t worry too much about sspi. We are doing this process for pserver protocol only. Do what it says.

You will now be asked to enter a password for this user. This password is only for CVS use so it should not be the real system password! Enter the password twice.
Now the CVSROOT/passwd file will be created and the user you entered will be added to the list in this file.
This step is necessary if you are going to use the pserver

Creating Admin File:

  • Create a text file called admin (no extension) inside the CVSROOT directory of the repository. That is C:\cvsrepos\MyCode\CVSROOT
  • Edit this file by adding on separate lines the login names of the users you want to give administrative priviliges on the CVS server.

The file could look like this:
cvsadmin

Make sure you won’t create a .txt file. It shouldn’t contain any extension. If you don’t know how to create a file with no extension, copy one of the existing file and rename it as admin and remove its contents and above content. Still you can’t do this, Buy a computer professor CD from walmart and learn it. J (nice idea!! Right)

Giving Permissions to CVSAdmin User:

Give Permissions to cvsadmin user on cvsroot directory.

C:\cvsrepos\MyCode\CVSROOT : right click and add cvsadmin user and give full permissions.

clip_image032[1]

Adding new users to the CVS:

1. Open the command prompt and set the cvsroot for cvsadmin user.

clip_image034[1]

2. Now login into CVS with cvsadmin user.

Type cvs login on the command promt and enter password of cvsadmin user. This user is your System user that you created above. (System password of cvsadmin).

clip_image036[1]

Create CVS Users as many as you want:

Type below command and give the name of the user you want to use.

C:\>cvs passwd -r cvsadmin -a thamos

It will ask for a password for two times, Give it whatever you want for this user.

clip_image038[1]

Very nice!! So far you have added CVS Users in to the system.

5. Testing the CVS connection with pserver:

Set the CVS Root:

C:\>set cvsroot=:pserver:thamos@sharatlaptop:/cvsrepos/MyCode

clip_image040[1]
Open another command window and type:
set cvsroot=:pserver:thamos@sharatlaptop:cvsrepos/MyCode
Then:
cvs login (enter password on prompt)
cvs ls -l -R
(this should give you a list of the files in C:\cvsrepos\MyCode)

Awesome!! You did a great job so far.

If you cannot get this far, for example if the login fails, then you should check the Windows Firewall settings on the CVSNT server:

7. Modifying Windows Firewall to allow CVS calls

  • Go to Control Panel
  • Open the Windows Firewall item.
  • Select the Exceptions tab
  • Click the "Add port" button
  • Enter the name CVSNT and port number 2401 as a TCP port
  • Accept back to the main screen
  • Make sure Windows Firewall is set to ON

clip_image042[1]

clip_image044[1]

clip_image046[1]

Integrating with JDeveloper 10.1.3

Open JDeveloper:

clip_image048

To configure JDeveloper to use CVS:

  1. Choose Toolsclip_image049 Preferences, then select Extensions from the left panel of the Preferences dialog.
  2. In the right panel, ensure that Versioning Support n.n is checked.
  3. In the left panel of the Preferences dialog, open the Versioning node and then the CVS node. The main CVS preferences panel is shown. Other CVS preferences panels are shown when you click on the items beneath the CVS node.
  4. Make changes to the preferences as required. For more information about the specific preferences, press F1.
  5. Click OK to close the Preferences dialog.

clip_image051

clip_image053

Make sure here it is selected as External Executable.

Connecting to a CVS repository

You connect to a CVS repository through the CVS Connection wizard, which you can open from the CVS Navigator by selecting CVS, then clicking the right mouse button and choosing New CVS Connection.

clip_image055

clip_image057

clip_image059

clip_image061

clip_image063

clip_image065

Click on TestConnection.

clip_image067

Give the user password.

clip_image069

clip_image071

clip_image073

Now you must be doing this, to check some project/files. So open your java project in JDeveloper.

clip_image075

Now Click on Versioning and Click on Import Module.

clip_image077

clip_image079

clip_image081

clip_image083

clip_image085

clip_image087

clip_image089

clip_image091

clip_image093

Say YES

clip_image095

No change some part of your code in the Test JSP file.

clip_image097

clip_image099

Now Save the file and Click on Commit.

clip_image101

As this is the first time, you have to all folders.

clip_image103

Commit until workspace folder.

clip_image105

NOW LOGIN AS A DIFFERENT USER and See IF HE CAN COMMIT AND UPDATE THE FILES

Before setting it up for second user, remove first user stuff from Jdeveloper IDE.

1. Remove CVS Connection.

clip_image107

clip_image109

Now JDEV will be like this:

clip_image111

Here you go:

clip_image113

Now get the cvs connection using second user login: babu

clip_image115

Here there is one catch: If the user name you gave it has john and if you type here as John

Here (small) j VS (caps)J. It will fail. User name is also case sensitive. I know you love this tip!!

clip_image117

clip_image119

Click on Test Connection:

clip_image121

Now you can see the JDev like this:

clip_image123

Now checkout the module:

clip_image125

clip_image127

clip_image129

Make sure u check out to the JohnWork folder (some folder) Because u are testing it for two user from the same box.

Once you check out, see the application navigator. You got the code commited by previous user.

clip_image131

Now open testfile.jsp and change something to :

clip_image133

Now Save the file and commit:

clip_image135

clip_image137

Now you can see version got changed to 1.3 (or some number) to testfile.jsp.

clip_image139

Check the version history of the testfile.jsp:

clip_image141

clip_image143

You are done… have a wonderful day……..

JDK 1.5 Features

1.Generics
Allows programmers to specify the types allowed for Collections
Allows the compiler to enforce the type specifications
//Before
List stringList
//In JDK 1.5
List<String> stringList;
2.Enhanced for loop
A new language constuct for the Iterator pattern
//Before
for(Iterator i = line.iterator();i.hasNext(); )
{
  String word = (String)i.next();
  …
}
//In JDK 1.5
for(String word: line)
{
  …
}
3.Autoboxing
Essentially bridges between the “primitive” types (such as int, boolean) and the
“boxed” types (such as Integer, Boolean)

int primitive = 5;
Integer boxed = primitive;
int unboxed = boxed + 5;

4.Varargs
Allow a variable number of arguments for methods like printf() or Method.invoke()
Internally parameters are an array of Object
Compiler constructs array for the call
void printf(String format, Object…args);

printf(“{0} {1}\n”, “Hello”, “World”);
printf(“PI = {0}”, 3.14159);
5.Enumerations
Essentially the “typesafe enum pattern”.
Simple C-style enumeration
Can add behavior to each instance
High peformance EnumSet implementaion using a bit-vector

public enum Coin {
PENNY(1), NICKEL(5);
private final int value;
Coin(int value) {this.value = value}
}

6.Metadata
Ability to decorate Java classes and their members with arbitrary data
Retrieve values
– From source files
– From class files
– At runtime using Reflection
@Retention(RetentionPolicy.RUNTIME)
public @interface Test{}

Spring Framework

  1. What is Spring?

Spring is a lightweight inversion of control and aspect-oriented container framework.

  1. Explain Spring?

  • Lightweight – spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.

  • Inversion of control (IoC) – Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.

  • Aspect oriented (AOP) – Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.

  • Container – Spring contains and manages the life cycle and configuration of application objects.

  • Framework – Spring provides most of the intra functionality leaving rest of the coding to the developer.

  1. What are the different modules in Spring framework?

  • The Core container module

  • Application context module

  • AOP module (Aspect Oriented Programming)

  • JDBC abstraction and DAO module

  • O/R mapping integration module (Object/Relational)

  • Web module

  • MVC framework module

  1. What is the structure of Spring framework?

  1. What is the Core container module?

This module is provides the fundamental functionality of the spring framework. In this module BeanFactory is the heart of any spring-based application. The entire framework was built on the top of this module. This module makes the spring container.

  1. What is Application context module?

The Application context module makes spring a framework. This module extends the concept of BeanFactory, providing support for internationalization (I18N) messages, application lifecycle events, and validation. This module also supplies many enterprise services such JNDI access, EJB integration, remoting, and scheduling. It also provides support to other framework.

  1. What is AOP module?

The AOP module is used for developing aspects for our Spring-enabled application. Much of the support has been provided by the AOP Alliance in order to ensure the interoperability between Spring and other AOP frameworks. This module also introduces metadata programming to Spring. Using Spring’s metadata support, we will be able to add annotations to our source code that instruct Spring on where and how to apply aspects.

  1. What is JDBC abstraction and DAO module?

Using this module we can keep up the database code clean and simple, and prevent problems that result from a failure to close database resources. A new layer of meaningful exceptions on top of the error messages given by several database servers is bought in this module. In addition, this module uses Spring’s AOP module to provide transaction management services for objects in a Spring application.

  1. What are object/relational mapping integration module?

Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring provide support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction management supports each of these ORM frameworks as well as JDBC.

  1. What is web module?

This module is built on the application context module, providing a context that is appropriate for web-based applications. This module also contains support for several web-oriented tasks such as transparently handling multipart requests for file uploads and programmatic binding of request parameters to your business objects. It also contains integration support with Jakarta Struts.

  1. What is web module?

Spring comes with a full-featured MVC framework for building web applications. Although Spring can easily be integrated with other MVC frameworks, such as Struts, Spring’s MVC framework uses IoC to provide for a clean separation of controller logic from business objects. It also allows you to declaratively bind request parameters to your business objects. It also can take advantage of any of Spring’s other services, such as I18N messaging and validation.

  1. What is a BeanFactory?

A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the application’s configuration and dependencies from the actual application code.

  1. What is AOP Alliance?

AOP Alliance is an open-source project whose goal is to promote adoption of AOP

and interoperability among different AOP implementations by defining a common

set of interfaces and components.

  1. What is Spring configuration file?

Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other.

  1. What does a simple spring application contain?

These applications are like any Java application. They are made up of several classes, each performing a specific purpose within the application. But these classes are configured and introduced to each other through an XML file. This XML file describes how to configure the classes, known as the Spring configuration file.

  1. What is XMLBeanFactory?

BeanFactory has many implementations in Spring. But one of the most useful one is org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file. To create an XmlBeanFactory, pass a java.io.InputStream to the constructor. The InputStream will provide the XML to the factory. For example, the following code snippet uses a java.io.FileInputStream to provide a bean definition XML file to XmlBeanFactory.

BeanFactory factory = new XmlBeanFactory(new FileInputStream(“beans.xml”));

To retrieve the bean from a BeanFactory, call the getBean() method by passing the name of the bean you want to retrieve.

MyBean myBean = (MyBean) factory.getBean(“myBean”);

  1. What are important ApplicationContext implementations in spring framework?

  • ClassPathXmlApplicationContext – This context loads a context definition from an XML file located in the class path, treating context definition files as class path resources.

  • FileSystemXmlApplicationContext – This context loads a context definition from an XML file in the filesystem.

  • XmlWebApplicationContext – This context loads the context definitions from an XML file contained within a web application.

  1. Explain Bean lifecycle in Spring framework?

1. The spring container finds the bean’s definition from the XML file and instantiates the bean.

2. Using the dependency injection, spring populates all of the properties as specified in the bean definition.

3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.

4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.

5. If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.

6. If an init-method is specified for the bean, it will be called.

7. Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

  1. What is bean wiring?

Combining together beans within the Spring container is known as bean wiring or wiring. When wiring beans, you should tell the container what beans are needed and how the container should use dependency injection to tie them together.

  1. How do add a bean in spring application?

<?xml version=”1.0″ encoding=”UTF-8″?>

<!DOCTYPE beans PUBLIC “-//SPRING//DTD BEAN//EN”

“http://www.springframework.org/dtd/spring-beans.dtd”>

<beans>

<bean id=”foo” class=”com.act.Foo”/>

<bean id=”bar” class=”com.act.Bar”/>

</beans>

In the bean tag the id attribute specifies the bean name and the class attribute specifies the fully qualified class name.

 

  1. What are singleton beans and how can you create prototype beans?

Beans defined in spring framework are singleton beans. There is an attribute in bean tag named ‘singleton’ if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in spring framework are by default singleton beans.

<beans>

<bean id=”bar” class=”com.act.Foo” singleton=”false”/>

</beans>

  1. What are the important beans lifecycle methods?

There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the container. The second method is the teardown method which is called when the bean is unloaded from the container.

  1. How can you override beans default lifecycle methods?

The bean tag has two more important attributes with which you can define your own custom initialization and destroy methods. Here I have shown a small demonstration. Two new methods fooSetup and fooTeardown are to be added to your Foo class.

<beans>

<bean id=”bar” class=”com.act.Foo” init-method=”fooSetup” destroy=”fooTeardown”/>

</beans>

  1. What are Inner Beans?

When wiring beans, if a bean element is embedded to a property tag directly, then that bean is said to the Inner Bean. The drawback of this bean is that it cannot be reused anywhere else.

  1. What are the different types of bean injections?

There are two types of bean injections.

    1. By setter

    2. By constructor
    1. What is Auto wiring?

    You can wire the beans as you wish. But spring framework also does this work for you. It can auto wire the related beans together. All you have to do is just set the autowire attribute of bean tag to an autowire type.

    <beans>

    <bean id=”bar” class=”com.act.Foo” Autowire=”autowire type”/>

    </beans>

    1. What are different types of Autowire types?

    There are four different types by which autowiring can be done.

      • byName

      • byType

      • constructor

        1. autodetect
        1. What are the different types of events related to Listeners?

        There are a lot of events related to ApplicationContext of spring framework. All the events are subclasses of org.springframework.context.Application-Event. They are

        • ContextClosedEvent – This is fired when the context is closed.

        • ContextRefreshedEvent – This is fired when the context is initialized or refreshed.

        • RequestHandledEvent – This is fired when the web context handles any request.

        1. What is an Aspect?

        An aspect is the cross-cutting functionality that you are implementing. It is the aspect of your application you are modularizing. An example of an aspect is logging. Logging is something that is required throughout an application. However, because applications tend to be broken down into layers based on functionality, reusing a logging module through inheritance does not make sense. However, you can create a logging aspect and apply it throughout your application using AOP.

        1. What is a Jointpoint?

        A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point could be a method being called, an exception being thrown, or even a field being modified. These are the points where your aspect’s code can be inserted into the normal flow of your application to add new behavior.

         

        1. What is an Advice?

        Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, and advice is inserted into an application at joinpoints.

        1. What is a Pointcut?

        A pointcut is something that defines at what joinpoints an advice should be applied. Advices can be applied at any joinpoint that is supported by the AOP framework. These Pointcuts allow you to specify where the advice can be applied.

        1. What is an Introduction in AOP?

        An introduction allows the user to add new methods or attributes to an existing class. This can then be introduced to an existing class without having to change the structure of the class, but give them the new behavior and state.

        1. What is a Target?

        A target is the class that is being advised. The class can be a third party class or your own class to which you want to add your own custom behavior. By using the concepts of AOP, the target class is free to center on its major concern, unaware to any advice that is being applied.

        1. What is a Proxy?

        A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object and the proxy object are the same.

        1. What is meant by Weaving?

        The process of applying aspects to a target object to create a new proxy object is called as Weaving. The aspects are woven into the target object at the specified joinpoints.

        1. What are the different points where weaving can be applied?

        • Compile Time

        • Classload Time

        • Runtime

        1. What are the different advice types in spring?

        • Around : Intercepts the calls to the target method

        • Before : This is called before the target method is invoked

        • After : This is called after the target method is returned

        • Throws : This is called when the target method throws and exception

        • Around : org.aopalliance.intercept.MethodInterceptor

        • Before : org.springframework.aop.BeforeAdvice

        • After : org.springframework.aop.AfterReturningAdvice

        • Throws : org.springframework.aop.ThrowsAdvice

        1. What are the different types of AutoProxying?

        • BeanNameAutoProxyCreator

        • DefaultAdvisorAutoProxyCreator

        • Metadata autoproxying

        1. What is the Exception class related to all the exceptions that are thrown in spring applications?

        DataAccessException – org.springframework.dao.DataAccessException

         

        1. What kind of exceptions those spring DAO classes throw?

        The spring’s DAO class does not throw any technology related exceptions such as SQLException. They throw exceptions which are subclasses of DataAccessException.

        1. What is DataAccessException?

        DataAccessException is a RuntimeException. This is an Unchecked Exception. The user is not forced to handle these kinds of exceptions.

        1. How can you configure a bean to get DataSource from JNDI?

        <bean id=”dataSource” class=”org.springframework.jndi.JndiObjectFactoryBean”>
        <property name=”jndiName”>       <value>java:comp/env/jdbc/myDatasource</value>
          </property>
        </bean>

        1. How can you create a DataSource connection pool?

        <bean id=”dataSource” class=”org.apache.commons.dbcp.BasicDataSource”>
        <property name=”driver”>
        <value>${db.driver}</value>
        </property>
        <property name=”url”>
        <value>${db.url}</value>
        </property>
        <property name=”username”>
        <value>${db.username}</value>
        </property>
        <property name=”password”>
        <value>${db.password}</value>
        </property>
        </bean>

        1. How JDBC can be used more efficiently in spring framework?

        JDBC can be used more efficiently with the help of a template class provided by spring framework called as JdbcTemplate.

        1. How JdbcTemplate can be used?

        With use of Spring JDBC framework the burden of resource management and error handling is reduced a lot. So it leaves developers to write the statements and queries to get the data to and from the database.

        JdbcTemplate template = new JdbcTemplate(myDataSource);

        A simple DAO class looks like this.

        public class StudentDaoJdbc implements StudentDao {
        private JdbcTemplate jdbcTemplate;
             public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
                  this.jdbcTemplate = jdbcTemplate;
             }
             more..
        }

        The configuration is shown below.

        <bean id=”jdbcTemplate” class=”org.springframework.jdbc.core.JdbcTemplate“>
        <property name=”dataSource”>
               <ref bean=”dataSource”/>
           </property>
        </bean>
        <bean id=”studentDao” class=”StudentDaoJdbc”>
        <property name=”jdbcTemplate”>
                <ref bean=”jdbcTemplate”/>
           </property>
        </bean>
        <bean id=”courseDao” class=”CourseDaoJdbc”>
        <property name=”jdbcTemplate”>
               <ref bean=”jdbcTemplate”/>
           </property>
        </bean>

        1. How do you write data to backend in spring using JdbcTemplate?

        The JdbcTemplate uses several of these callbacks when writing data to the database. The usefulness you will find in each of these interfaces will vary. There are two simple interfaces. One is PreparedStatementCreator and the other interface is BatchPreparedStatementSetter.

        1. Explain about PreparedStatementCreator?

        PreparedStatementCreator is one of the most common used interfaces for writing data to database. The interface has one method createPreparedStatement().

        PreparedStatement createPreparedStatement(Connection conn)
        throws SQLException;

        When this interface is implemented, we should create and return a PreparedStatement from the Connection argument, and the exception handling is automatically taken care off. When this interface is implemented, another interface SqlProvider is also implemented which has a method called getSql() which is used to provide sql strings to JdbcTemplate.

        1. Explain about BatchPreparedStatementSetter?

        If the user what to update more than one row at a shot then he can go for BatchPreparedStatementSetter. This interface provides two methods

        setValues(PreparedStatement ps, int i) throws SQLException;
        int getBatchSize();

        The getBatchSize() tells the JdbcTemplate class how many statements to create. And this also determines how many times setValues() will be called.

        1. Explain about RowCallbackHandler and why it is used?

        In order to navigate through the records we generally go for ResultSet. But spring provides an interface that handles this entire burden and leaves the user to decide what to do with each row. The interface provided by spring is RowCallbackHandler. There is a method processRow() which needs to be implemented so that it is applicable for each and everyrow.

        void processRow(java.sql.ResultSet rs);

        Dojo Examples – II

        1. Getting Data

        Create one sample file to load in and name it as sample.txt with below text
        I am a <em>remote</em> file.
        We used Dojo(Ajax) to put text
        in our page

        <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
        <html>
        <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
        <title>Getting data with Dojo</title>
        <!– load the dojo toolkit base –>
        <script type=”text/javascript” src=”dojo/dojo.js”
        djConfig=”parseOnLoad:true, isDebug:true”></script>
        <script type=”text/javascript”>
        var init = function(){
        var contentNode = dojo.byId(“content”);
        dojo.xhrGet({
        url: “sample.txt”,
        handleAs: “text”,
        load: function(data,args){
        // fade out the node we’re modifying
        dojo.fadeOut({
        node: contentNode,
        delay: 2000,
        onEnd: function(){
        // set the data, fade it back in
        contentNode.innerHTML = data;
        dojo.fadeIn({node: contentNode}).play();
        }
        }).play();
        },
        // if any error occurs, it goes here:
        error: function(error,args){
        console.warn(“error!”,error);
        }

        // single handle argument is used instead of both load & error
        handle: function(data,args){
        if(typeof data == “error”){
        console.warn(“error!”);
        console.log(args);
        }else{
        dojo.fadeOut({
        node: contentNode,
        delay: 2000,
        onEnd: function(){
        // set the data, fade it back in
        contentNode.innerHTML = data;
        dojo.fadeIn({node: contentNode}).play();
        }
        }).play();
        }
        }
        });
        };
        dojo.addOnLoad(init);
        </script>
        <style type=”text/css”>
        container {
        border:1px dotted #b7b7b7;
        background:#ededed;
        width:75px;
        height:55px;
        }
        </style>
        </head>

        <body>
        <div id=”container” class=”box”>
        <div id=”content”>
        I am some Inner Content.
        I am going to be replaced
        </div>
        </div>
        </body>
        </html>

        Dojo Examples – I

        <html>
        <head>
        <title>Dojo Toolkit Working Examples</title>
        <!– load the dojo toolkit base –>
        <script type=”text/javascript” src=”dojo/dojo.js”
        djConfig=”parseOnLoad:true, isDebug:true”></script>
        <script type=”text/javascript”>
        /* our JavaScript will go here */
        dojo.require(“dijit.form.Button”);
        dojo.require(“dijit.TitlePane”);
        dojo.require(“dojo.NodeList-fx”);
        //——Example – 1————-
        dojo.addOnLoad(function(){
        dojo.byId(“testHeading”).innerHTML = “We’re on our way!”
        console.log(“onLoad fires after require() is done”);
        dojo.query(“#testHeading”)
        // add “testClass” to its class=”" attribute
        .addClass(“testClass”)
        // and fade it out after 500 ms
        .fadeOut({ delay:2000 }).play();
        dojo.query(“.para”)
        .addClass(“testClass”)
        .fadeOut({ delay: 1000 }).play();
        var node = dojo.byId(“testHeading”);
        dojo.connect(node,”onclick”,function(){
        node.innerHTML = “I’ve been clicked”
        });
        });
        // ——– Example – 2 —————————-

        var disableLinks = function(){
        dojo.query(“a”).connect(“onclick”,function(e){
        e.preventDefault(); // stop the event
        console.log(‘clicked: ‘,e.target); // the node we clicked on
        });
        };
        dojo.addOnLoad(disableLinks);
        // ———— Example – 3 ——————–
        var mineObj = {
        aMethod: function(){
        console.log(‘running A’);
        },
        bMethod: function(){
        console.log(‘running B’);
        }
        };
        var otherObj = {
        cMethod: function(){
        console.log(‘running C’);
        }
        };
        dojo.addOnLoad(function(){
        // run bMethod() whenever aMethod() gets run
        dojo.connect(mineObj,”aMethod”,mineObj,”bMethod”);
        // run an entirely different object’s method via a separate connection
        dojo.connect(mineObj,”bMethod”,otherObj,”cMethod”);
        // start chain of events
        mineObj.aMethod();
        });
        // ————- Example – 4 ———————-
        dojo.addOnLoad(function(){
        var animArgs = {
        node: “testHeading”,
        duration: 1000, // ms to run animation
        delay: 250 // ms to stall before playing
        };
        dojo.fadeOut(animArgs).play();
        });
        // ———- Example – 5 —————————–
        dojo.addOnLoad(function(){
        dojo.style(“testHeading”,”opacity”,”0″); // hide it
        var anim1 = dojo.fadeOut({ node: “testHeading”, duration:700 });
        var anim2 = dojo.animateProperty({
        node: “testHeading”, delay: 1000,
        properties:{
        // fade back in and make text bigger
        opacity: { end: 1 }, fontSize: { end:19, unit:”pt”}
        }
        });
        anim1.play();
        anim2.play();
        });
        // ———- Example – 6 —————————–

        dojo.require(“dojo.fx”);
        dojo.addOnLoad(function(){
        var anim = dojo.fadeOut({ node: “testHeading” });
        var anim2 = dojo.fx.slideTo({ node: “testHeading”, top:75, left:75 });
        var result = dojo.fx.combine([anim,anim2]);
        result.play();
        });
        // ——– Example – 7 —————

        dojo.addOnLoad(function(){
        var anim = dojo.fadeOut({ node: “testHeading” });
        dojo.connect(anim,”onEnd”,function(){
        dojo.byId(“testHeading”).innerHTML = “replaced after fade!”
        dojo.fadeIn({ node:”testHeading” }).play();
        });
        anim.play();
        });
        // ——– Example – 8 ——————

        dojo.addOnLoad(function(){
        var anim = dojo.animateProperty({
        node:”testHeading”,
        duration:700,
        properties: {
        // javascript css names are camelCase (not hyphenated)
        fontSize: { start:12, end:22, unit:”pt” },
        opacity: { start:1, end:0.5 },
        color: { start: “#000″, end:”#FFE” }
        },
        delay:100 // be careful of this trailing comma, it breaks IE.
        });
        anim.play();
        });
        // ———– Example – 9 —————————-

        dojo.require(“dojo.NodeList-fx”);
        var fadeThemOut = function(){
        dojo.query(“.fadeNode”).fadeOut().play();
        }
        var fadeThemIn = function(){
        dojo.query(“.fadeNode”).fadeIn().play();
        }
        dojo.addOnLoad(function(){
        dojo.connect(dojo.byId(“fadeOutTest”),”onclick”,fadeThemOut);
        dojo.connect(dojo.byId(“fadeInTest”),”onclick”,fadeThemIn);
        });
        </script>
        <style type=”text/css”>
        /* our CSS can go here */
        .testClass {
        color:red;
        }
        </style>
        </head>
        <body>
        <!– this is a Typical WebPage starting point … –>
        <h1 id=”testHeading”>Dojo Skeleton Page</h1>
        <a class=”link” href=”#”>First link</a>
        <a class=”link” href=”#”>Second Link</a>
        <p class=”para”>First paragraph</p>
        <p class=”para”>Second paragraph</p>
        <p class=”para”>Third paragraph</p>
        <p class=”fadeNode”>FadeNode1 </p>
        <p class=”fadeNode”>FadeNode2</p>
        <p class=”fadeNode”>FadeNode3</p>
        <div id=”fadeInTest”> Click to fadeIn</div>
        <div id=”fadeOutTest”>Click to fadeOut</div>
        <div id=”contentNode”>
        <p>Some Content To Replace</p>
        </div>
        </body>
        </html>

        JavaScript

        1. What is JavaScript?
        JavaScript is a platform-independent, event-driven, interpreted client-side scripting and programming language developed by Netscape Communications Corp. and Sun Microsystems.
        2. How is JavaScript different from Java?
        Java is an entire programming language developed by Sun Microsystems, while JavaScript is a scripting language that was introduced by Netscape.
        3.What’s relationship between JavaScript and ECMAScript?
        ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3.
        4.How do you submit a form using Javascript?
        Use document.forms[0].submit();
        (0 refers to the index of the form – if you have more than one form in a page, then the first one has the index 0, second has index 1 and so on).
        5.How do we get JavaScript onto a web page?
        JavaScript can be placed inside of the <head> element or it can directly add inside <body> element.
        <script type=”text/javascript” >
        // Add scripting code here
        </script>
        JavaScript can be referenced from a separate file also
        <script type=”text/javascript” SRC=”myStuff.js”></script>
        6.How to read and write a file using javascript?
        I/O operations like reading or writing a file is not possible with client-side javascript. However , this can be done by coding a Java applet that reads files for the script.
        7.How to detect the operating system on the client machine?
        In order to detect the operating system on the client machine, the navigator.appVersion
        string (property) should be used.
        8.How can JavaScript make a Web site easier to use? That is, are there certain JavaScript techniques that make it easier for people to use a Web site?
        JavaScript’s greatest potential gift to a Web site is that scripts can make the page more immediately interactive, that is, interactive without having to submit every little thing to the server for a server program to re-render the page and send it back to the client. For example, consider a top-level navigation panel that has, say, six primary image map links into subsections of the Web site. With only a little bit of scripting, each map area can be instructed to pop up a more detailed list of links to the contents within a subsection whenever the user rolls the cursor atop a map area.
        9.What are JavaScript types?
        Number, String, Boolean, Function, Object, Null, Undefined.
        10.How do you convert numbers between different bases in JavaScript?
        Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt (“3F”, 16); 
        11.How to create arrays in JavaScript?
        var arr = new Array();
        arr[0] = ‘HTML’
        arr[1] = ‘JavaScript’
        // We also can create the arrays like this
        var arr = new Array(21, 22, 23, 24, 25);
        12.How do you target a specific frame from a hyperlink?
        Include the name of the frame in the target attribute of the hyperlink. <a href=”mypage.htm” target=”myframe”>>My Page</a>
        13.What is a fixed-width table and its advantages?
        Fixed width tables are rendered by the browser based on the widths of the columns in the first row, resulting in a faster display in case of large tables. Use the CSS style table-layout:fixed to specify a fixed width table.
        If the table is not specified to be of fixed width, the browser has to wait till all data is downloaded and then infer the best width for each of the columns. This process can be very slow for large tables.
        14.Example of using Regular Expressions for syntax checking in JavaScript
        var re = new RegExp(“^(&[A-Za-z_0-9]{1,}=[A-Za-z_0-9]{1,})*$”);
        var text = myWidget.value;
        var OK = re.test(text);
        if( ! OK ) {
        alert(“The extra parameters need some work.\r\n Should be something like: \”&a=1&c=4\”");
        }
        15.How to add Buttons in JavaScript?
        <input type=”submit” value=”GO!” />
        Another useful approach is to set the “type” to “button” and use the “onclick” event.
        <input type=”button” value=”Hector” onclick=”displayHero(this)” />
        16.Where are cookies actually stored on the hard disk?
        This depends on the user’s browser and OS.
        In the case of Netscape with Windows OS,all the cookies are stored in a single file called
        cookies.txt
        c:\Program Files\Netscape\Users\username\cookies.txt
        In the case of IE,each cookie is stored in a separate file namely username@website.txt.
        c:\Windows\Cookies\username@Website.txt
        17.What can javascript programs do?
        Generation of HTML pages on-the-fly without accessing the Web server. The user can be given control over the browser like User input validation Simple computations can be performed on the client’s machine The user’s browser, OS, screen size, etc. can be detected Date and Time Handling
        18.How to set a HTML document’s background color?
        document.bgcolor property can be set to any appropriate color.
        19.How can JavaScript be used to personalize or tailor a Web site to fit individual users?
        JavaScript-enhanced page can instruct the browser to render only certain content based on the browser, operating system, and even the screen size.
        Scripting can even go further if the page author desires. For example, the author may include a preference screen that lets the user determine the desired background and text color combination. A script can save this information on the client in a well-regulated local file called a cookie. The next time the user comes to the site, scripts in its pages look to the cookie info and render the page in the color combination selected previously. The server is none the wiser, nor does it have to store any visitor-specific information.
        20.What does isNaN function do?
        Return true if the argument is not a number. 
        21.What is negative infinity?
        It’s a number in JavaScript, derived by dividing negative number by zero.
        22.In a pop-up browser window, how do you refer to the main browser window that opened it?
        Use window.opener to refer to the main window from pop-ups.
        23.What is the data type of variables of in JavaScript?
        All variables are of object type in JavaScript.
        24.Methods GET and POST in HTML forms – what’s the difference?.
        GET: Parameters are passed in the querystring. Maximum amount of data that can be sent via the GET method is limited to about 2kb.
        POST: Parameters are passed in the request body. There is no limit to the amount of data that can be transferred using POST. However, there are limits on the maximum amount of data that can be transferred in one name/value pair.
        25.How to write a script for “Select” lists using javascript
        1. To remove an item from a list set it to null
        mySelectObject.options[3] = null;
        2. To truncate a list set its length to the maximum size you desire
        mySelectObject.length = 2;
        3. To delete all options in a select object set the length to 0.
        mySelectObject.leng
        26.Text From Your Clipboard?
        It is true, text you last copied for pasting (copy & paste) can be stolen when you visit web sites using a combination of JavaScript and ASP (or PHP, or CGI) to write your possible sensitive data to a database on another server.
        27.What does the “Access is Denied” IE error mean?
        The “Access Denied” error in any browser is due to the following reason.
        A javascript in one window or frame is tries to access another window or frame whose
        document’s domain is different from the document containing the script.
        28.Is a javascript script faster than an ASP script?
        Yes.Since javascript is a client-side script it does require the web server’s help for its
        computation,so it is always faster than any server-side script like ASP,PHP,etc..
        29.Are Java and JavaScript the Same?
        No.java and javascript are two different languages.
        Java is a powerful object – oriented programming language like C++,C whereas Javascript is a
        client-side scripting language with some limitations.
        30.How to embed javascript in a web page?
        javascript code can be embedded in a web page between <script
        langugage=”javascript”></script> tags 
        31.What boolean operators does JavaScript support?
        &&, || and !
        32.What does “1″+2+4 evaluate to?
        Since 1 is a string, everything is a string, so the result is 124. 
        33.How to get the contents of an input box using Javascript?
        Use the “value” property.
        var myValue = window.document.getElementById(“MyTextBox”).value;
        34.How to determine the state of a checkbox using Javascript?
        var checkedP = window.document.getElementById(“myCheckBox”).checked;
        35.How to set the focus in an element using Javascript?
        document.forms[0].elements["myelementname"].focus(); 
        36.How to access an external javascript file that is stored externally and not embedded?
        This can be achieved by using the following tag between head tags or between body tags.
        <script src=”abc.js”></script>
        37.What is the difference between an alert box and a confirmation box?
        An alert box displays only one button which is the OK button whereas the Confirm box
        displays two buttons namely OK and cancel. 
        38.What is a prompt box?
        A prompt box allows the user to enter input by providing a text box.
        39.Can javascript code be broken in different lines?
        Breaking is possible within a string statement by using a backslash \ at the end but not within any other javascript statement.
        that is ,
        document.write(“Hello \ world”);
        is possible but not document.write \
        (“hello world”);
        40.How about 2+5+”8″?
        Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.
        41.What is the difference between SessionState and ViewState?
        ViewState is specific to a page in a session. Session state refers to user specific data that can be accessed across all pages in the web application.
        42.How to Accessing Elements using javascript?
        We can use the “getElementById” method (which is generally preferred)
        document.getElementById(“useless”).style.color = “red”;
        43.What looping structures are there in JavaScript?
        for, while, do-while loops, but no foreach.
        44.To put a “close window” link on a page ?
        <a href=’javascript:window.close()’ class=’mainnav’> Close </a>
        45.How to hide javascript code from old browsers that dont run it?
        Use the below specified style of comments <script language=javascript> <!– javascript code goes here // –> or Use the <NOSCRIPT>some html code </NOSCRIPT> tags and code the display html statements between these and this will appear on the page if the browser does not support javascript
        46.How to comment javascript code?
        Use // for line comments and
        /* */ for block comments
        47.Name the numeric constants representing max,min values
        Number.MAX_VALUE
        Number.MIN_VALUE
        48.What does javascript null mean?
        The null value is a unique value representing no value or no object.
        It implies no object,or null string,no valid boolean value,no number and no array object.
        49.How do you create a new object in JavaScript?
        var obj = new Object(); or var obj = {};
        50.How do you assign object properties?
        obj["age"] = 17 or obj.age = 17.
        51.What’s a way to append a value to an array?
        arr[arr.length] = value;
        52.What is this keyword?
        It refers to the current object.
        53.What does the term sticky session mean in a web-farm scenario? Why would you use a sticky session? What is the potential disadvantage of using a sticky session?
        Sticky session refers to the feature of many commercial load balancing solutions for web-farms to route the requests for a particular session to the same physical machine that serviced the first request for that session. This is mainly used to ensure that a in-proc session is not lost as a result of requests for a session being routed to different servers. Since requests for a user are always routed to the same machine that first served the request for that session, sticky sessions can cause uneven load distribution across servers.
        54.To set all checkboxes to true using JavaScript?
        var checkboxes = document.getElementsByTagName(“input”);
        checkboxes.item(0).checked = true;
        55.How to select an element by id and swapping an image ?
        ..
        <script language=”JavaScript” type=”text/javascript” >
        function setBeerIcon() {

        var beerIcon = document.getElementById(“beerIcon”);
        beerIcon.src = “images/”+getSelectValue(“beer”)+”.jpg”;
        }
        </script>

        <img border=”0″ src=”" id=”brandIcon” alt=”brand” />

        <select name=”beer” id=”beer” onChange=”setButton();setBeerIcon();”>
        <option value=”–Select–”>Select beer</option>
        <option value=”heineken”>heineken</option>
        <option value=”sol”>sol</option>
        <option value=”amstellight”>amstellight</option>
        <option value=”coronalight”>coronalight</option>
        <option value=”coronaextra”>coronaextra</option>
        <option value=”"></option>
        </select>
        56.What does undefined value mean in javascript?
        Undefined value means the variable used in the code doesnt exist or is not assigned any value or the property doesnt exist.
        57.What is the difference between undefined value and null value?
        (i)Undefined value cannot be explicitly stated that is there is no keyword called undefined whereas null value has keyword called null
        (ii)typeof undefined variable or property returns undefined whereas typeof null value returns object
        58.What is variable typing in javascript?
        It is perfectly legal to assign a number to a variable and then assign a string to the same variable as follows
        example
        i = 10;
        i = “string”;
        This is called variable typing
        59.Does javascript have the concept level scope?
        No.Javascript does not have block level scope,all the variables declared inside a function possess the same level of scope unlike c,c++,java.
        60.What are undefined and undeclared variables?
        Undeclared variables are those that are not declared in the program (do not exist at all),trying to read their values gives runtime error.But if undeclared variables are assigned then implicit declaration is done .
        Undefined variables are those that are not assigned any value but are declared in the program.Trying to read such variables gives special value called undefined value.
        61.What is === operator ?
        ==== is strict equality operator ,it returns true only when the two operands are having the same value without any type conversion.
        62.How to find the selected radio button immediately using the ‘this’ variable?
        <script>
        function favAnimal(button) {
        alert(‘You like ‘+button.value+’s.’);
        }
        </script>
        <input type=”radio” name=”marsupial” value=”kangaroo”
        onchange=”favAnimal(this)”>Kangaroo
        <br /><input type=”radio” name=”marsupial” value=”Opossum”
        onchange=”favAnimal(this)”>Opossum
        <br /><input type=”radio” name=”marsupial” value=”Tasmanian Tiger”
        onchange=”favAnimal(this)”>Tasmanian Tiger
        63.How to find radio button selection when a form is submitted?
        <script type=”text/javascript”>
        function findButton() {
        var myForm = document.forms.animalForm;
        var i;
        for(i=0;i<myForm.marsupial.length; i++) {
        if(myForm.marsupial[i].checked) {
        break;
        }
        }
        alert(“You selected \”"+myForm.marsupial[i].value+”\”.”);
        }
        </script>
        <form name=”animalForm” action=”">
        <input type=”radio” name=”marsupial” value=”kangaroo” />Kangaroo
        <br /><input type=”radio” name=”marsupial” value=”Opossum” />Opossum
        <br /><input type=”radio” name=”marsupial” value=”Tasmanian Tiger” />Tasmanian Tiger
        <input type=”button” name=”GO” value=”GO” onclick=”findButton()” />
        64.How to disable an HTML object
        document.getElementById(“myObject”).disabled = true;
        65.To write messages to the screen without using “document.write()” ?

        <span id=”mystatus”>Test. </span>

        var element = document.getElementById(“mystatus”);
        element.textContent = message; //for Firefox
        element.innerHTML = message; //for IE
        66.How to Add new elements dynamically.

        <p id=”firstP”>firstP<p>

        var newP = document.createElement(“p”);
        var textNode = document.createTextNode(” I’m a new text node”);
        newP.appendChild(textNode);
        document.getElementById(“firstP”).appendChild(newP);
        67.how to have an element invoke a javascript on selection, instead of going to a new URL:
        <script type=”text/javascript”>
        function pseudoHitMe() {
        alert(“Ouch!”);
        }
        </script>
        <a href=”javascript:pseudoHitMe()”>hit me</a>
        68.How to have the status line update when the mouse goes over a link (The support of the status line is sporadic)?
        <a href=”javascript.shtml”
        onmouseover=”window.status=’Hi There!’;return true”
        onmouseout=”window.status=”;return true”>Look at the Status bar</a>

        Look at the Status bar as your cursor goes over the link.
        69.How to create a popup warning box
        alert(‘Warning: Please enter an integer between 0 and 100.’);
        70.How to create a confirmation box?
        confirm(“Do you really want to launch the missile?”);
        71.How to create an input box?
        prompt(“What is your temperature?”);
        72.How to open a window with no toolbar, but with the location object.
        window.open(“http://www.mysite.org/Misc/Pennies”,”Pennies”,”resizable=yes, status=yes,toolbar=yes,location=yes,menubar=yes,scrollbars=yes,width=800,height=400″);
        73.How to setting a cookie with the contents of a textbox ?
        Values stored in cookies may not have semicolons, commas, or spaces. You should use the handy “escape()” function to encode the values, and “unescape()” to retrieve them.

        <input name=”myTextBox” type=”text” id=”myTextBox”/>

        var myBox = window.document.getElementById(myTextBox”);
        document.cookie = “myTextBox=”+ escape(myBox.value);
        74.How to getting values from cookies to set widgets?
        ….
        var cookieData = document.cookie;
        var cEnd = cookieData.length;
        unescape(cookieData.substring(0, cEnd));

        75.How to Handle Event Handlers?

        function onHit() {
        alert(“I’ve been hit!”);
        }

        <input type=”button” id=”hitme” name=”hitme” value=”hit me” onclick=”onHit()” />
        Or
        document.getElementById(“hitme”).onclick = onHit;
        Or
        document.getElementById(“hitme”).onclick = function () { alert(“howdy!”); }
        Or
        document.getElementById(“hitme”).addEventListener(“click”, onHit, false); 
        76.How to remove the event listener:
        document.getElementById(“hitme”).removeEventListener(“click”, onHit, false);
        77.How to change style on an element?
        document.getElementById(“myText”).style.color = “green”;
        document.getElementById(“myText”).style.fontSize = “20″;
        -or-
        document.getElementById(“myText”).className = “regular”;
        78.How to make elements invisible
        Change the “visibility” attribute of the style object associated with your element. Remember that a hidden element still takes up space, use “display” to make the space disappear as well.

        if ( x == y) {
        myElement.style.visibility = ‘visible’;
        } else {
        myElement.style.visibility = ‘hidden’;
        }
        79.How to set the cursor to wait.
        In theory, we should cache the current state of the cursor and then put it back to its original state.
        document.body.style.cursor = ‘wait’;
        //do something interesting and time consuming
        document.body.style.cursor = ‘auto’; 
        80.How to reload the current page
        window.location.reload(true); 
        81.how to force a page to go to another page using JavaScript?
        <script language=”JavaScript” type=”text/javascript” ><!– location.href=”http://newhost/newpath/newfile.html”; //–></script>
        82.How to convert a string to a number using JavaScript?
        You can use the parseInt() and parseFloat() methods. Notice that extra letters following a valid number are ignored, which is kinda wierd but convenient at times.
        parseInt(“100″) ==> 100
        parseFloat(“98.6″) ==> 98.6
        parseFloat(“98.6 is a common temperature.”) ==> 98.6
        parseInt(“aa”) ==> Nan //Not a Number
        parseInt(“aa”,16) ==> 170 //you can supply a radix or base
        83.How to convert numbers to strings using JavaScript?
        You can prepend the number with an empty string
        var mystring = “”+myinteger;
        or
        var mystring = myinteger.toString();
        You can specify a base for the conversion,
        var myinteger = 14;
        var mystring = myinteger.toString(16);

        mystring will be “e”.
        84.How to test for bad numbers using JavaScript?
        the global method, “isNaN()” can tell if a number has gone bad.
        var temperature = parseFloat(myTemperatureWidget.value);
        if(!isNaN(temperature)) {
        alert(“Please enter a valid temperature.”);
        }
        85.What’s Math Constants and Functions using JavaScript?
        The Math object contains useful constants such as Math.PI, Math.E
        Math also has a zillion helpful functions.
        Math.abs(value); //absolute value
        Math.max(value1, value2); //find the largest
        Math.random() //generate a decimal number between 0 and 1
        Math.floor(Math.random()*101) //generate a decimal number between 0 and 100 
        86.What’s the Date object using JavaScript?
        Time inside a date object is stored as milliseconds since Jan 1, 1970.
        new Date(06,01,02) // produces “Fri Feb 02 1906 00:00:00 GMT-0600 (Central Standard Time)”
        new Date(06,01,02).toLocaleString() // produces “Friday, February 02, 1906 00:00:00″
        new Date(06,01,02) – new Date(06,01,01) // produces “86400000″ 
        87.What does the delete operator do?
        The delete operator is used to delete all the variables and objects used in the program ,but it does not delete variables declared with var keyword.
        88.How to delete an entry using JavaScript?
        The “delete” operator removes an array element, but oddly does not change the size of the array.
        89.How to use strings as array indexes using JavaScript?
        Javascript does not have a true hashtable object, but through its wierdness, you can use the array as a hashtable.

        <script type=”text/javascript”>
        var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];

        for(var i=0; i < days.length; i++) {
        days[days[i]] = days[i];
        }

        document.write(“days[\"Monday\"]:”+days["Monday"]);
        </script>
        This produces
        days["Monday"]:Monday
        90.How to use “join()” to create a string from an array using JavaScript?
        “join” concatenates the array elements with a specified seperator between them.

        <script type=”text/javascript”>
        var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
        document.write(“days:”+days.join(“,”));
        </script>
        This produces
        days:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
        91.How to make a array as a stack using JavaScript?
        The pop() and push() functions turn a harmless array into a stack

        <script type=”text/javascript”>
        var numbers = ["one", "two", "three", "four"];
        numbers.push(“five”);
        numbers.push(“six”);
        document.write(numbers.pop());
        document.write(numbers.pop());
        document.write(numbers.pop());
        </script>
        This produces
        sixfivefour
        92.How to shift and unshift using JavaScript?
        <script type=”text/javascript”>
        var numbers = ["one", "two", "three", "four"];
        numbers.unshift(“zero”);
        document.write(” “+numbers.shift());
        document.write(” “+numbers.shift());
        document.write(” “+numbers.shift());
        </script>
        This produces
        zero one two
        shift, unshift, push, and pop may be used on the same array. Queues are easily implemented using combinations.
        93.How to create an object using JavaScript?
        var myMovie = new Object();
        myMovie.title = “Aliens”;
        myMovie.director = “James Cameron”;
        …OR…
        function movie(title, director) {
        this.title = title;
        this.director = director;
        }
        var aliens = new movie(“Aliens”,”Cameron”);
        …OR…
        function movie(title, director) {
        title : title;
        director : director;
        }
        var aliens = new movie(“Aliens”,”Cameron”);

        94.How to associate functions with objects using JavaScript?
        this.title = title;
        this.director = director;
        this.toString = function movieToString() {
        return(“title: “+this.title+” director: “+this.director);
        }
        …OR…
        this.title = title;
        this.director = director;
        this.toString = movieToString; //assign function to this method pointer
        95.eval()?
        The eval() method is incredibly powerful allowing you to execute snippets of code during exection.
        var USA_Texas_Austin = “521,289″;
        eval(“USA_”+”Texas_”+”Austin”)
        96.What does break and continue statements do?
        Continue statement continues the current loop (if label not specified) in a new iteration whereas break statement exits the current loop.
        97.How to create a function using function constructor?
        The following example illustrates this
        It creates a function called square with argument x and returns x multiplied by itself.
        var square = new Function (“x”,”return x*x”);
        98.What’s Prototypes for JavaScript?
        Objects have “prototypes” from which they may inherit fields and functions.

        <script type=”text/javascript”>
        function movieToString() {
        return(“title: “+this.title+” director: “+this.director);
        }
        function movie(title, director) {
        this.title = title;
        this.director = director || “unknown”; //if null assign to “unknown”
        this.toString = movieToString; //assign function to this method pointer
        }
        movie.prototype.isComedy = false; //add a field to the movie’s prototype
        var officeSpace = new movie(“OfficeSpace”);
        var narnia = new movie(“Narni”,”Andrew Adamson”);
        document.write(narnia.toString());
        document.write(“
        Narnia a comedy? “+narnia.isComedy);
        officeSpace.isComedy = true; //override the default just for this object
        document.write(“
        Office Space a comedy? “+officeSpace.isComedy);
        </script>
        99.unescape(), escape() ?
        These are similar to the decodeURI() and encodeURI(), but escape() is used for only portions of a URI.
        var myvalue = “Sir Walter Scott”;
        escape(myvalue);

        &author=”+escape(myvalue);
        100.decodeURI(), encodeURI() ?
        Many characters cannot be sent in a URL, but must be converted to their hex encoding. These functions are used to convert an entire URI (a superset of URL) to and from a format that can be sent via a URI.
        <script type=”text/javascript”>
        var uri = “http://www.google.com/search?q=sonofusion Taleyarkhan”
        document.write(“Original uri: “+uri);
        document.write(“<br />encoded: “+encodeURI(uri));
        </script>

        HTML

        1. What is HTML?
              HTML, or HyperText Markup Language, is a Universal language which allows an individual using special code to create web pages to be viewed on the Internet. HTML Code is the code that tells the browser what to do.
        2. What is a tag?
              In HTML, a tag tells the browser what to do. When you write an HTML page, you enter tags for many reasons — to change the appearance of text, to show a graphic, or to make a link to another page.      
        3. What is the simplest HTML page?
          HTML Code:
        <HTML><HEAD><TITLE>This is my page title! </TITLE></HEAD><BODY>This is my message to the world!</BODY></HTML>
        Browser Display: This is my message to the world!
        4. How do I create frames? What is a frameset?
             Frames allow an author to divide a browser window into multiple (rectangular) regions. Multiple documents can be displayed in a single window, each within its own frame. Graphical browsers allow these frames to be scrolled independently of each other, and links can update the document displayed in one frame without affecting the others.
              You can’t just “add frames” to an existing document. Rather, you must create a frameset document that defines a particular combination of frames, and then display your content documents inside those frames. The frameset document should also include alternative non-framed content in a NOFRAMES element.
              The HTML 4 frames model has significant design flaws that cause usability problems for web users. Frames should be used only with great care.
        5. How can I include comments in HTML?
              An HTML comment begins with “<!–”, ends with “–>”, and does not contain “–” or “>” anywhere in the comment.
        6. What is a Hypertext link?
              A hypertext link is a special tag that links one page to another page or resource. If you click the link, the browser jumps to the link’s destination.
        7. What is a DOCTYPE? Which one do I use?
              According to HTML standards, each HTML document begins with a DOCTYPE declaration that specifies which version of HTML the document uses. Originally, the DOCTYPE declaration was used only by SGML-based tools like HTML validators, which needed to determine which version of HTML a document used (or claimed to use).
        8. Can I nest tables within tables?
              Yes, a table can be embedded inside a cell in another table. Here’s a simple example:
            <table><tr><td>this is the first cell of the outer table</td>
                       <td>this is the second cell of the outer table, with the inner table embedded in it
                           <table><tr><td>this is the first cell of the inner table</td>
                                         <td>this is the second cell of the inner table</td>
                                      </tr>
                               </table>
                           </td>
                       </tr>
                 </table>
              Older versions of Netscape Navigator have problems with tables that are nested extremely deeply (e.g., tables nested ten deep). To avoid problems, avoid nesting tables more than a few deep. You may be able to use the ROWSPAN and COLSPAN attributes to minimize table nesting.
        9. How do I align a table to the right (or left)?
              You can use <TABLE ALIGN=”right”> to float a table to the right. (Use ALIGN=”left” to float it to the left.) Any content that follows the closing </TABLE> tag will flow around the table. Use <BR CLEAR=”right”> or <BR CLEAR=”all”> to mark the end of the text that is to flow around the table
        10. How can I use tables to structure forms?
              <FORM ACTION=”[URL]“>
                 <TABLE BORDER=”0″>
                   <TR>
                   <TH>Account:</TH>
                      <TD><INPUT TYPE=”text” NAME=”account”></TD>
                   </TR>
                   <TR>
                      <TH>Password:</TH>
                   <TD><INPUT TYPE=”password” NAME=”password”></TD>
                   </TR>
                   <TR>
                      <TD> </TD>
                      <TD><INPUT TYPE=”submit” NAME=”Log On”></TD>
                   </TR>
                 </TABLE>
               </FORM>

        11. How do I center a table?
              In your HTML, use

            <div class=”center”>
                <table>…</table>
            </div>

            In your CSS, use

            div.center {
                text-align: center;
            }

            div.center table {
                margin-left: auto;
                margin-right: auto;
                text-align: left;
            }
        12. How do I use forms?
              The basic syntax for a form is: <FORM ACTION=”[URL]“>…</FORM>
            When the form is submitted, the form data is sent to the URL specified in the ACTION attribute. This URL should refer to a server-side (e.g., CGI) program that will process the form data. The form itself should contain

            * at least one submit button (i.e., an <INPUT TYPE=”submit” …> element),
            * form data elements (e.g., <INPUT>, <TEXTAREA>, and <SELECT>) as needed, and
            * additional markup (e.g., identifying data elements, presenting instructions) as needed.
        13. How can I check for errors?
              HTML validators check HTML documents against a formal definition of HTML syntax and then output a list of errors. Validation is important to give the best chance of correctness on unknown browsers (both existing browsers that you haven’t seen and future browsers that haven’t been written yet).
              HTML checkers (linters) are also useful. These programs check documents for specific problems, including some caused by invalid markup and others caused by common browser bugs. Checkers may pass some invalid documents, and they may fail some valid ones.
              All validators are functionally equivalent; while their reporting styles may vary, they will find the same errors given identical input. Different checkers are programmed to look for different problems, so their reports will vary significantly from each other. Also, some programs that are called validators (e.g. the “CSE HTML Validator”) are really linters/checkers. They are still useful, but they should not be confused with real HTML validators.
              When checking a site for errors for the first time, it is often useful to identify common problems that occur repeatedly in your markup. Fix these problems everywhere they occur (with an automated process if possible), and then go back to identify and fix the remaining problems.
              Link checkers follow all the links on a site and report which ones are no longer functioning. CSS checkers report problems with CSS style sheets.
        14. How do I make a form so it can be submitted by hitting ENTER?
              The short answer is that the form should just have one <INPUT TYPE=TEXT> and no TEXTAREA, though it can have other form elements like checkboxes and radio buttons.  
        15. How do I set the focus to the first form field?
              You cannot do this with HTML. However, you can include a script after the form that sets the focus to the appropriate field, like this:

            <form id=”myform” name=”myform” action=…>
                <input type=”text” id=”myinput” name=”myinput” …>
            </form>

            <script type=”text/javascript”>
                document.myform.myinput.focus();
            </script>

              A similar approach uses <body onload=…> to set the focus, but some browsers seem to process the ONLOAD event before the entire document (i.e., the part with the form) has been loaded.
        16. How can I eliminate the extra space after a </form> tag?
              HTML has no mechanism to control this. However, with CSS, you can set the margin-bottom of the form to 0. For example:
              <form style=”margin-bottom:0;” action=…>
              You can also use a CSS style sheet to affect all the forms on a page:
              form { margin-bottom: 0 ; }     
        17. Can I have two or more actions in the same form?
              No. A form must have exactly one action. However, the server-side (e.g., CGI) program that processes your form submissions can perform any number of tasks (e.g., updating a database, sending email, logging a transaction) in response to a single form submission.
        18. How can I use forms for pull-down navigation menus?
              There is no way to do this in HTML only; something else must process the form. JavaScript processing will work only for readers with JavaScript-enabled browsers. CGI and other server-side processing is reliable for human readers, but search engines have problems following any form-based navigation.
        19. Can I use percentage values for <TD WIDTH=…>?
              The HTML 3.2 and HTML 4.0 specifications allow only integer values (representing a number of pixels) for the WIDTH attribute of the TD element. However, the HTML 4.0 DTD allows percentage (and other non-integer) values, so an HTML validator will not complain about <TD WIDTH=”xx%”>.
              It should be noted that Netscape and Microsoft’s browsers interpret percentage values for <TD WIDTH=…> differently. However, their interpretations (and those of other table-aware browsers) happen to match when combined with <TABLE WIDTH=”100%”>. In such situations, percentage values can be used relatively safely, even though they are prohibited by the public specifications.
        20. Why doesn’t <TABLE WIDTH=”100%”> use the full browser width?
              Graphical browsers leave a narrow margin between the edge of the display area and the content.
              Also note that Navigator always leaves room for a scrollbar on the right, but draws the scrollbar only when the document is long enough to require scrolling. If the document does not require scrolling, then this leaves a right “margin” that cannot be removed.
        21. Why is there extra space before or after my table?
              This is often caused by invalid HTML syntax. Specifically, it is often caused by loose content within the table (i.e., content that is not inside a TD or TH element). There is no standard way to handle loose content within a table. Some browsers display all loose content before or after the table. When the loose content contains only multiple line breaks or empty paragraphs, then these browsers will display all this empty space before or after the table itself.
              The solution is to fix the HTML syntax errors. All content within a table must be within a TD or TH element.
        22. How do I create a link that sends me email?
              Use a mailto link, for example
              Send me email at
              <A HREF=”mailto:me@mydomain.com”>me@mydomain.com</A>.
        23. How can I have two sets of links with different colors?
              You can suggest this presentation in a style sheet. First, specify colors for normal links, like this:

            a:link {color: blue; background: white}
            a:visited {color: purple; background: white}
            a:active {color: red; background: white}

            Next, identify the links that you want to have different colors. You can use the CLASS attribute in your HTML, like this:

            <a class=”example1″ href=”[URL]“>[link text]</a>
            Then, in your style sheet, use a selector for links with this CLASS attribute, like this:

            a.example1:link {color: yellow; background: black}
            a.example1:visited {color: white; background: black}
            a.example1:active {color: red; background: black}

            Alternatively, you can identify an element that contains the links that you want to have different colors, like this:

            <div class=”example2″>…
            <a href=”[URL]“>[link text]</a>…
            <a href=”[URL]“>[link text]</a>…
            <a href=”[URL]“>[link text]</a>…
            </div>

            Then, in your style sheet, use a selector for links in this containing element, like this:

            .example2 a:link {color: yellow; background: black}
            .example2 a:visited {color: white; background: black}
            .example2 a:active {color: red; background: black}
        24. How can I show HTML examples without them being interpreted as part of my document?
              Within the HTML example, first replace the “&” character with “&amp;” everywhere it occurs. Then replace the “&lt;” character with “<” and the “&gt;” character with “>” in the same way.
            Note that it may be appropriate to use the CODE and/or PRE elements when displaying HTML examples.
        25. Should I put quotes around attribute values?
              It is never wrong to quote attribute values, and many people recommend quoting all attribute values even when the quotation marks are technically optional. XHTML 1.0 requires all attribute values to be quoted. Like previous HTML specifications, HTML 4 allows attribute values to remain unquoted in many circumstances (e.g., when the value contains only letters and digits).
              Be careful when your attribute value includes double quotes, for instance when you want ALT text like “the “King of Comedy” takes a bow” for an image. Humans can parse that to know where the quoted material ends, but browsers can’t. You have to code the attribute value specially so that the first interior quote doesn’t terminate the value prematurely. There are two main techniques:

            * Escape any quotes inside the value with " so you don’t terminate the value prematurely: ALT=”the "King of Comedy" takes a bow”.
            * Use single quotes to enclose the attribute value: ALT=’the “King of Comedy” takes a bow’.

              Both these methods are correct according to the specification and are supported by current browsers, but both were poorly supported in some earlier browsers. The only truly safe advice is to rewrite the text so that the attribute value need not contain quotes, or to change the interior double quotes to single quotes, like this: ALT=”the ‘King of Comedy’ takes a bow”.
        26. HTML for Lists
              1. Bulleted Lists: <ul> begins a bulleted, indented list. Each item in the list is then prefaced with the <li> tag. It is not necessary to insert a break at the end of each line — the <li> tag automatically creates a new line.

            * with <li type=disc>
            * with <li type=square>
            * with <li type=circle>

              2. Numbered Lists: <ol> begins a numbered, indented list. Each item in the list is then prefaced with the <li> tag. You need to close the list with the </ol> tag. Note: You can expand the <ol> to specify the TYPE of numbering:

            <ol> 1 (decimal numbers: 1, 2, 3, 4, 5, …)
            <ol type=”a”> a (lowercase alphabetic: a, b, c, d, e, …)
            <ol type=”A”> A (uppercase alphabetic: A, B, C, D, E, …)
            <ol type=”i”> i (lowercase Roman numerals: i, ii, iii, iv, v, …)
            <ol type=”I”> I (uppercase Roman numerals: I, II, III, IV, V, …)
        27. How do I eliminate the blue border around linked images?
              In your HTML, you can specify the BORDER attribute for the image:
              <a href=…><img src=… alt=… border=”0″></a>
              However, note that removing the border that indicates an image is a link makes it harder for users to distinguish quickly and easily which images on a web page are clickable.
        28. How do I eliminate the space around/between my images?
              If your images are inside a table, be sure to set the BORDER, CELLSPACING, and CELLPADDING attributes to 0.
              Extra space between images is often created by whitespace around the <IMG> tag in the markup. It is safe to use newlines inside a tag (between attributes), but not between two tags. For example, replace this:

              <td …>
              <img src=… alt=…>
              <img src=… alt=…>
              </td>

              with this:

              <td …><img src=… alt=…><img src=… alt=…></td>

              According to the latest specifications, the two should be equivalent. However, common browsers do not comply with the specifications in this situation.
              Finally, extra space between images can appear in documents that trigger the “standards” rendering mode of Gecko-based browsers like Mozilla and Firefox.
        29. How can I specify colors?
              If you want others to view your web page with specific colors, the most appropriate way is to suggest the colors with a style sheet. Cascading Style Sheets use the color and background-color properties to specify text and background colors. To avoid conflicts between the reader’s default colors and those suggested by the author, these two properties should always be used together.
              With HTML, you can suggest colors with the TEXT, LINK, VLINK (visited link), ALINK (active link), and BGCOLOR (background color) attributes of the BODY element.
              Note that these attributes are deprecated by HTML 4. Also, if one of these attributes is used, then all of them should be used to ensure that the reader’s default colors do not interfere with those suggested by the author. Here is an example:
              <body bgcolor=”#ffffff” text=”#000000″ link=”#0000ff” vlink=”#800080″ alink=”#000080″>
              Authors should not rely on the specified colors since browsers allow their users to override document-specified colors.
        30. How do I get form data emailed to me?
              The only reliable mechanism for processing form submissions is with a server-side (e.g., CGI) program. To send form data to yourself via email, you should use a server-side program that processes the form submission and sends the data to your email address.
        31. Can I prevent a form from being submitted again?
              No. The server-side (e.g., CGI) program that processes the form submission must handle duplicate submissions gracefully.
              You could generate the form with a server-side (e.g., CGI) program that adds a hidden field with a unique session ID. Then the server-side program that processes the form submission can check the session ID against a list of previously used session IDs. If the session ID has already been used, then an appropriate action can be taken (e.g., reject the submission, or update the previously submitted data).
              Ultimately, your server-side program must be smart enough to handle resubmitted data. But you can avoid getting resubmitted data by not expiring the confirmation page from form submissions. Since you want to expire pages quickly when they have transient data, you might want to avoid putting transient data on the confirmation page. You could provide a link to a database query that returns transient data though.
        32. How can I allow file uploads to my web site?
              These things are necessary for Web-based uploads:

            * An HTTP server that accepts uploads.
            * Access to the /cgi-bin/ to put the receiving script. Prewritten CGI file-upload scripts are available.
            * A form implemented something like this:

            <form method=”post” enctype=”multipart/form-data” action=”submitAction”>
            File to upload: <input type=file name=upfile><br>
            Notes about the file: <input type=text name=note><br>
            <input type=submit value=Press> to upload the file!
            </form>
        33. How can I require that fields be filled in, or filled in correctly?
              Have the server-side (e.g., CGI) program that processes the form submission send an error message if the field is not filled in properly. Ideally, this error message should include a copy of the original form with the original (incomplete or incorrect) data filled in as the default values for the form fields. The Perl CGI.pm module provides helpful mechanisms for returning partially completed forms to the user.
              In addition, you could use JavaScript in the form’s ONSUBMIT attribute to check the form data. If JavaScript support is enabled, then the ONSUBMIT event handler can inform the user of the problem and return false to prevent the form from being submitted.
              Note that the server-side program should not rely upon the checking done by the client-side script.
        34. How do I change the title of a framed document?
              The title displayed is the title of the frameset document rather than the titles of any of the pages within frames. To change the title displayed, link to a new frameset document using TARGET=”_top” (replacing the entire frameset).
        35. How do I link an image to something?
              Just use the image as the link content, like this:
            <a href=…><img src=… alt=…></a>
        36. How do I link to a location in the middle of an HTML document?
              There are different ways to fullfil the above requirement
              a. <h2><a name=”section2″>Section 2: Beyond Introductions</a></h2>
              b.<h2 id=”section2″>Section 2: Beyond Introductions</h2>
              c.<a href=”#section2″>go to Section 2</a>
              d.<a href=”thesis.html#section2″>go to Section 2 of my thesis</a>   
        37. How do I create a link?
              <A HREF=”http://www.yoursite.com/faq/html/”>Web Authoring FAQ</A>
        38. How do I create a link that opens a new window?
              <a target=”_blank” href=…> opens a new, unnamed window.
              <a target=”example” href=…> opens a new window named “example”, provided that a window or frame by that name does not already exist.
        39. How do I let people download a file from my page?
              Once the file is uploaded to the server, you need only use an anchor reference tag to link to it. An example would be:
              <a href=”../files/foo.zip”>Download Foo Now! (100kb ZIP)</a>
        40. How do I create a button which acts like a link?
              This is best done with a small form:

            <FORM ACTION=”[URL]” METHOD=GET>
                <INPUT TYPE=submit VALUE=”Text on button”>
            </FORM>
        41. How can I make a form with custom buttons?
              Rather than a normal submit button (<input type=”submit” …>), you can use the image input type (<input type=”image” …>). The image input type specifies a graphical submit button that functions like a server-side image map.      
            <input type=”image” name=”Send” alt=”Send” value=”Send” src=”send-button.gif”>      
        42. How do I specify page breaks in HTML?
               There is no way in standard HTML to specify where page breaks will occur when printing a page. HTML was designed to be a device-independent structural definition language, and page breaks depend on things like the fonts and paper size that the person viewing the page is using.
        43. Which should I use, &entityname; or &#number; ?
              In HTML, characters can be represented in three ways:

            1. a properly coded character, in the encoding specified by the “charset” attribute of the “Content-type:” header;
            2. a character entity (&entityname;), from the appropriate HTML specification (HTML 2.0/3.2, HTML 4, etc.);
            3. a numeric character reference (&#number;) that specifies the Unicode reference of the desired character. We recommend using decimal references; hexadecimal references are less widely supported.

        44. How do I remove the border around frames?
              Removing the border around frames involves both not drawing the frame borders and eliminating the space between the frames. The most widely supported way to display borderless frames is <FRAMESET … BORDER=0 FRAMEBORDER=0 FRAMESPACING=0>.
              Note that these attributes are proprietary and not part of the HTML 4.01 specifications. (HTML 4.01 does define the FRAMEBORDER attribute for the FRAME element, but not for the FRAMESET element.) Also, removing the border around a frame makes it difficult to resize it, as this border is also used in most GUIs to change the size of the frame.
        45. How can I specify background images?
              With HTML, you can suggest a background image with the BACKGROUND attribute of the BODY element. Here is an example:
              <body background=”imagefile.gif” bgcolor=”#ffffff” text=”#000000″ link=”#0000ff” vlink=”#800080″ alink=”#000080″>
              If you specify a background image, you should also specify text, link, and background colors since the reader’s default colors may not provide adequate contrast against your background image. The background color may be used by those not using your background image. Authors should not rely on the specified background image since browsers allow their users to disable image loading or to override document-specified backgrounds.
        46. Is it possible to make the HTML source not viewable?
              In short, there is no real method or script for making standard HTML source code not viewable. You may consider doing any of the below if they are concerned about your source code.

            1. Create the web page in Macromedia Flash or a similar program. The visitor would need to download the Macromedia Flash plug-in and would be unable to view the source code for the flash applet.
            2. There are various scripts that will disable the right click feature, preventing the user from saving images or viewing the source. However, this will not protect the source code of your page. For example, Internet Explorer users may still click “View” and “Source” to view the source code of the page, or a user could disable scripts and images can be saved by simply saving the web page to the hard drive.
            3. There are several programs that will help scramble your code, making it difficult (not impossible) to read. Again, this is not going to prevent someone from viewing your code.
        47. How do I make a thumbnail for my image(s)?
              Thumbnails are very useful, but they take a little bit of time to make. All you need is a graphics editing program that has functions to resize an image (sometimes it’s under a function called image attributes). Be advised–when you have made a thumbnail, you will need to save it as something different than the original. Also, you will generally want to link to the larger graphic when you are done.
              <a href=”taco.jpg”><img src=”tacot.jpg” width=100 height=25 border=0 alt=”click for larger taco”></a>
        48. What is the difference between the HTML form methods GET and POST?
              The method parameter specifies which method the client is using to send information to the WEB server. The method determines which parameter you will find the CGI request data in:

            * POST – post_args
            * GET – http_search_args
        49. How do I put sounds for older versions of Internet Explorer?
              For older versions of Internet Explorer, this technique was used <BG SOUND=”sound.ext”>.
        50. How to transferring user to new web page automatically?
              You will need to use the below meta tag.
            <META HTTP-EQUIV=”Refresh” CONTENT=”2″; URL=”http://www.yourname.com”>
                Placing the above tag in your <HEAD></HEAD> will load yousite.com in 2 seconds.
                Changing the 2 value on CONTENT=”2″ to another value will increase or decrease the delay until loading the new page.
        51. I’m trying to `include’ a HTML document in another document…Is there a way to do this?
              SGML already provides the standard way to do this, using an entry in the DocType Declaration for a file:

            <!doctype html public “-//IETF//DTD HTML 3.0//EN” [
            <!entity foo system "bar.html">
            ]>
            …
            and then later when you want to include the file
            …
            &foo;
        52. My page looks good on one browser, but not on another.
              There are slight differences between browsers, such as Netscape Navigator and Microsoft Internet Explorer, in areas such as page margins. The only real answer is to use standard HTML tags whenever possible, and view your pages in multiple browsers to see how they look.
        53. How do I make sure my framed documents are displayed inside their frameset?
              If the reader’s browser has JavaScript support enabled, the following script will restore the frameset:

            <SCRIPT TYPE=”text/javascript”>
            if (parent.location.href == self.location.href) {
            if (window.location.href.replace)
            window.location.replace(‘frameset.html’);
            else
            // causes problems with back button, but works
            window.location.href = ‘frameset.html’;
            }
            </SCRIPT>
            A more universal approach is a “restore frames” link:

            <A HREF=”frameset.html” TARGET=”_top”>Restore Frames
        54. How do I update two frames at once?
              There are two basic techniques for updating multiple frames with a single link: The HTML-based technique links to a new frameset document that specifies the new combination of frames. The JavaScript-based solution uses the onClick attribute of the link to update the additional frame (or frames).

            The HTML-based technique can link to a new frameset document with the TARGET=”_top” attribute (replacing the entire frameset). However, there is an alternative if the frames to be updated are part of a nested frameset. In the initial frameset document, use a secondary frameset document to define the nested frameset. For example:

            <frameset cols=”*,3*”>
            <frame src=”contents.html” name=”Contents”>
            <frame src=”frameset2.html” name=”Display”>
            <noframes>
            <!– Alternative non-framed version –>
            </body></noframes>   
            </frameset>

            A link can now use the TARGET=”Display” attribute to replace simultaneously all the frames defined by the frameset2.html document.
            The JavaScript-based solution uses the onClick attribute of the link to perform the secondary update. For example:
            <a href=”URL1″ target=”Frame1″ onClick=”top.Frame2.location=’URL2′;”>Update frames
            The link will update Frame1 with URL1 normally. If the reader’s browser supports JavaScript (and has it enabled), then Frame2 will also be updated (with URL2).     
        55. Can I have two or more Submit buttons in the same form?
              Yes. This is part of HTML 2.0 Forms support (some early browsers did not support it, but browser coverage is now excellent).
            The submit buttons must have a NAME attribute. The optional VALUE attribute can be used to specify different text for the different submit buttons.
            To determine which submit button was used, you need to use different values for the NAME and/or VALUE attributes. Browsers will send to the server the name=value pair of the submit button that was used. Here is an example:

            <input type=”submit” name=”join” value=”I want to join now”>
            <input type=”submit” name=”info” value=”Please send full details”>

        56. How do I make a link or form in one frame update another frame?
              in the frameset document (the HTML document containing the <frameset> <frame> tags), make sure to name the individual frames using the NAME attribute. The following example creates a top frame named “navigation” and a bottom frame named “content”:

            <frameset rows=”*,3*”>
                <frame name=”navigation” src=”navigation.html”>
                <frame name=”content” src=”content.html”>
                <noframes><body>
                <!– Alternative non-framed version –>
                </body></noframes>
            </frameset>

            Then, in the document with the link, use the TARGET attribute to specify which frame should be used to display the link. (The value of the TARGET attribute should match the value of the target frame’s NAME attribute.) For example:

            <a target=”content” href=…>
            To target a form submission, use the TARGET attribute of the FORM element, like this:

            <form target=”content” action=…>
            Note that when forms are processed entirely by JavaScript, the target frame must be specified in the JavaScript. The value of the TARGET attribute is irrelevant.
            Normally, the default target frame is the current frame (“_self”). To change the default target for every link/form on the page, use the TARGET attribute of the BASE element, like this: <base target=”content”>
        57. When I try to upload my site, all my images are X’s. How do I get them to load correctly?
              They are a few reasons that this could happen. The most common are:

            1. You’re attempting to use a .bmp or .tif or other non-supported file format. You can only use .gif and .jpg on the web. You must convert files that are not .gif or .jpg into a .gif or .jpg with your image/graphics program.
            2. You’ve forgotten to upload the graphic files. Double-Check.
            3. You’ve incorrectly linked to the images. When you are starting out, try just using the file name in the <img> tag. If you have cat.jpg, use
            img src=”cat.jpg”>.
            4. Image file names are case-sensitive. If your file is called CaT.JpG, you cannot type cat.jpg, you must type CaT.JpG exactly in the src.
            5. If all of the above fail, re-upload the image in BINARY mode. You may have accidentally uploaded the image in ASCII mode.     
        58. Why does the browser show my plain HTML source?
               If Microsoft Internet Explorer displays your document normally, but other browsers display your plain HTML source, then most likely your web server is sending the document with the MIME type “text/plain”. Your web server needs to be configured to send that filename with the MIME type “text/html”. Often, using the filename extension “.html” or “.htm” is all that is necessary. If you are seeing this behavior while viewing your HTML documents on your local Windows filesystem, then your text editor may have added a “.txt” filename extension automatically. You should rename filename.html.txt to filename.html so that Windows will treat the file as an HTML document.
        59. How can I display an image on my page?
              Use an IMG element. The SRC attribute specifies the location of the image. The ALT attribute provides alternate text for those not loading images. For example:

            <img src=”logo.gif” alt=”ACME Products”>
        60. Why do my links open new windows rather than update an existing frame?
              If there is no existing frame with the name you used for the TARGET attribute, then a new browser window will be opened, and this window will be assigned the name you used. Furthermore, TARGET=”_blank” will open a new, unnamed browser window.
            In HTML 4, the TARGET attribute value is case-insensitive, so that abc and ABC both refer to the same frame/window, and _top and _TOP both have the same meaning. However, most browsers treat the TARGET attribute value as case-sensitive and do not recognize ABC as being the same as abc, or _TOP as having the special meaning of _top.
            Also, some browsers include a security feature that prevents documents from being hijacked by third-party framesets. In these browsers, if a document’s link targets a frame defined by a frameset document that is located on a different server than the document itself, then the link opens in a new window instead.
         61. How do I make a frame with a vertical scrollbar but without a horizontal scrollbar?
              The only way to have a frame with a vertical scrollbar but without a horizontal scrollbar is to define the frame with SCROLLING=”auto” (the default), and to have content that does not require horizontal scrolling. There is no way to specify that a frame should have one scrollbar but not the other. Using SCROLLING=”yes” will force scrollbars in both directions (even when they aren’t needed), and using SCROLLING=”no” will inhibit all scrollbars (even when scrolling is necessary to access the frame’s content). There are no other values for the SCROLLING attribute.
        62. Are there any problems with using frames?
              The fundamental problem with the design of frames is that framesets create states in the browser that are not addressable. Once any of the frames within a frameset changes from its default content, there is no longer a way to address the current state of the frameset. It is difficult to bookmark – and impossible to link or index – such a frameset state. It is impossible to reference such a frameset state in other media. When the sub-documents of such a frameset state are accessed directly, they appear without the context of the surrounding frameset. Basic browser functions (e.g., printing, moving forwards/backwards in the browser’s history) behave differently with framesets. Also, browsers cannot identify which frame should have focus, which affects scrolling, searching, and the use of keyboard shortcuts in general.
              Furthermore, frames focus on layout rather than on information structure, and many authors of framed sites neglect to provide useful alternative content in the NOFRAMES element. Both of these factors cause accessibility problems for browsers that differ significantly from the author’s expectations and for search engines.
        63. How do I open a link into a new window?
              This feature is a byproduct of frames (In many opinions, the only good things frames did for web design). On any HTML page, you can just add target=”_blank” to your link syntax. e.g. yoursite.com

        CSS

        1. What is CSS?   
        2. What are Cascading Style Sheets?
        3. How do I center block-elements with CSS1?
        4. If background and color should always be set together, why do they exist as separate properties?
        5. What is class?
        6. What is grouping
        7. What is external Style Sheet? How to link?
        8. Is CSS case sensitive?
        9. Three selectors: h1, .warning and #footer, what they do ?
        10. What are Style Sheets?
        11. What is CSS rule ‘ruleset’?
        12. ‘Fixed’ Background?
        13. What is embedded style? How to link?
        14. What is ID selector?
        15. What is contextual selector?
        16. How do I have a background image that isn’t tiled?
        17. What does \ABCD (and \ABCDE) mean?
        18. Why do style sheets exist?
        19. What are the advantages/disadvantages of the various style methods?
        20. What is inline style? How to link?
        21. What is imported Style Sheet? How to link?
        22. What is a Style Sheet?
        23. What is alternate Style Sheet? How to link?
        24. How can you set a minimum width for IE?
        25. Which browsers support CSS?
        26. How do I place text over an image?
        27. what CSS is, why not start coding??
        28. Why does my content shift to the left on some pages (in FF)?
        29. How do I combine multiple sheets into one?
        30. What is attribute selector?
        31. What is parent-child selector?
        32. How can I specify background images?
        33. How do I have a fixed (non-scrolling) background image?
        34. What are inline, block, parent, children, replaced and floating elements?
        35. Which set of definitions, HTML attributes or CSS properties, take precedence?
        36. How do I eliminate the blue border around linked images?
        37. why call the subtended angle a “pixel”, instead of something else (e.g. “subangle”)?
        38. Why was the decision made to make padding apply outside of the width of a ‘box’, rather than inside, which would seem to make more sense?
        39. How to use CSS to separate content and design ?
        40. Can CSS be used with other than HTML documents?
        41. Can Style Sheets and HTML stylistic elements be used in the same document?
        42. What are pseudo-classes?
        43. How do I design for backward compatibility using Style Sheets?
        44. As a reader, how can I make my browser recognize my own style sheet?
        45. How do I get rid of the gap under my image?
        46. Why use Style Sheets?
        47. What does the “Cascading” in “Cascading Style Sheets” mean?
        48. What is CSS rule ‘at-rule’?
        49. What is selector?
        50. What is CLASS selector?
        51. What is CSS declaration?
        52. What is ‘important’ declaration?
        53. What is cascade?
        54. Are Style Sheets case sensitive?
        55. How do I have a non-tiling (non-repeating) background image?
        56. CSS is clearly very useful for separating style from content …
        57. I always wanted to have “included” substyles or “aliases” in my CSS definition, to save redundancy …
        58. Styles not showing?
        59. How do I quote font names in quoted values of the style attribute?
        60. Why is my external stylesheet not working ?
        61. What can be done with style sheets that can not be accomplished with regular HTML?
        62. How do I make my div 100% height?
        63. What is property?
        64. How do I write my style sheet so that it gracefully cascades with user’s personal sheet ?
        65. What are pseudo-elements?
        66. As a developer who works with CSS every day …
        67. How can I make a page look the same in e.g. NS and MSIE ?
        68. Is there anything that CAN’T be replaced by Style Sheets?
        69. Can I include comments in my Style Sheet?
        70. What is the difference between ID and CLASS?
        71. How to make text-links without underline?
        72. How do you make a tooltip that appears on hover?
        73. Which characters can CSS-names contain?
        74. What is cascading order?
        75. What browsers support style sheets? To what extent?
        76. Why shouldn’t I use fixed sized fonts ?
        77. How do you make a whole div into a link?
        78. How do I have links of different colours on the same page?
        79. What is shorthand property?
        80. How to use CSS building a standards based HTML template?
        81. What is value?
        82. What is initial value?
        83. How frustrating is it to write a specification knowing that you’re at the browser vendors’ mercy?
        84. How far can CSS be taken beyond the web page–that is, have generalized or non-web specific features for such things as page formatting or type setting?
        85. How To Style Table Cells?
        86. How To Style Forms?
        87. How do I get my footer to sit at the bottom…?
        88. Can I attach more than one declaration to a selector?
        89. Border around a table?
        90. How do you target a certain browser?
        91. How does inheritance work?
        92. What is the percentage value in ‘font-size’ relative to?
        93. What is wrong with font-family: “Verdana, Arial, Helvetica”?
        94. How do I centre my page?
        95. Must I quote property values?
        96. Do any WYSIWYG editors support the creation of Style Sheets? Any text-based HTML editors?
        97. Which style specification method should be used? Why?
        98. Justified Text?
        99. Why can @import be at the top only?
        100. Colored Horizontal Rule?
        101. Do URL’s have quotes or not?
        102. To what are partial URLs relative?
        103. What’s the difference between ‘class’ and ‘id’?
        104. I made a 10px-high div, but IE makes it 20px high…
        105. How do I place two paragraphs next to each other?
        106. Can you use someone else’s Style Sheet without permission?
        107. I want my page fonts to look the same everywhere as in…
        108. When is auto different from 0 in margin properties?
        109. How do I move the list bullet to the left/right?
        110. How does a simple CSS style rule look ?
        111. Why are there gaps above and below my form in IE?
        112. If one were to set Text and Link colors using a style sheet, should one also define the background colors for these elements as well?
        113. How do you override the underlining of hyperlinks?
        114. How do you show which page you’re on (in a menu)?
        115. How can I specify two different sets of link colors?
        116. How can I place multiple blocks next to each other?
        117. Document Style Semantics and Specification Language (DSSSL)?
        118. What is Extensible Stylesheet Language (XSL)?
        119. Which font names are available on all platforms ?
        120. Why does Netscape lose my styles ?
        121. Why is it my ‘:hover’ declaration for links does not work ?

        Dojo Tool Kit

        1.What is and Why Dojo Toolkit ?

        • Dojo toolkit is open source DHTML toolkit written in JavaScript. In other words, it is a set of JavaScript libraries.
        • Dojo toolkit aims to solve some long-standing historical problems with DHTML such as browser incompatibility.
        • Dojo toolkit also allows you easily add dynamic capabilities into the web pages by the usage of pre-built widgets and animations.
        • Because it is client-side technology, it can work with any server side technology.

        2.What is Dojo Toolkit ?

        • Open Source DHTML toolkit written in JavaScript.
        • It is a set of JavaScript libraries.
        • Aims to solve some long-standing historical problems with DHTML – Browser incompatibility.
        • Allows you to easily build dynamic capabilities into web pages ie. Widgets, Animations.
        • You can use Dojo toolkit to make your web applications to be more usable, responsive, and functional.
        • Using Dojo toolkit is one of the most effective means of building AJAX based Web applications.
        • Dojo provides lots of plumbing facilities, for example, it hides low-level XMLHttpRequest processing.
        • It also handles browser incompatibilities.

        3. Why Dojo Toolkit ?

        • You can use Dojo to make your web applications more useable, responsive, and functional Supports AJAX.
        • Dojo provides lots of plumbing facilities i.e.Hides XMLHttpRequest processing, Handles browser incompatibilities.
        • Dojo provides powerful AJAX-based IO abstraction. What this means is that it handles asynchronous communication
          through the usage of XMLHttpRequest. Again this is called remoting.
        • It provides hooks for backward, forward, bookmarking support.
        • Its event system is pretty powerful, for example, it lets you to invoke your event handler before or after an event occurs.
          This is called “aspect-oriented” event system.
        • It does provide markup based UI constructions through widgets. You can also build and reuse widgets that you built or built by someone else.
        • It does support animation. And again, Dojo toolkit comes with lots of useful JavaScript libraries.

        4. Features of Dojo Toolkit ?

        • Powerful AJAX-based I/O abstraction (remoting).
        • Graceful degradation.
        • Backward, forward, bookmarking support.
        • Aspect-oriented event system.
        • Markup-based UI construction through widgets.
        • Widget prototyping.
        • Animation

        5.List out the Dojo Toolkit Libraries ?

        dojo.io: AJAX-based communication with the server
        dojo.event: unified event system for DOM and programmatic events
        dojo.lang: utility routines to make JavaScript easier to use.
        dojo.string: String manipulation routines
        dojo.dom: DOM manipulation routines
        dojo.style: CSS Style manipulation routines
        dojo.html: HTML specific operations
        dojo.reflect: Reflection API
        dojo.date: Date manipulation
        dojo.logging.Logger: Logging library
        dojo.profile: JS Profiler
        dojo.regexp: Regular Expression generators
        dojo.dad: Drag and Drop
        dojo.collections: Collection data structures
        dojo.crypto: Cryptographic API
        dojo.reflection: Reflection routines
        dojo.math: Mathematic routines
        dojo.storage: Storage routines
        dojo.uri: URL handling routines
        dojo.widget: Widget framework

        6.Explain Event System in Dojo ?

        Dojo’s event system offers a refreshing alternative to the normal JavaScript events. With Dojo, you connect functions to one another, creating a link that calls one function when another fires.

        dojoAttachEvent

        dojoAttachEvent allows you to specify DOM event handlers in a very concise manner:

        dojo.webui.widgets.MyWidget = function() {

        this.templateString = ‘<div dojoAttachPoint=”divNode”
        dojoAttachEvent=”onClick; onMouseOver: onNode;”></div>’;
        }

        In other words, for a widget that contains the above templateString, there is a div node, that will listen for onclick and onmouseover DOM events. The onclick event will be routed to a handler called onClick for that widget, while the onmouseover event will be routed to handler onNode

        dojo.webui.widgets.MyWidget = function() {

        this.onClick = function(evt) {
        // do something when clicking on the div for this widget
        }

        this.onNode = function(evt) {
        // do something else when mousing over the div for
        // this widget
        }

        }

        Note that onNode and onClick are just arbitrary names of methods in the widget. The limitation of dojoAttachEvent is that it only currently works for binding from DOM events.

        dojo.event.connect

        dojo.event.connect is a mechanism for connecting a dom event or method call to another event handler or method call:

        dojo.webui.widgets.MyWidget = function() {

        dojo.event.connect(this.divNode, “onclick”, this, “onClick”);
        dojo.event.connect(this, “onClick”, this, “onNode”);
        dojo.event.connect(widgetBar, “onBar”, this, “onNode”);

        }

        The first connect method above does the same thing as the example above defined with dojoAttachEvent.
        The second one is more interesting, as it connects the onClick handler method to another method called onNode.
        The third example shows how you might connect any two method from any two objects.

        dojo.event.topic

        Say you have a case where you have a number of widgets in a document, and you want them all to be able to listen for the same event, and also push events to the other widgets that are listening. With the normal dojo.event.connect, you would need to create a connection between each set of widgets manually. Instead, you just do the following:

        // to send/publish an event to the topic
        dojo.event.topic.publish(“recordFound”, newRecord);
        // to listen/subscribe to all events published to a topic
        dojo.event.topic.subscribe(“recordFound”, this, “onNode”);

        disconnect and unsubscribe

        To remove an event connection or a topic subscription, dojo.event.disconnect and dojo.event.topic.unsubscribe take exactly the same parameters as their counterparts.

        Explain DTD

        A document type definition (DTD) describes the permissible tags of an XML document.

        The DTD serves as a data template. It defines entities, elements, attributes, and notations, as well as the relationships between these.

        For example, the DTD can state that a memo element consists of To, From, Subject, and Message elements.

        You need to use a DTD if you want the XML processor to validate your XML documents.

        DTDs can help you ensure that your XML documents are well-formed.

        You need to indicate to the XML processor that a DTD should be used. This is done by adding a document type declaration before the document element.

        The DTD can be internal or external to the document. If the DTD is external, you will need to specify its location or URL.

        Is an XML schema an alternative to DTD

        Schemas are becoming more popular and DTDs less so. A schema is an XML-based syntax for describing how the XML document is marked up or how it looks – very similar to a DTD, but a DTD has a lot of drawbacks.
        A DTD doesn’t use anything like XML syntax to describe the definition. You can’t do data typing in a DTD, and it’s not extensible.

        An XML schema allows you to specify elements as an integer, a float, a Boolean, or whatever, and has more extensibility to it. Plus, it’s in XML format. Your XML schema, the definition for your XML, is also in XML format.
        Microsoft is pushing the XML schema – so you’re likely to see schemas more and more. That’s all we use. In fact, the new BizTalk Server from Microsoft actually uses schemas.

        Explain XML Namespaces

        An XML namespace is a collection of element names or attribute names to be defined within an XML document.
        Let’s say you have an invoice XML document and an order XML document and you want to put them together. You usually have certain names that overlap each other – like the date. You might have an invoice date and an order date – both called “date”.

        With a namespace, you have an invoice date and an order date, and you can reference them as such – “invoice:date” and then “order:date.” That way you can still use the same two tag names and you won’t get confused about which is which. That’s really what an XML namespace is supposed to do for you.

        What are the advantages of XML

        XML is free form which means that you can configure it any way you want. It’s also very easy to read – you don’t have to read cryptic code to figure it out.
        It was designed specifically for internet protocols, and this makes it simple to transmit an XML document across, for example, a HTTP protocol.
        Strong data typing is available for xml, and it is also compatible with the SGML standard.

        XML is Application independent – you can transfer XML data from a C language program to a Visual Basic program. Or you could, for example, have XML data going from one server out across the internet and being picked up by another application running on a Unix box. XML is also platform independent – it works equally well on Windows, UNIX, or for example, a CICS on a mainframe.
        XML is also language independent so it doesn’t matter what type of programming language you’re using – C, Visual Basic, ASP using JavaScript. It doesn’t matter – all have mechanisms to read an XML document.

        XML is Unicode-based which makes it very flexible and very good for operating across languages like English, Spanish, or French. You can describe all these types of languages since it’s in Unicode.
        A huge benefit of XML is that it’s license free –
        it doesn’t cost anything to use XML.

        Differences between DTD and Schema

          XML Schema DTD
        Markup validation Any global element can be root. No ambiguous content support. Can specify only the root element in the instance document. No ambiguous content support.
        Namespace support Yes. Declarations only where multiple namespaces are used. No.
        Code reuse Can reuse definitions using named types. Poorly supported. Can use parameter entities.
        Datatype Validation Provides flexible set of datatypes. Provides multi-field key cross references. No co-occurrence constraints. No real datatype support.

        What are the disadvantages of DTD

        • They are not written in XML syntax, which means you have to learn a new syntax in order to write them
        • there is no support for namespaces
        • there are no constraints imposed on the kind of character data allowed, so datatyping is not possible
        • there is minimal support for code modularity and none for inheritance
        • large DTDs are hard to read and maintain
        • there are no default values for elements and attribute defaults must be specified when they are declared
        • its attribute value models and ID attribute mechanism are simplistic
        • there is limited ability to control whitespace
        • there is limited documentation support, as you cannot use the structured documentation features available for schema notation

        Exception Drill

        1. What is an Exception ?
        An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error.

        2. What is a Java Exception ?
        A Java exception is an object that describes an exceptional condition i.e., an error condition that has occurred in a piece of code. When this type of condition arises, an object representing that exception is created and thrown in the method that caused the error by the Java Runtime. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed.

        3.Where does Exception stand in the Java tree hierarchy ?
                 java.lang.Object
                 java.lang.Throwable
                 java.lang.Exception
                 java.lang.Error

        4.What are checked exceptions ?
        Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.

        5.What are runtime exceptions ?
        Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.

        6.What is the difference between error and an exception ?
        An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).

        7.How to create custom exceptions ?
        Your class should extend class Exception, or some more specific type thereof.

        8.If I want an object of my class to be thrown as an exception object, what should I do ?
        The class should extend from Exception class. Or you can extend your class from some more precise exception type also.

        9.If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object ?
        One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.

        10.How does an exception permeate through the code ?
        An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.

        11.What are the different ways to handle exceptions ?
        There are two ways to handle exceptions,
        1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
        2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.

        12.What is the basic difference between the 2 approaches to exception handling.
        1 try catch block and
        2 specifying the candidate exceptions in the throws clause ?
        In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it’s own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.

        13.Is it compulsory to use the finally block  ?
        It is always a good practice to use the finally block. The reason for using the finally block is, any unreleased resources can be released and the memory can be freed. For example while closing a connection object an exception has occurred. In finally block we can close that object. Coming to the question, you can omit the finally block when there is a catch block associated with that try block. A try block should have at least a catch or a finally block.

        14.How are try, catch and finally block organized  ?
        A try block should associate with at least a catch or a finally block. The sequence of try, catch and finally matters a lot. If you modify the order of these then the code won’t compile. Adding to this there can be multiple catch blocks associated with a try block. The final concept is there should be a single try, multiple catch blocks and a single finally block in a try-catch-finally block.

        15.What is a throw in an Exception block ?
        “throw” is used to manually throw an exception (object) of type Throwable class or a subclass of Throwable. Simple types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.

        throw ThrowableInstance; ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
        throw new NullPointerException(“thrownException”);

        16.What is the use of throws keyword ?
        If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw.

        type method-name(parameter-list) throws exception-list {
        // body of method
        }

        Here, exception-list is a comma-separated list of the exceptions that a method can throw.

        static void throwOne() throws IllegalAccessException {
        System.out.println(“Inside throwOne.”);

        17.Is it necessary that each try block must be followed by a catch block ?
        It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

        18.If I write return at the end of the try block, will the finally block still execute ?
        Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.

        19.If I write System.exit (0); at the end of the try block, will the finally block still execute ?
        No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.

        20.What are Checked and UnChecked Exception ?
        A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
        Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream’s read() method·
        Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn’t force client programmers either to catch the
        exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String’s charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

        21.Give me some examples of Checked Exceptions and Unchecked Exceptions ?
        Unchecked Exceptions. 
                 ArithmeticException 
                 ArrayIndexOutOfBoundsException
                 ClassCastException
                 IndexOutOfBoundsException
                 IllegalStateException
                 NullPointerException
                 SecurityException 

        Checked Exception
                ClassNotFoundException
                CloneNotSupportedException 
                IllegalAccessException
                InstantiationException
                InterruptedException
                NoSuchFieldException
                NoSuchMethodException

        22. What are Chained Exceptions ?
        The chained exception feature allows you to associate another exception with an exception. This second exception describes the cause of the first exception. Lets take a simple example. You are trying to read a number from the disk and using it to divide a number. Think the method throws an ArithmeticException because of an attempt to divide by zero (number we got). However, the problem was that an I/O error occurred, which caused the divisor to be set improperly (set to zero). Although the method must certainly throw an ArithmeticException, since that is the error that occurred, you might also want to let the calling code know that the underlying cause was an I/O error. This is the place where chained exceptions come in to picture.

        Throwable getCause( )
        Throwable initCause(Throwable causeExc)

        Collections Drill – II

        1.What is meant by compatible equals() and hashCode() methods ?
        In order for the Java Collections to work properly (and everything else in Java), the equals() and hashCode() methods must be compatible. Here, compatible means that if equals() reports that two instances are the same, then the hashCode() of both instances must be the same value.

        2.Since Properties extends Hashtable, can I use the Hashtable methods to add elements to a Properties list ?
        Technically speaking you can. However, you have to make sure you only add key-value pairs where both are strings. If you add something other than a String, the listing, loading, and saving methods won’t work as expected.
        Like the Stack/Vector subclass relationship, Properties/Hashtable should be a has-a relationship, not an is-a/subclass relationship.

        3.When I wrap a collection to be read-only or synchronized, why can’t I call any of the collection methods via reflection without getting an IllegalAccessException ?
        When you wrap a collection through the static methods of the Collections class, this creates an instance of a package-private (default access) class. Because you don’t have access to these classes, you can’t call their methods via reflection (though you can call their methods directly through the appropriate interface).

        4.What is a weak reference and what are they used for ?
        Normally the Java garbage collector plays safe. It will only free up the memory used by an object when that object can no longer be accessed by the program. Once an object become impossible to reach it is eligible for collection, and eventually its memory will be reclaimed.
        This eliminates one of the most common programming errors in some other languages (like C++), where code accidentally tries to access an object that has been freed. Unfortunately it can lead to another problem, where you leave open a potential access route to an object that you don’t need any more. Memory fills up, and the program slows down or reports an “Out of Memory” error.

        To avoid this, you can be very careful to close off access paths to an object once you have finished using it. Java 2 introduces another alternative, the weak reference. Weak references provide access to an object without preventing it from being freed. When you use a weak reference you have to accept that the object referred to may have disappeared, which results in the reference being automatically set to null. On the other hand, the weak reference will not hold the object in memory once it is inaccessible via normal references (or via “soft” references – see below). Weak references are not appropriate in all circumstances, but sometimes they can make code easier to write and understand.

        The most common use of weak references is indirect – they are used internally by the WeakHashMap class. Like HashMap, WeakHashMap associates key objects with values. However, once the key object becomes inaccessible via stronger references it becomes eligible for garbage collection. When it is freed, the map entry magically disappears. The assumption here is that if you are not using the key anywhere other than in the map you will have no need to look it up, so it should be freed.

        Other specialist references are soft references (which inhibit collection until memory runs short), and phantom references (used for cleanup when objects are freed).

        5.What is the minimum number of key-value pairs for which it makes sense to use a HashMap, as opposed to using a pair of arrays (one for keys, the other for values) with brute-force key searches ?

        Many people often need maps for very small numbers (2-5) of key-value pairs. When does it make sense to forgo the convenience of the HashMap to avoid the associated overhead?
        Well, is there really that much of a performance loss using a HashMap? There is no synchronization penalty (unless you impose your own). You can tune the sizing by adjusting the initial size and load factor. Plus, do you really want to be responsible for “rolling your own” code to handle the dynamic resizing of the key and value arrays, inserting/removing data from these arrays, optimizing the searching algorithm, etc. Yuck!

        In general, the performance hit associated with using a general purpose Map (such as the HashMap) is far outweighed by the benefits of using a simple interface backed by a tested algorithm.

        The only reason I could see wanting to use arrays is to guaruntee the type of your key/values to add type checking and avoid casting. Still, if this is a critical aspect of your application, you can wrap your HashMap in another object to provide type-safety, and the casting overhead should be minimal.

        Another alternative to creating a custom solution is to explore other collection classes, such as ObjectSpaces’s JGL Libraries. There may be something there that would suit your needs.

        So, to answer your question, I would say that the fewer the key-value pairs you have, the more reason you have to use a HashMap. Since the fewer the keys, the faster the search, why not use it for 2-5 key-value pairs. I would think that only when you get to many pairs (tens of thousands) and there is a performance problem you should consider an alternative. Basically, exhaust your search of tried-and-true collections before you try a custom solution. Let other people create these collections so you can focus on your application.

        6.How does ArrayList increase its capacity ?
        Unlike Vector where you can specify a capacity increment, ArrayList doesn’t support this. Instead, ArrayList will increase capacity by about a half when it runs out of space. The refernece implementation uses the forumla:
        newCapacity = (oldCapacity * 3)/2 + 1
        though, this isn’t part of the class definition so others can implement it differently.

        7.What is the default initial size for a Hashtable / HashMap ?
        This depends on what version of Java you are using. For JDK 1.2, the size was 101. For JDK 1.3, the size changed to 11.

        8.How do you create a multi-dimensional List ?
        Since the elements of a List are objects, in order to make the List multi-dimensional, each object in the outer list needs to be a List, too. For instance, …

        List list = new ArrayList(10);
        for (int i=0; i<10; i++) {
        list.set(i, new LinkedList());
        }

        Then just fill up each inner list with items.

        9.In a TreeMap, can I use a sorting algorithm other than the natural sorting for the keys ?
        You can pass a Comparator to the TreeMap constructor to use a sorting order other than the natural order.

        10.What are the differences between HashMap and Hashtable ?
        Both provide key-value access to data. The Hashtable is one of the original collection classes in Java. HashMap is part of the new Collections Framework, added with Java 2, v1.2.
        The key difference between the two is that access to the Hashtable is synchronized on the table while access to the HashMap isn’t. You can add it, but it isn’t there by default.

        Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t. If you change the map while iterating, you’ll know.

        And, a third difference is that HashMap permits null values in it, while Hashtable doesn’t.

        For new code, I would tend to always use HashMap.

        11.What are the differences between Vector and ArrayList? Which is best to use ?
        Vector and ArrayList are very similar. Both of them represent a ‘growable array’, where you access to the elements in it through an index.

        ArrayList it’s part of the Java Collection Framework, and has been added with version 1.2, while Vector it’s an object that is present since the first version of the JDK. Vector, anyway, has been retrofitted to implement the List interface.

        The main difference is that Vector it’s a synchronized object, while ArrayList it’s not.

        While the iterator that are returned by both classes are fail-fast (they cleanly thrown a ConcurrentModificationException when the orignal object has been modified), the Enumeration returned by Vector are not.

        Unless you have strong reason to use a Vector, the suggestion is to use the ArrayList.

        12.How should I implement object comparisons in a flexible manner? For example, I have a Person class and sometimes I will compare based on name and sometimes I will compare based on age.
        Instead of having the Person class implement the Comparable interface, you could delegate the comparing to another class. Perhaps you could have a PersonComparator interface that you could implement for the various types of comparisons. For example:
        public interface Person {
        public String getName();
        public int getAge();
        }

        public interface PersonComparator {
        public int compare(Person p1, Person p2);
        }

        public class AgeComparator implements PersonComparator {
        public int compare(Person p1, Person p2) {
        if (p1.getAge() == p2.getAge()) return 0;
        return p1.getAge() > p2.getAge() ? 1 : -1;
        }
        }

        public class NameComparator implements PersonComparator {
        public int compare(Person p1, Person p2) {
        return p1.getName().compareTo(p2.getName());
        }
        }

        This is a very simple example of the Strategy Pattern. This allows your comparisons and your object to change independent of one another.

        13.Does the equals() method of an array do element-level checking ?
        If you have two arrays in memory with the same elements, and ask first.equals(second), this does not do an element-by-element comparison. Instead, it behaves just like Object’s equals() method, essentially asking if the variables point to the same place in memory:
        int a[] = {1, 2, 3};
        int b[] = {1, 2, 3};
        // This prints false
        System.out.println(a.equals(b));

        To check for equality of two arrays, use Arrays.equals().
        // This prints true
        System.out.println(Arrays.equals(a,b));

        14.How can I retrieve the items in my HashSet / HashMap in the order they were added ?
        Prior to Java 1.4, you had to manage a separate insertion order list yourself. Starting with Java 1.4, you can use the new LinkedHashMap / LinkedHashSet classes. The iterators you get back from them return the items in insertion order.

        15.How do you sort an ArrayList (or any list) of user-defined objects ?
        Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator).

        16.How can you get the hash code for an instance of a class if the class overrode hashCode() ?
        The System class method identityHashCode() allows you to get this information:
        int code = System.identityHashCode(anObject);

        17.How can I easily shift the elements in a List / Vector such that all the elements rotate n elements ?
        The Java 1.4 API adds a rotate() method to the Collections class: rotate(List list, int distance) that will shift the elements for you.

        18.What’s the most optimum way of swapping two elements in a List ?
        The 1.4 version of Collections has a swap() method to do this for you. However, for earlier version of Java, you can swap two elements w/o an intermediate variable with:
        list.set(index1, list.set(index2, list.get(index1)));
        This works because the set() method returns the original element.

        19.What’s the purpose of the IdentityHashMap ?
        The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.

        20.How do I convert an old-style Enumeration to something in the Collections Framework ?
        Prior to Java 1.4, any conversion had to be manually done. With the introduction of 1.4, you can call Collections.list(enumeration) to automatically convert the Enumeration to an ArrayList.

        21.How do I retrieve the values of a Hashtable/HashMap in sorted order ?
        Basically, you can’t directly do this. What you can do is get the Collection of values() back from the map and create a sorted collection, or maintain two maps, one in each direction, and keep the second map sorted by being a TreeMap. Which you use depends on the frequency you must sort the elements.

        22.How can I add a Collection to another Collection ?
        The java.util.Collection interface includes an addAll(Collection c) method to add one collection to another.

        23.How can I use two iterators to go through a collection ?
        Just get a separate iterator for each loop:
        Collection l = …;
        for(Iterator i = l.iterator(); …) {
        for(Iterator j = l.iterator();…) {
        }
        }

        24.How do I traverse a map backwards ?
        Just keep getting the last key and the head map before it:
        if (!map.isEmpty()) {
        Object last = map.lastKey();
        boolean first = true;
        do {
        if (!first) {
        System.out.print(“, “);
        }
        System.out.print(last);
        last=map.headMap(last).lastKey();
        first=false;
        } while (last != map.firstKey());
        System.out.println();
        }

        25.How do I traverse a sorted set backwards ?
        Just keep getting the last element and the head set before it:
        if (!set.isEmpty()) {
        Object last = set.last();
        boolean first = true;
        do {
        if (!first) {
        System.out.print(“, “);
        }
        System.out.print(last);
        last=set.headSet(last).last();
        first=false;
        } while (last != set.first());
        System.out.println();
        }

        26.How can I go through an Iterator mulitple times ?
        There is no direct support for this. You’ll need to create your own caching mechanism. For instance, as you go through the Iterator the first time, add the elements to a LinkedList. Then, you can just get an Iterator from the LinkedList for the second pass through.

        27.What’s new to the Collections Framework in Java 1.4 ?
        There are three new implementations:
                  LinkedHashSet
                  LinkedHashMap
                  IdentityHashMap
                 One marker interface: 
                 RandomAccess
                And six new utility methods for the Collections class:
                rotate(List list, int distance)
                replaceAll(List list, Object oldVal, Object newVal)
                indexOfSubList(List source, List target)
                lastIndexOfSubList(List source, List target) 
               swap(List list, int i, int j) 
               list(Enumeration e)

        28.How can I add an array of objects to a collection ?
        First you need to convert the array to a Collection. This can be done with Arrays.asList(objectArray). Once you have the array as a List, you can add it to another Collection with theCollection.addAll(theList).

        29.Is Vector’s clone method thread-safe ?
        Sure it is, since it is a Vector which is thread-safe.

        30.How do I load property settings with the Properties class ?
        java.util.Properties objects can load values from a file using the method load(InputStream).
        Here is the code you need:

        Properties props = new Properties();
        props.load(new FileInputStream(“propertyfile.properties”));
        String value = props.getProperty(“propertyname”);

        //Just a trick: in a web archive (war) you can get the InputStream inside the war archive using
        ClassLoader cl = this.getClass().getClassLoader();
        InputStream is = cl.getResourceAsStream(“it/package/application.properties”);

        This is better than using a FileInputStream, because you are loading the file within the archive as it was a resource. You should use this.getClass().getClassLoader() to use the same ClassLoader as the one used the servlet container to load your JSP/Servlet. This code is snipped from a JSP page inside Tomcat.

        31.How do I save properties settings with the Properties class ?
        Try this:
        Properties prop = new Properties();
        FileOutputStream output = new FileOutputStream(“Test.properties”);
        prop.store(output,”my testproperties”);
        output.flush();
        output.close();

        You’ll need to catch an IOException.

        32.What happens if two threads perform a get of one hashmap at the same time ?
        Synchronization needs to be done only when there is a chance of changing the data from different threads simultaneously. In your case, it is simply going to be a read, the synchronization is not required. If you need to remove or modify the values in the hashmap, then you [may] need to synchronize that.

        For synchronizing a HashMap, you can use Collections.synchronizedMap(<your hashmap reference>) which will return a synchronized map for you, which is thread-safe.

        Remember, synchronization will cause a performance problem. So, it needs to be used carefully, when really required.

        33.How can I convert a Collection to an Array then back to a Collection ?
        The Collection interface provides a mechanism to turn a Collection into an Array using the methods <T> T[] toArray(T[] a) or Object[] toArray(). The first method will return a Array containing all the elements of the Collection with the array being that of the type provided in the method call. The second method just returns an array being of an Object[] type.

        The Arrays class provides the opposite. A way to turn an array into a List using the List<T> asList(Array[] a) method. The List returned is of a fixed length with any attempts to add an element throwing an UnsupportedOperationException.

        import java.util.*;

        public class G{
        public static void main(String[] args){
        List<String> sun = new ArrayList<String>();
        sun.add(“Feel”);
        sun.add(“the”);
        sun.add(“power”);
        sun.add(“of”);
        sun.add(“the”);
        sun.add(“Sun”);
        String[] s1 = sun.toArray(new String[0]); //Collection to array
        for(int i = 0; i < s1.length; ++i){
        String contents = s1[i];
        System.out.print(contents);
        }
        System.out.println();
        List<String> sun2 = Arrays.asList(s1); //Array back to Collection
        for(String s2: sun2){
        String s3 = s2; System.out.print(s3);
        }
        //sun2.add(new String(“Hello”)); // throws UnsupportedOperationException
        }
        }

        34.How can I create a Collection based on another Collection ?
        Every concrete implementation provides a constructor, which takes a Collection as an argument. Care must be taken when creating a Collection based another Collection, this is because depending on the target concrete implementation being created, specific rules regarding duplicates may be be enforced. Such as creating a Set based on a List.

        The following is a short list of the constructors provided by some of the concrete Classes of the JCF (Java Collections Framework), which enable the creation of a Collection based an another implementation.

        ArrayList(Collection<? extends E> c)
        LinkedList(Collection<? extends E> c)
        Vector(Collection<? extends E> c)
        TreeSet(Collection<? extends E> c)

        Creating a Collection based on another Collection is quite easy. The hard part is knowing which Collection to use based on performance and other issues.

        For example the ArrayList created will contain the same elements in the same order as the first ArrayList created.

        List<String> slist = new ArrayList<String>();
        slist.add(“g”);
        slist.add(“a”);
        slist.add(“d”);
        slist.add(“a”);
        slist.add(“f”);
        slist.add(“e”);
        slist.add(“c”);
        slist.add(“b”);
        for(String s : slist){
        System.out.print(s + “\t”);
        }
        System.out.println();
        List<String> s2list = new ArrayList<String>(slist);
        for(String s : s2list){
        System.out.print(s + “\t”);
        }

        When creating a Set based on an existing List the Set will be void of duplicates.
        List<String> slist = new ArrayList<String>();
        slist.add(“g”);
        slist.add(“a”);
        slist.add(“d”);
        slist.add(“a”);
        slist.add(“f”);
        slist.add(“e”);
        slist.add(“c”);
        slist.add(“b”);
        for(String s : slist){
        System.out.print(s + “\t”);
        }
        System.out.println();
        Set<String> s2set = new TreeSet<String>(slist);
        for(String s : s2set){
        System.out.print(s + “\t”);
        }

        35.How can I define my own Comparable type so that it can be naturally sorted within a List ?
        When taking a peek at the Java docs you will notice certain classes implement an interface named Comparable. Take a look at some of the subclasses of Number such as Byte, Integer, Long, Float or some of the classes like String and Date. What the Comparable interface provides is a way for a class to be sorted by it’s natural ordering. So what do we mean by natural ordering? Depending on the type wishing to be sorted the natural ordering can be different things. If we are sorting Strings the ordering is lexicographic or alphabetic if we are sorting Dates the ordering is chronological if we are sorting Integers the ordering is numerical.

        Comparable only contains one method that needs to be implemented by the class wishing to be sorted naturally. Remember if you try and sort a list that contains elements that do not implement the Comparable interface then Collections.sort() will throw an exception specifically a ClassCastException.

        public interface Comparable<T>{
        public int compareTo(T o);
        }

        The following is a short example on how to implement the Comparable interface and use the compareTo(T o) method.
        import java.util.*;

        public final class Alpha implements Comparable<Alpha>{
        public static void main(String[] args){
        List<Alpha> alpha = new ArrayList<Alpha>();
        alpha.add(new Alpha(“z”));
        alpha.add(new Alpha(“g”));
        alpha.add(new Alpha(“k”));
        alpha.add(new Alpha(“q”));
        alpha.add(new Alpha(“a”));
        alpha.add(new Alpha(“b”));
        alpha.add(new Alpha(“o”));
        alpha.add(new Alpha(“v”));
        alpha.add(new Alpha(“c”));
        Collections.sort(alpha);
        System.out.println(alpha);
        }
        private String letter;
        public Alpha(String letter){
        if(letter == null){throw new NullPointerException();}
        this.letter = letter;
        }
        public String toString(){return letter;}
        public boolean equals(Alpha a){
        if(!(a instanceof Alpha))
        return false;
        return letter.equals(a.letter);
        }
        public int compareTo(Alpha a){
        int i = letter.compareTo(a.letter);
        return i;
        }
        }

        More complex examples might included sorting on multiple fields. Most things that you would have to sort probably have more then one part like a name for instance (First:Middle:Last) or maybe you have to sort in (Brand:Model) order.
        import java.util.*;

        public final class Car implements Comparable<Car>{
        public static void main(String[] args){
        Car[] cararry = {new Car(“Toyota”,”Celica”), new Car(“Honda”,”Civic”),
        new Car(“Ford”,”Mustang”), new Car(“Lexus”,”ES”), new Car(“Acura”,”Integra”),
        new Car(“Honda”,”Accord”), new Car(“Acura”,”RL”), new Car(“Toyota”,”Avalon”)
        };
        List<Car> car = Arrays.asList(cararry);
        Collections.sort(car);
        System.out.println(car);
        }
        private String brand;
        private String model;
        public Car(String brand, String model){
        if(brand == null || model == null){throw new NullPointerException();}
        this.brand = brand;
        this.model = model;
        }
        public String toString(){return brand + ” ” + model;}
        public boolean equals(Car car){
        if(!(car instanceof Car))
        return false;
        boolean samebrand = brand.equals(car.brand);
        return samebrand != true ? samebrand: model.equals(car.model);
        }
        public int compareTo(Car car){
        int i = brand.compareTo(car.brand);
        return(i != 0 ? i : model.compareTo(car.model));
        }
        }

        36.What are Generics and how can I use them ?
        One of the biggest additions since the creation of the Collections framework is Generics.This long awaited update to the type system is a welcomed feature, which C++ developers have had in their toolbox for years using the STL. A generic type is defined using one or more type variables with it’s contained methods using that type variable as a place holder to mark a parameter or return type. For instance the interface List has now been defined as.

        public interface List<E>{
        public add(E e);
        Iterator<E> iterator();
        }
        public interface Iterator<E>{
        E next();
        boolean hasNext();
        }

        Type Safe Collections

        So you might ask. What are Generics and why should I use them? Generics are a way to restrict a data structure to hold only a specific type thus providing compile time type checking. One of the added bonuses is that it is no longer necessary to cast a returned Object to a specific type because the compiler is aware of what type is being held by the Collection and what type is to be returned.

        Set s = new SortedSet();
        s.add(new String(“Java”));
        String j = (String) s.get(0); // cast required;

        // java 5
        Set<String> s = new SortedSet<String>();
        s.addElement(new String(“String Type”));
        String s = s.get(0); // no cast required!

        Having a type safe system not only obviates the need to cast to a specific type but shields the programmer against miss-casting or casting to an unrelated type at runtime.

        String s = “Java, write once run anywhere”
        List l = new ArrayList();
        l.add(new String(“Java”));
        Integer i = (Integer)l.get(0); // Runtime exception! ClassCastException!

        // Using Generics the compiler catches
        String s = “Java. Write once run anywhere!”
        List<String> l = new ArrayList<String>();
        l.add(new String(“Java”));
        Integer i = l.get(0);

        Generics and Subtyping

        Generics do not share some of the things that are commonly held true in the Java language and one of them is subtyping. One would assume the following perfectly legal since it is true that Object is a supertype of String. But the following is in fact illegal and will cause a compile time error.

        List<Object> l = new ArrayList<String>();

        As a rule. If X is a superclass or superinterface of Y and E is a generic type declaration then it not the case that E<X> is a supertype of E<Y>. So if E<Object> is not a super type of E<String> then what is the super type of E<String>? Read on and find out!

        Wild Cards

        Wild Cards represent what is called “the unknown type”. Essentially they can be thought of as the supertype of any Collection. Wildcards allow some flexibility in certain situations where it is needed that a type be abstracted out. For instance what if we define the following method, printSet(Collection<Object> x). We just saw in the previous example that E<Object> is not the super type of E<String> or any other type for that matter. In this case we can change the printSet’s parameter to Collection<?>. This allows us to pass in E<X> where X is any type.

        public void printElements(Collection<?> c){
        for(Object o: c){
        System.out.println(o);
        }
        }

        When working with wildcards it is always legal to read and assign the contents to an Object type

        List<String> l = new ArrayList<String>();
        l.add(new String(“Java”));
        Object o = getElement(l, 0); // legal

        public Object getElement(List<?> l, int index){
        Object o = null;
        try{
        o = l.get(0);
        }catch(IndexOutOfBoundsException e){
        //…….
        }
        return o;
        }

        assigning values is another matter. The add() method takes an argument of type E which is the type that the Collection is to hold. Any type wishing to be added to the Collection would have to be of the same type. Since<?> represents an unknown type it is impossible to determine what the type parameter of the collection represents.

        Bounded Wildcards

        A Bounded Wildcard allows as type to be constrained. Bounded Wildcards are useful when there is some type of partial knowledge about the type arguments. While it is still illegal to try and add an element to a unknown Collection with a bounded type they come in handy in other situations. One use is to be able to pass not only types into a method but sub-types also. In doing this we are able to implement polymorphic behavior.

        import java.util.*;

        class Printer{
        public void print(String s){
        for(int i = 0; i < s.length(); i++){
        System.out.print(s.charAt(i));
        }
        }
        }
        class ReversePrinter extends Printer{
        public void print(String s){
        for(int i = s.length() – 1 ; i >= 0; i–){
        System.out.print(s.charAt(i));
        }
        }
        }
        public class G{
        public static void main(String[] args){
        String s = “Nothing like a good cup of Java in the morning!”
        List<Printer> l = new ArrayList<Printer>();
        l.add(new Printer());
        printElements(l,s);
        List<ReversePrinter> rl = new ArrayList<ReversePrinter>();
        rl.add(new ReversePrinter());
        printElements(rl,s);
        }
        public static void printElements(List<? extends Printer> l, String s){
        Printer printer = l.get(0);
        printer.print(s);
        System.out.println();
        }
        }

        37.How can I shuffle the elements of a Collection ?
        The Collections class which can be found within the java.util namespace provides two methods which suffle the elements of a Collection.

        static void shuffle(List<?> list)
        static void shuffle(List<?> list, Random rnd)

        The first method shuffles the elements according to a default source of randomness, with the second using a specified source of randomness.
        import java.util.*;

        public class ShuffleTest{
        public static void main(String[] args){
        List<String> sl = new ArrayList<String>();
        sl.add(“One”);
        sl.add(“Two”);
        sl.add(“Three”);
        sl.add(“Four”);
        sl.add(“Five”);
        sl.add(“Six”);
        for(String s: sl){
        System.out.println(s);
        }
        System.out.println();
        Collections.shuffle(sl);
        for(String s: sl){
        System.out.println(s);
        }
        }
        }

        38.How can i tell if two Collections contain the same elements or have no elements in common ?
        Two methods are needed in this case.

        boolean containsAll(Collection<?> c)
        boolean disjoint(Collection<?>c1 Collection<?>c2)

        Since containsAll(Collection<?> c) is defined within the Collection interface all concrete implementations will be able to use this method. disjoint(Collection<?>c1 Collection<?>c2) is defined within the Collections class.

        Using both of these methods is pretty straightforward. containsAll(Collection<?> c) is an instance method so naturally it must be invoked on an object. disjoint(Collection<?>c1 Collection<?>c2) is defined as Static within the Collections class so all that is needed is to invoke it using the class name ie Collections.disjoint(Collection<?>c1 Collection<?>c2)

        39.How can I traverse a List backwards ?
        In order to traverse a List backwards a ListIterator must be used. The List interface provides a method, which returns a ListIterator.

        ListIterator<E> listIterator()

        Using a returned ListIterator, concrete implementations of List can be traverse backwards using the following methods.

        boolean hasPrevious()
        E previous()

        Since ListIterator extends the Iterator interface forward direction is still possible via Iterators methods.
        boolean hasNext()
        E next()

        import java.util.List;
        import java.util.ArrayList;
        import java.util.ListIterator;

        public class {
        public static void main(String[] args){
        List<String> slist = new ArrayList<String>();
        slist.add(“1″);
        slist.add(“2″);
        slist.add(“3″);
        slist.add(“4″);
        ListIterator i = slist.listIterator();
        while(i.hasNext()){
        System.out.print(i.next());
        }
        System.out.println();
        while(i.hasPrevious()){
        System.out.print(i.previous());
        }
        }
        }

        40.How can I get a sorted list of keys that are contained within a Map ?
        The Map interface defines a method named keySet() which concrete classes such as HashMap and TreeMap implement. Depending on the implementation on which keySet() is invoked the returned Set might not contain it’s elements (keys) in sorted order. For instance the HashMap class makes no guarantees as to the order of the elements contained within. Whereas the TreeMap class does guarantee element ordering since it implements the SortedMap interface.

        /* TreeMap used. Keys stored in ascending order */

        Map<String,String> book = new TreeMap<String,String>();
        book.put(new String(“Java”),new String(“A trademark used for a programming language designed to develop applications, especially ones for the Internet, that can operate on different platforms.”));
        book.put(new String(“C#”),new String(“An object-oriented language devised and promoted by Microsoft, intended to replace Java, which it strongly resembles.”));
        book.put(new String(“Python”),new String(“A simple, high-level interpreted language by Guido van Rossum”));
        book.put(new String(“LISP”),new String(“A programming language designed to process data consisting of lists. It is widely used in artificial intelligence research.”));
        Set words = book.keySet();
        for(Iterator i = words.iterator();i.hasNext();){
        System.out.print(i.next() + “\t”);
        }

        41.How can I create a read only Collection ?
        Unmodifiable Collections can be easily created using various static methods which the Collections class provides. Any attempts to modify the returned Collection, whether direct or via its iterator, result in an UnsupportedOperationException.

        Collection<T> unmodifiableCollection(Collection<? extends T> c)
        List<T> unmodifiableList(List<? extends T> list)
        Set<T> unmodifiableSet(Set<? extends T> s)
        SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)

        import java.util.*;

        public class Unmod{
        public static void main(String[] args){
        List<String> strlist = new ArrayList<String>();
        strlist.add(“C”);
        strlist.add(“B”);
        strlist.add(“A”);
        Collection<String> unmodstrlist = Unmod.makeUnmodifiable(strlist);
        // unmodstrlist.add(“G”); throws UnsupportedOperationException
        Set<String> strset = new TreeSet<String>();
        strset.add(“C”);
        strset.add(“B”);
        strset.add(“A”);
        Collection<String> unmodstrset = Unmod.makeUnmodifiable(strset);
        // unmodstrset.add(“G”); throws UnsupportedOperationException
        }
        public static Collection<String> makeUnmodifiable(Collection<String> c){
        return(Collections.unmodifiableCollection(c));
        }
        }

        42.Is there a way determine how many times an Object occurs within a Collection ?
        The Collections class provides a method which returns the number of times an Object appears within a given Collection.

        public static int frequency(Collection<?> c, Object o)

        If a null Collection is passed in then a NullPointerException is thrown.
        import java.util.*;

        public class Freq {
        public static void main(String[] args){
        List<Integer> password = new ArrayList<Integer>();
        password.add(new Integer(4));
        password.add(new Integer(6));
        password.add(new Integer(8));
        password.add(new Integer(4));
        password.add(new Integer(9));
        Integer passwordelement = new Integer(4);
        System.out.println(passwordelement + ” appears “
        + getFrequency(password,passwordelement) + ” times within password”);
        }
        private static int getFrequency(Collection c, Object o){
        return(Collections.frequency(c,o));
        }
        }

        43.What is the easiest way to obtain a Map Entry ?
        The easiest way to obtain a Map Entry or (key-value pair) is by invoking the following method provided by the Map interface.

        Set<Map.Entry<K,V>> entrySet();

        The entrySet() method returns a Set which is populated with Map.Entry objects. The only way to obtain a reference to a Map.Entry is by using an Iterator on the returned Set view. Once a reference to a Map.Entry is obtained the follow methods can be invoked which return the key and value corresponding to the entry.

        K getKey()
        V getValue()

        import java.util.Map;
        import java.util.Set;
        import java.util.TreeMap;
        import java.util.Iterator;

        public class Emps{
        public static void main(String[] args){
        Map<String,String> empmap = new TreeMap<String,String>();
        empmap.put(“956544″,”Bob Jones”);
        empmap.put(“132485″,”Phil Harris”);
        empmap.put(“102161″,”Kamal Uganda”);
        empmap.put(“226545″,”Bill Russel”);
        empmap.put(“116423″,”Dorris Smith”);
        Set s = empmap.entrySet();
        for(Iterator i = s.iterator();i.hasNext();){
        Map.Entry me = (Map.Entry)i.next();
        System.out.println(me.getKey() + ” : ” + me.getValue());
        }
        }
        }

        44.How can I find the maximum element contained within a Collection ?
        Finding the maximum element within a Collection is easy. The following method can be used which can be found within the Collections class.

        public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)

        This method returns the maximum element of the given Collection according to the natural ordering of it’s elements. This means that all elements must implement the Comparable interface. With the following code below the implementation of the Comparable interface is already taken care of since the class Byte already implements this interface.
        import java.util.Set;
        import java.util.ArrayList;
        import java.util.Collection;
        import java.util.Collections;

        public class Max{
        public static void main(String[] args){
        Collection<Byte> numl = new ArrayList<Byte>();
        numl.add(new Byte(“2″));
        numl.add(new Byte(“6″));
        numl.add(new Byte(“3″));
        numl.add(new Byte(“1″));
        numl.add(new Byte(“5″));
        numl.add(new Byte(“4″));
        System.out.print(“Max element is ” + getMax(numl));
        }
        public static Byte getMax(Collection<Byte> c){
        return Collections.max(c);
        }
        }

        If the element type being store within the Collection is user defined, implementation of the Comparable interface must be provided.

        import java.util.Set;
        import java.util.ArrayList;
        import java.util.Collection;
        import java.util.Collections;

        public class Max{
        public static void main(String[] args){
        Collection<Num> numl = new ArrayList<Num>();
        numl.add(new Num(“2″));
        numl.add(new Num(“6″));
        numl.add(new Num(“3″));
        numl.add(new Num(“1″));
        numl.add(new Num(“5″));
        numl.add(new Num(“4″));
        System.out.print(“Max element is ” + getMax(numl).getNum());
        }
        public static Num getMax(Collection<Num> c){
        return Collections.max(c);
        }
        }
        class Num implements Comparable<Num>{
        private String i;
        public Num(String i){
        this.i = i;
        }
        public int compareTo(Num num){
        int x = i.compareTo(num.i);
        return x;
        }
        public String getNum(){
        return i;
        }
        }

        45.How can I create an immutable List consisting of n Copies of an Object ?
        nCopies(int n, T o) can be used to create an immutable List which contains a specific number of copies of an Object. Care must be taken when trying to add elements to or extract elements from the returned List. Both attempts will throw UnsupportedOperationExceptions.

        public static <T> List<T> nCopies(int n, T o)

        import java.util.List;
        import java.util.Collections;

        public class NCopiesTest{
        public static void main(String[] args){
        List<String> slist = Collections.nCopies(5, “Java Blend”); //immutable list!
        slist.add(“Moca Blend”); // throws UnsupportedOperationException!
        String selement = slist.remove(0); // throws UnsupportedOperationException!
        }
        }

        46.What is the difference between a Stack and a Queue ?
        First things first. Where can Stacks and Queue’s be found? Java provides a Stack class, which can be found within the java.util namespace. Within the same namespace you will find a Queue interface. All concrete Queue implementations can be located within the java.util.concurrent package.

        What is a Stack?

        Java’s Stack class extends the Vector class. A Stack represents a Collection of objects that are in LIFO (Last In First Out Order). The Stack class provides operations that allow testing for zero elements, inspection of it’s top most element, removal of it’s top most element, and the addition of elements.

        boolean empty() Tests if this stack is empty.
        E peek() Looks at the object at the top of this stack without removing it from the stack.
        E pop() Removes the object at the top of this stack and returns that object as the value of this function.
        E push(E item) Pushes an item onto the top of this stack.
        int search(Object o) Returns the 1-based position where an object is on this stack.

        What is a Queue?

        A Queue is also a Collection of Objects similar to a Stack. Queues typically order the elements contained within in FIFO order but this is not always the case. Elements that are inserted into a Queue are inserted at the tail end as opposed to a Stack where the elements are pushed into it at the head. Looking at the Queue interface the operations are similar to what a Stack provides.

        E element() Retrieves, but does not remove, the head of this queue.
        boolean offer(E o) Inserts the specified element into this queue, if possible.
        E peek() Retrieves, but does not remove, the head of this queue, returning null if this queue is empty.
        E poll() Retrieves and removes the head of this queue, or null if this queue is empty.
        E remove() Retrieves and removes the head of this queue.

        So what are the differences between Queues and Stacks?

        Besides how each order their elements there really isn’t much difference. Both provided pretty much the same operations. The big difference is that one is a concrete implementation (Stack) while the other is an interface (Queue) thus implying that additional functionality is provided by the concrete classes that implement the Queue interface such as blocking, and synchronization.

        47.How can I insert an element into a List ?
        In order to insert an element into a List add(int index, E element) must be used since the List interface does not provide an insert method. If the index is out of rage ie. index < 0 || index > size() an exception will be thrown.

        import java.util.*;

        public class Insert{
        public static void main(String[] args){
        List<String> slist = new ArrayList<String>();
        slist.add(new String(“Java”));
        slist.add(new String(“Write”));
        slist.add(new String(“run”));
        slist.add(new String(“anywhere!”));
        slist.add(2,new String(“once”));
        for(String s:slist){
        System.out.println(s);
        }
        }
        }

        48.How do I make a copy of an array ?
        The clone() in Clonable interface allows to make a copy of the array. In the previous case i.e. arraycopy() we must mention the source array,the source offset(starting position),the destination array,the destination offset(Starting position),and the final one is the number of elements to be copied.This method is useful when you copy a part of the array to a new one. But when we need to copy a whole array to another,then we need not mention all the arguments and have a tough time instead we go for clone() method.In case of the clone() we need to mention the source array and destination array. eg: Array a2=a1.clone(); here the elements of the Array a1 is copied to the Array a2.If we add new elements in Array a1 it will not be reflected in a2.For doing so we need to use the Object refrences.

        49.What is the purpose of the CopyOnWriteArrayList and CopyOnWriteArraySet collections ?
        Synchronized operations are costly and if you aren’t modifying a collection much, it is best not to synchronize all collection accesses. The CopyOnWriteXXX collections avoid concurrent modification issues during traversal by traversing through the original collection and the modifications happening in a copy of the original store. Think of CopyOnWriteArrayList as a thread-safe version of ArrayList without the syncrhonized access limitations. CopyOnWriteArraySet acts as like a Set, backed by a CopyOnWriteArrayList.

        50.What implementations of the Deque interface does Java offer ?
        ArrayDeque offers an array backed deque. LinkedList offers a linked list version. LinkedBlockingDeque offers an optionally bounded blocking version.

        51.Why do I keep getting an UnsupportedOperationException thrown when I try some collection operations ?
        Several methods of the collection interfaces are considered optional. If an unsupported operation is called, that is when you’ll see the UnsupportedOperationException thrown. The javadoc for a collection implementation should document which methods are optional.

        53.Is it better to use a for-each loop or an Iterator with a collection ?
        It depends on what you need to do. The remove() method of an Iterator is the safe way to remove elements from an underlying collection. You can’t safely remove elements with a for-each loop. For just “visiting” each element, either way works.

        54.How can I detect if a duplicate is added to a Set ?
        The add() method returns a boolean. If the set did not previously contain the element, true is returned. If the set previoulsy did contain the element, false is returned. Of course, you can also check with the contains() method to see if the element is contained in the Set first.

        55.What is a multimap ?
        A multimap is a map where a single key can map to multiple values.(And a value can be associated with multiple keys.)

        54.How do I create a multimap in Java ?
        Typically a Map maps a key to a single value. To have a multimap, the values of a Map should be a List instead. Thus there can be multiple values in the List associated with a single key.

        56.What is the natural ordering of a Boolean? Does FALSE come first or second ?
        Boolean.FALSE < Boolean.TRUE

        57.What does Class<String> mean ?
        Class<String> is the generics way of writing String.class. It allows you to improve type safety.

        58.What type of data structure would you use to store java objects (Element) with the following requirements ?
        I.
        Created/loaded only once
        Elements are frequently read by multiple threads
        No updates (add/remove) to the data structure are required once loaded
        Order is not important
        Random object access is required by a unique key search.

        Answer: HashMap

        II.
        Created once
        Elements are added / removed in a multi threaded environment
        Elements are frequently read in a multi threaded environment
        Order is not important
        Random object access is required by a unique key search.

        Answer: HashTable is synchronized
        III.
        Created/loaded only once
        Elements are frequently read in a multi threaded environment
        Elements are added / removed in a multi threaded environment
        Elements are frequently read in a multi threaded environment
        Order is important
        Random object access is require based on an index
        Duplicate objects allowed

        Answer: Vector is synchronized

        IV.

        Created once
        Order is important
        Random object access is require based on an index
        Elements are frequently read in a multi threaded environment

        Answer: ArrayList

        Collections Drill – I

        1.How to find the maximum size of heap used in the memory in java ?
        maxMemory
        (): Returns the maximum amount of memory that the Java virtual machine will attempt to use
        totalMemory(): Returns the total amount of memory in the Java virtual machine.
        Also you can use -Xmx parameter to set the max heap size.

        2.What is the difference between marshalling and unmarshalling ?
        marshling is convert from byte code to network understand able format
        unmarshsling is converting from network understand able fromat to byte code convertion.

        3.What is the Collections API ?
        The Collections API is a set of classes and interfaces that support operations on collections of objects.

        4.What is the List interface ?
        The List interface provides support for ordered collections of objects.

        5.What is the Vector class ?
        The Vector class provides the capability to implement a growable array of objects.

        6.What is an Iterator interface ?
        The Iterator interface is used to step through the elements of a Collection .

        7.Which java.util classes and interfaces support event handling?
        The EventObject class and the EventListener interface support event processing.

        8.What is the GregorianCalendar class ?
        The GregorianCalendar provides support for traditional Western calendars

        9.What is the Locale class ?
        The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region .

        10.What is the SimpleTimeZone class ?
        The SimpleTimeZone class provides support for a Gregorian calendar .

        11.What is the Map interface ?
        The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

        12.What is the highest-level event class of the event-delegation model ?
        The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.

        13.What is the Collection interface ?
        The Collection interface provides support for the implementation of a mathematical bag – an unordered collection of objects that may contain duplicates.

        14.What is the Set interface ?
        The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.

        15.What is the typical use of Hashtable ?
        Whenever a program wants to store a key value pair, one can use Hashtable.

        16.I am trying to store an object using a key in a Hashtable. And some other object already exists in that location, then what will happen? The existing object will be overwritten? Or the new object will be stored elsewhere?
        The existing object will be overwritten and thus it will be lost.

        17.What is the difference between the size and capacity of a Vector?
        The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time.

        18.Can a vector contain heterogenous objects ?
        Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.

        19.Can a ArrayList contain heterogenous objects ?
        Yes a ArrayList can contain heterogenous objects. Because a ArrayList stores everything in terms of Object.

        20.What is an enumeration ?
        An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.

        21.Considering the basic properties of Vector and ArrayList, where will you use Vector and where will you use ArrayList ?
        The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.

        22.Can a vector contain heterogenous objects ?
        Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object

        23.How do I use an Iterator to go through a Collection ?
        Collection collection = …;
        Iterator iterator = collection.iterator();
        while (iterator.hasNext()) {
        Object element = iterator.next();
        // Do something with element
        }
        }

        24.How do I use a ListIterator to go through a List backwards ?
        List list = …;
        ListIterator iterator = list.listIterator(list.size());
        while (iterator.hasPrevious()) {
        Object element = iterator.previous();
        // Process element
        }

        25.How do I count the frequency of some word/object ?
        The Map interface can be used to count the number of times a word/object appears. The following program demonstrates counting word frequency from the command line:

        import java.util.*;

        public class MapExample {
        public static void main(String args[]) {
        Map map = new HashMap();
        Integer ONE = new Integer(1);
        for (int i=0, n=args.length; i<n; i++) {
        String key = args[i];
        Integer frequency = (Integer)map.get(key);
        if (frequency == null) {
        frequency = ONE;
        } else {
        int value = frequency.intValue();
        frequency = new Integer(value + 1);
        }
        map.put(key, frequency);
        }
        System.out.println(map);
        Map sortedMap = new TreeMap(map);
        System.out.println(sortedMap);
        }
        }

        26. How do I sort objects into their reverse natural ordering ?
        The Collections.reverseOrder() method returns a Comparator that sorts objects that implement the Comparable interface in reverse order.

        27.How do I use Enumeration to iterate through a collection ?
        Enumeration enum = …;
        while (enum.hasMoreElements()) {
        Object element = iterator.nextElement();
        // process element
        }

        28.How do I make an array larger ?
        You cannot directly make an array larger. You must make a new (larger) array and copy the original elements into it, usually with System.arraycopy(). If you find yourself frequently doing this, the Vector class does this automatically for you, as long as your arrays are not of primitive data types.

        29.How do you store a primitive data type within a Vector or other collections class ?
        You need to wrap the primitive data type into one of the wrapper classes found in the java.lang package, like Integer, Float, or Double, as in:

        Integer in = new Integer(5);

        30.How do I create linked lists if there are no pointers ?
        No pointers does not mean no reference variables. You just can’t deference them as you can in C/C++ or perform pointer arithmetic. You can still use abstract data types that require dynamic data structures. See the LinkedList class for an example of a linked list implementation.

        31.How do I use an array with the Collections Framework ?
        The Arrays.asList() method provides a fixed-length List view of an array, where changes to the List are stored in the original array. The Arrays class also provides additional support methods for sorting and searching an array.

        32.Which is faster, synchronizing a HashMap or using a Hashtable for thread-safe access ?
        Because a synchronized HashMap requires an extra method call, a Hashtable is faster for synchronized access.

        33.Which is the preferred collection class to use for storing database result sets ?
        When retrieving database results, the best collection implementation to use is the LinkedList.
        The benefits include:
        Retains the original retrieval order
        Has quick insertion at the head/tail
        Doesn’t have an internal size limitation like a Vector where when the size is exceeded a new internal structure is created (or you have to find out size beforehand to size properly)
        Permits user-controlled synchronization unlike the pre-Collections Vector which is always synchronized

        Basically:

        ResultSet result = stmt.executeQuery(“…”);
        List list = new LinkedList();
        while(result.next()) {
        list.add(result.getString(“col”));
        }

        If there are multiple columns in the result set, you’ll have to combine them into their own data structure for each row. Arrays work well for that as you know the size, though a custom class might be best so you can convert the contents to the proper type when extracting from databse, instead of later.

        34.Why doesn’t the Iterator interface extend the Enumeration interface ?
        If the Iterator interface extended the Enumeration interface, the Iterator interface would end up with five methods where two methods just called other methods in the interface. The designers of the framework wanted to get rid of the cumbersome Enumeration method names so had the Iterator interface stand on its own with new shorter method names.

        35.How do I print a Collection ?
        The Collection Framework implementation classes override the toString() method to print out all the elements of the collection. If you create your own custom implementation, as long as your class is a subclass of AbstractMap or AbstractCollection you’ll inherit this behavior. (Keep in mind that AbstractList and AbstractSet subclass AbstractCollection.)

        36.How do I synchronize a collection ?
        With the Collections Framework, the new implementations are all unsynchronized by default. If you need synchronized access, you must synchronize things yourself. The Collections class offers a wrapper method for each of the six core collection interfaces that add synchronization to an arbitrary collections implementation. To ensure thread-safety, direct access to the original backing collection must be avoided.
        For example, the following will synchronize an arbitrary List and lose the original reference so you can’t access it directly:

        List list = …;
        list = Collections.synchronizedList(list);

        37.How I do a case-sensitive sort in a language-insensitive manner ?
        If you have an array of primitives or an array of equivalent objects that implement the Comparable interface, all you need to do is call the sort() method of the java.util.Arrays class. If the class doesn’t implement Comparable, you need to provide your own Comparator implementation to the sort() method.

        38.How do I get the length of an array ?
        To avoid getting an ArrayIndexOutOfBoundsException, you can check for the array length from either the length instance variable or using reflection and calling java.lang.reflect.Array.getLength(), passing the array as an argument to the method.
        int length = args.length;
        // or
        int length2 = Array.getLength(args);

        39.How can I speed up array accesses and turn off array bounds checking ?
        You cannot. It is part of the security architecture of the Java runtime to ensure never accessing invalid memory space.

        40.How do I get the list of system properties that tell me things like which version of Java a user is running and their platform-specific line separator ?
        The System.getProperties() method will return the standard property set. However, in untrusted applets, you can only ask for specific properties, as in System.getProperty(“java.version”).

        41.How do I sort an array ?
        The Arrays class in java.util provides a series of sort() methods for sorting arrays. If the array is an array of primitives or an array of a class that implements Comparable then you can just call the method directly:

        Arrays.sort(theArray);

        If, however, it is an array of objects that don’t implement the Comparable interface then you need to provide a custom Comparator to help you sort the elements in the array.

        Arrays.sort(theArray, theComparator);

        42.How can I implement a List (ordered collection) that keeps an index (i.e. a Map) of its contents ?
        You can’t. Each of the Map and List interfaces define a remove(Object o) method. Each method returns a different type (Map returns an Object while List returns a boolean). Because the compiler doesn’t permit overloaded methods that differ by only return type, you cannot create a class that implements both the List and Map interface.

        If you need a Map that maintains insertion order, see the LinkedHashMap added in Java 1.4.

        43.Is there a way to create a homogenous collection in Java? How do I make a collection where all the elements within it are a specific data type ?
        You can wait for Generics to be added to Java or…

        You’d have to build one yourself. Basically, you’re creating a class that is a Proxy (Gang Of Four design pattern) around the actual Collection.

        This works similarly to the way the (hidden) Synchronized versions in Collections work. They contain a reference to the original collection object that does the “real” work, but restrict access to it by synchronizing all the access methods.

        What you’d be doing in this case is restricting access by keeping a reference to the Class object of the class you want to restrict your collection to contain, and throw IllegalArgumentExceptions whenever there’s an attempt to add an object not of that class.

        There’s no way to enforce compile-time type safety in this manner. The API using “Object” references can’t be changed in Collection.

        You can also wrap a collection by a Proxy that provides the alternative API that has type-safe method signatures. This is what’s done by the StringTokenizer API (which implements Enumeration, and wraps Enumeration with String versions of the same methods).

        Otherwise, create your own class with its own signatures, and keep the Collection strictly private. This is best done if you are designing a class for others to use.

        44.How does a Hashtable internally maintain the key-value pairs ?
        The Hashtable class uses an internal (private) class named Entry to hold the key-value pairs. All entries of the Hashtable are stored in an array of Entry objects with the hash value of the key serving as the index. If two or more different keys have the same hash value these entries are stored as a linked list under the same index.

        45.How do I look through each element of a HashMap ?
        To go through all the elements of a HashMap, or any class that implements the Map interface, call the entrySet() or keySet() methods than loop through what is returned. The entrySet() returns a group of Map.Entry elements, whereas the keySet() method just returns a Set of key elements. If you then want what the key refers to, you’d have to look them up.
        Once you have a Set to work with, you would then use an Iterator to go through all its elements. The following demonstrates:

        Map map = some hash map
        Set set = map.keySet();
        Iterator it = set.iterator();
        while (it.hasNext()) {
        System.out.println(it.next());
        }

        46.How do I create a read-only collection ?
        The Collections class has six methods to help out here:
        unmodifiableCollection(Collection c)
        unmodifiableList(List list)
        unmodifiableMap(Map m)
        unmodifiableSet(Set s)
        unmodifiableSortedMap(SortedMap m)
        unmodifiableSortedSet(SortedSet s)

        If you then get an Iterator from one of these unmodifiable collections, when you call remove() it will throw an UnsupportedOperationException

        47.How can I process through the keys of a Hashtable in sorted order ?
        In order to get all the keys for a Hashtable, you use the keys() method to get an Enumeration or the keySet() method to get a Set. If you are using Java 2, and can use the collections framework, what you should do is get the key set of the Hashtable and create a TreeSet from it. You can then get an iterator() from the created TreeSet that will have the keys in order. If you can’t use the collections framework, you’ll have the sort the Enumeration you get back from keys() yourself.

        48.Which collections in Java are synchronized and which aren’t ?
        The original collection classes in Java are all synchronized: Vector and Hashtable, along with their subclasses Stack and Properties. Those classes introduced with the Java 2 Collections Framework are all NOT synchronized by default, the sets, lists, and maps

        49.What are the differences between ArrayList and LinkedList ?
        An ArrayList is a List implementation backed by a Java array, similar to the Vector class. As the number of elements in the collection increases, the internal array grows to fit them. If there are lots of growth periods, performance degrades as the old array needs to be copied into the new array. However, random access is very quick as it uses an array index to access.
        With a LinkedList, the List implementation is backed by a doubly linked list data structure, allowing easy inserts/deletions anywhere in the structure, but really slow random accesses as the access must start at an end to get to the specific position.

        Which you use really depends on the type of operations you need to support.

        50.How do I read input from a stream “one word at a time” ?           What you need to do is use the java.util.StringTokenizer or java.io.StreamTokenizer to parse your input into words. Each has a default set of delimiters like white space that can be changed. The following demonstrates the using of StringTokenizer to count words in a file.

        import java.io.*;
        import java.util.*;

        public class Test {
        static final Integer ONE = new Integer(1);

        public static void main (String args[])
        throws IOException {

        Map map = new TreeMap();
        FileReader fr = new FileReader(args[0]);
        BufferedReader br = new BufferedReader(fr);
        String line;
        while ((line = br.readLine()) != null) {
        processLine(line, map);
        }
        printMap(map);
        }
        static void processLine(String line, Map map) {
        StringTokenizer st = new StringTokenizer(line);
        while (st.hasMoreTokens()) {
        addWord(map, st.nextToken());
        }
        }
        static void addWord(Map map, String word) {
        Object obj = map.get(word);
        if (obj == null) {
        map.put(word, ONE);
        } else {
        int i = ((Integer)obj).intValue() + 1;
        map.put(word, new Integer(i));
        }
        }
        static void printMap(Map map) {
        Set set = map.entrySet();
        Iterator it = set.iterator();
        while (it.hasNext()) {
        Map.Entry entry = (Map.Entry)it.next();
        System.out.println(entry.getKey() +
        “: ” + entry.getValue());
        }
        }
        }

        51.Do the keys() and elements() methods of a Hashtable enumerate things in the same order ?
        There is no requirement that the elements are returned in the same order, only that all of them are returned in the Enumeration. Your best bet for getting the element for a key is to loop through the keys() returned and fetch the element for each. Or, if you can use a HashMap instead of a Hashtable, work with the Map.Entry that is returned by the keySet(). This includes both the key and value together, not requiring a separate lookup.

        52.How do I treat an object I get out of a Vector (collection) as the type I put into it  ?
        When you get an object out of a Vector (or any collection), the object is returned as being of type Object. You need to cast it back into the object type you put into the data structure if you need to call or treat the object as the original type.
        For instance, if you add an array to a vector:

        String args[] = {“1″, “2″, “3″};
        Vector v = new Vector();
        v.addElement(args);

        Then, when you get the object out of the vector, you need to cast it back to the original type:
        String args2[] = (String[])v.firstElement();
        System.out.println(args2.length);

        53.What is the difference between a singly linked list and doubley linked list ?
        A singly linked list is one that has only a pointer/reference to the next element in the list. A doubley linked list has both a previous and next pointer/reference.

        54.What is meant by natural ordering of objects in the context of the collections framework ?
        Java documentation refers to the natural ordering of objects when describing various algorithms and data structures in the collections framework. Object ordering is obviously needed by the sorting algorithms. It is also needed by the specifications of the interfaces such as SortedSet, SortedMap, etc., and the data structures used for container classes such as TreeSet, TreeMap, etc. Unless instructed otherwise via a Comparator object supplied as an argument to the constructor, the default behavior of a class such as TreeSet is to store its objects in an ascending natural order.
        The objects of a class exhibit natural ordering if the class has implemented the java.lang.Comparable interface. Such a class must provide an implementation for the compareTo method — referred to as the class’s natural comparison method — that can then be used by the algorithms and the data structures for comparing data objects. The compareTo method must return a negative integer, a zero, or a positive integer if the object on which it is invoked is less than, equal to, or greater than the argument object.

        It is strongly recommended that a class’s natural ordering as dictated by the implementation of the compareTo method be consistent with equals. This consistency is achieved if and only if e1.compareTo( (Object) e2 ) == 0 has the same boolean value as e1.equals( (Object) e2 ) for every pair of objects e1 and e2 of the class. Lack of this consistency could elicit strange behavior from the data structures that need to compare objects.

        Many of the system supplied classes possess natural ordering. These include String, Integer, Float, Double, Date, File and many others. For the String class, the natural order is lexicographic; it is chronological for the Date class; lexicographic on the pathname for the File class, etc.

        55.What is a fail-fast iterator ?
        An iterator is considered fail-fast if it throws a ConcurrentModificationException under either of the following two conditions:
        In multithreaded processing: if one thread is trying to modify a Collection while another thread is iterating over it.

        In single-threaded or in multithreaded processing: if after the creation of the Iterator, the container is modified at any time by any method other than the Iterator’s own remove or add methods.
        Note in particular what is implied by the second condition: After we create a container’s iterator, during a loop that iterates over the container we must only use the remove (and when applicable add) methods defined for the iterator and that we must NOT use the same methods defined for the container itself. To illustrate this point, suppose we declare and initialize a List in the following manner
        List list = new ArrayList();
        list.add(“Peter”);
        list.add(“Paul”);
        list.add(“Mary”);

        Let’s say we wish to iterate over this list. We’d need to declare a ListIterator as follows:
        ListIterator iter = list.listIterator();

        Having created this iterator, we could now set up a loop like:
        while(iter1.hasNext()){
        String str = iter1.next();
        // do something with str
        }

        Because iter is fail-fast, we are not allowed to invoke List’s add or remove methods inside the loop. Inside the loop, we are only allowed to use ListIterator’s add and remove methods. This makes sense because it is the Iterator object that knows where it is in a List as the List is being scanned. The List object itself would have no idea of that.
        The Iterators supported by all the work-horse container classes, such as ArrayList, LinkedList, TreeSet, and HashSet, are fail-fast. The Iterator type retrofitted to the older container class Vector is also fail-fast. For associative containers, such as HashMap and the older HashTable, the Iterator type for the Collections corresponding to either the keys or the values or the <key, value> pairs are fail-fast with respect to the container itself. That means that even if you are iterating over, say, just the keys of the container, any illegal concurrent modifications to the underlying container would be detected.

        One final note regarding iterators versus enumerations: It is also possible to use an Enumeration object returned by the elements() method for iterating over the older container types such as Vector. However, Enumerations do not provide a fail-fast method. On the other hand, the more modern Iterator returned by a Vector’s iterator() and listIterator() methods are fail-fast. Hence, iterators are recommended over enumerations for iterating over the elements of the older container types.

        56.How do you sort the elements of a vector ?
        Since the Vector class implements the List interface, you can call the Collections.sort() method to sort the elements in place. You can also manually insert elements into a Vector to keep the vector sorted. Of course, if keeping sorted access is such a big deal, you should consider using a different, more appropriate data structure like a TreeSet.
        For 1.1 Java users, you’ll need to sort the elements yourself. There is no built-in support for this. A better option might be to sort the elements as you insert each element.

        57.What is a WeakHashMap? What is its use and when should you use it ?
        A WeakHashMap is a special Map implementation where the keys of the map are stored in a java.lang.ref.WeakReference. By storing the keys in a weak reference, key-value pairs can dynamically be dropped from the map when the only reference to the key is from the weak reference. This makes the WeakHashMap an excellent implementation for a weakly referenced list, where entries that aren’t used elsewhere may be dropped with no side effects. Also, just because a key may be dropped, doesn’t mean it will immediately be dropped. If the system has sufficient resources, the weak key reference that isn’t externally referenced could stay around for a long time.

        58.What is the function of a load factor in a Hashtable ?
        The load factor determines how full a hashtable may get before it expands its capacity. I think that the comments on the Hashtable API docs explain it very well:
        The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hashtable exceeds the product of the load factor and the current capacity, the capacity is increased by calling the rehash method.

        Generally, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the time cost to look up an entry (which is reflected in most Hashtable operations, including get and put).

        59.How do you control growth of vectors when their internal arrays are full ?
        The vector constructor can include either an initial capacity or a capacity and growth increment. When not specified, the initial size of the vector is 10 and growth will double when necessary. Otherwise, initialize size and growth will grow when needed as specified by the arguments to the constructor.
        If the argument to the constructor is a collection, the initial size of the internal structure is 10% larger than the collection. Since there is no second argument to control growth, the capacity will double when necessary.

        60.How to sort the messages in JavaMail ?
        Within the JavaMail classes there is no support for this. However, once you get the array of messages back from a folder, you can call the Arrays.sort() method in the collections framework to sort the messges. Since MimeMessage doesn’t implement Comparable, you’ll need to provide your own Comparator specifying how you want the messages to be sorted.

        61.When did Strings start caching their hash codes ?
        Starting with the 1.3 release of Java, the java.lang.String class will only calculate the hashcode once, when its first needed. Future calls to hashCode() will return the previously calculated value.

        62.How can you retrieve the Hashtable’s load factor ?
        There is no public interface to access the load factor setting.
        Some choices you can do to expose this value…

        Subclass Hashtable and add a read-only accessor method
        Use reflection to access the private field (only possible in trusted environment)
        Serialize the Hashtable and get the value from the stream (when reading back the stream, you’ll have to figure out where the appropriate field is)

        63.Why can’t I add a collection to itself ?
        This will cause a stack overflow exception to be generated on calls to methods like toString() and hashCode(), which recursively call the method on the elements of the collection.

        MQ Series – Drill One

         

        What is MQSeries.

        MQSeries is a software family developed by IBM and its components are used to enable different applications running on different operating systems to exchange data using messages and queues. MQSeries is also known as business integration software or business integration framework because of its ability to tie different types of applications together.

        The MQSeries family of software also includes a standard library of functions known as the Message Queue Interface (MQI). The MQI is identical on different platforms and operating systems allowing straightforward and easy implementation. The MQI takes care of the communication layer and operating environment specifics allowing developers to concentrate on the applications business logic.

        What is MQI

        The Message Queue Interface (MQI) is the common API for MQSeries. It contains calls and messages that are language independent.

        What is QUEUE

        A queue is a data structure that stores messages. Applications send messages to, and receive messages from, a queue. Multiple applications can send information to the same queue.

        Each queue has a name, similar to a TCP port.

        Every queue belongs to a Queue Manager. The Queue Manager organizes the messages and places them in the appropriate queue. Each system can have multiple queue managers.

        Queue managers talk to other queue managers through channels.

        What is Channel.

        A channel serves as a communication path that enables queue managers to transmit messages between each other. There are various types of transport protocols that can be used with channels, the most common being TCP/IP.

        Explain IBM MQ Series.

        MQSeries  is  IBM¢s  award-winning  middleware  for  commercial  messaging and  queuing.    It  runs  on  a  variety  of  platforms.   The  MQSeries  products enable  programs  to  communicate  with  each  other  across  a  network  of unlike  components,  such  as  processors,  subsystems,  operating  systems  and communication  protocols.    MQSeries  programs  use  a  consistent  application program  interface  (API)  across  all  platforms.

        Programs use  MQSeries  API  calls,  that  is  the  message  queue  interface  (MQI),  to communicate  with  a  queue  manager  (MQM),  the  run-time  program  of MQSeries.    For  the  queue  manager  to  do  its  work,  it  refers  to  objects,  such as  queues  and  channels.    The  queue  manager  itself  is  an  object  as  well.

        What Is Messaging and Queuing?

        Messaging means  that  programs  communicate  with  each  other  by  sending data  in  messages  and  not  by  calling  each  other  directly. Queuing means  that  programs  communicate  through  queues.    Programs communicating  through  queues  need  not  be  executed  concurrently. With  asynchronous  messaging,  the  sending  program  proceeds  with  its  own processing  without  waiting  for  a  reply  to  its  message.    In  contrast, synchronous  messaging  waits  for  the  reply  before  it  resumes  processing.

        MQSeries  is  used  in  a  client/server  or  distributed  environment.    Programs belonging  to  an  application  can  run  in  one  workstation  or  in  different machines  on  different  platforms.

        What is a Queue  Manager?

         The  heart  of  MQSeries  is  its  run-time  program,  the queue  manager  (MQM). Its  job  is  to  manage  queues  of  messages.    Application  programs  invoke functions  of  the  queue  manager  by  issuing  API  calls.    For  example,  the MQPUT  API  puts  a  message  on  a  queue  to  be  read  by  another  program using  the  MQGET  API.   This  scenario  is  shown  in  Figure   31  on  page   54. A  program  may  send  messages  to  another  program  that  runs  in  the  same machine  as  the  queue  manager,  or  to  a  program  that  runs  in  a  remote system,  such  as  a  server  or  a  host.    The  remote  system  has  its  own  queue manager  with  its  own  queues. Application  programmers  do  not  need  to  know  where  the  program  runs  they send  messages  to.    They  put  their  message  on  a  queue  and  let  the  queue manager  worry  about  the  destination  machine  and  how  to  get  it  there. For  the  queue  manager  to  do  its  work,  it  refers  to  objects  that  are  defined  by an  administrator,  usually  when  the  queue  manager  is  created  or  when  a new  application  is  added.    The  objects  are  described  in  the  next  section. The  functions  of  a  queue  manager  can  be  defined  as  follows: · It  manages  queues  of  messages  for  application  programs. · It  provides  an  application  programming  interface,  the  Message  Queue Interface  (MQI).

        read more @ http://www.redbooks.ibm.com/redbooks/SG244896.html

        JMS Drill One

        What is JMS?

        Java Message Service: An interface implemented by most J2EE containers to provide point-to-point queueing and topic (publish/subscribe) behavior. JMS is frequently used by EJB’s that need to start another process asynchronously.
        For example, instead of sending an email directly from an Enterprise JavaBean, the bean may choose to put the message onto a JMS queue to be handled by a Message-Driven Bean (another type of EJB) or another system in the enterprise. This technique allows the EJB to return to handling requests immediately instead of waiting for a potentially lengthy process to complete.

        What are the advantages of JMS?

        You can use it in the context of mutithreading but it means JMS is not meant for Multithreading. Its basically meant for object communication.
        It will be useful when you are writing some event based applications like Chat Server which needs a publish kind of event mechanism to send messages between the server to the clients who got connected with the server.
        Moreover JMS gives Loosely-coupled kind of mechanism when compared with RMI which is tightly-coupled. In JMS there is no need for the destination object to be available online while sending a message from the client to the server. But in RMI it is necessary. So we can use JMS in place of RMI where we need to have loosely-coupled mechanism.

        What are major JMS products available in the market?

        IBM’s MQ Series, SonicMQ, iBus etc.
        All the J2EE compliant application servers come built with thier own implementation of JMS. 

        What are the different types of messages available in the JMS API?

        Message, TextMessage, BytesMessage, StreamMessage, ObjectMessage, MapMessage are the different messages available in the JMS API. 

        What is the difference between Point to Point and Publish/Subscribe Messaging Domains

        A point-to-point (PTP) product or application is built around the concept of message queues, senders, and receivers. Each message is addressed to a specific queue, and receiving clients extract messages from the queue(s) established to hold their messages. Queues retain all messages sent to them until the messages are consumed or until the messages expire
        In a publish/subscribe (pub/sub) product or application, clients address messages to a topic. Publishers and subscribers are generally anonymous and may dynamically publish or subscribe to the content hierarchy. The system takes care of distributing the messages arriving from a topic’s multiple publishers to its multiple subscribers. Topics retain messages only as long as it takes to distribute them to current subscribers.

        What is the diffrence between JAVA Mail and JMS Queue

        Java Mail – API siting on top of e-mail protocols like SMTP, POP, IMAP – essentially same stuff e-mail clients like MS outlook use .. hence make sense if at least on one side of conversation we have human.
        JMS Queue – is asynchronous point-to-point communication between systems

        What is the difference between ic and queue?

        A ic is typically used for one to many messaging i.e. it supports publish subscribe model of messaging. While queue is used for one-to-one messaging i.e. it supports Point to Point Messaging.

        What is the role of JMS in enterprise solution development?

        JMS is typically used in the following scenarios
        1. Enterprise Application Integration: – Where a legacy application is integrated with a new application via messaging.
        2. B2B or Business to Business: – Businesses can interact with each other via messaging because JMS allows organizations to cooperate without tightly coupling their business systems.
        3. Geographically dispersed units: – JMS can ensure safe exchange of data amongst the geographically dispersed units of an organization.
        4. One to many applications: – The applications that need to push data in packet to huge number of clients in a one-to-many fashion are good candidates for the use JMS. Typical such applications are Auction Sites, Stock Quote Services etc.

        What is the use of Message object?

        Message is a light weight message having only header and properties and no payload. Thus if the receivers are to be notified about an event, and no data needs to be exchanged then using Message can be very efficient.

        What are the three components of a Message ?

        A JMS message consists of three parts:
        Message header
        For message identification. For example, the header is used to determine if a given message is appropriate for a “subscriber”
        Properties
        For application-specific, provider-specific, and optional header fields
        Body
        Holds the content of the message. Several formats are supported, including TextMessage, which wrap a simple String, that wrap arbitrary Java objects (which must be serializable). Other formats are supported as well.

        What kind of information found in the header of a Message ?

        The header of a message contains message identification and routing information. This includes , but is not limited to :
        JMSDestination
        JMSDeliveryMode
        JMSMessageID
        JMSTimeStamp
        JMSExpiration
        JMSReplyTO
        JMSCorrelationID
        JMSType
        JMSRedelivered

        What is the basic difference between Publish Subscribe model and P2P model?

        Publish Subscribe model is typically used in one-to-many situation. It is unreliable but very fast. P2P model is used in one-to-one situation. It is highly reliable.

         

        What is the use of BytesMessage?

        BytesMessage contains an array of primitive bytes in it’s payload. Thus it can be used for transfer of data between two applications in their native format which may not be compatible with other Message types. It is also useful where JMS is used purely as a transport between two systems and the message payload is opaque to the JMS client. Whenever you store any primitive type, it is converted into it’s byte representation and then stored in the payload. There is no boundary line between the different data types stored. Thus you can even read a long as short. This would result in erroneous data and hence it is advisable that the payload be read in the same order and using the same type in which it was created by the sender.

        What is the use of StreamMessage?

        StreamMessage carries a stream of Java primitive types as it’s payload. It contains some conveient methods for reading the data stored in the payload. However StreamMessage prevents reading a long value as short, something that is allwed in case of BytesMessage. This is so because the StreamMessage also writes the type information alonwgith the value of the primitive type and enforces a set of strict conversion rules which actually prevents reading of one primitive type as another. 

        What is the use of TextMessage?

        TextMessage contains instance of java.lang.String as it’s payload. Thus it is very useful for exchanging textual data. It can also be used for exchanging complex character data such as an XML document.

        What is the use of ObjectMessage?

        ObjectMessage contains a Serializable java object as it’s payload. Thus it allows exchange of Java objects between applications. This in itself mandates that both the applications be Java applications. The consumer of the message must typecast the object received to it’s appropriate type. Thus the consumer should before hand know the actual type of the object sent by the sender. Wrong type casting would result in ClassCastException. Moreover the class definition of the object set in the payload should be available on both the machine, the sender as well as the consumer. If the class definition is not available in the consumer machine, an attempt to type cast would result in ClassNotFoundException. Some of the MOMs might support dynamic loading of the desired class over the network, but the JMS specification does not mandate this behavior and would be a value added service if provided by your vendor. And relying on any such vendor specific functionality would hamper the portability of your application. Most of the time the class need to be put in the classpath of both, the sender and the consumer, manually by the developer.

        What is the use of MapMessage?

        A MapMessage carries name-value pair as it’s payload. Thus it’s payload is similar to the java.util.Properties object of Java. The values can be Java primitives or their wrappers.

        What is the difference between BytesMessage and StreamMessage?

        BytesMessage stores the primitive data types by converting them to their byte representation. Thus the message is one contiguous stream of bytes. While the StreamMessage maintains a boundary between the different data types stored because it also stores the type information along with the value of the primitive being stored. BytesMessage allows data to be read using any type. Thus even if your payload contains a long value, you can invoke a method to read a short and it will return you something. It will not give you a semantically correct data but the call will succeed in reading the first two bytes of data. This is strictly prohibited in the StreamMessage. It maintains the type information of the data being stored and enforces strict conversion rules on the data being read.

        What is point-to-point messaging?

        With point-to-point message passing the sending application/client establishes a named message queue in the JMS broker/server and sends messages to this queue. The receiving client registers with the broker to receive messages posted to this queue. There is a one-to-one relationship between the sending and receiving clients. 

        Can two different JMS services talk to each other? For instance, if A and B are two different JMS providers, can Provider A send messages directly to Provider B? If not, then can a subscriber to Provider A act as a publisher to Provider B?

        The answers are no to the first question and yes to the second. The JMS specification does not require that one JMS provider be able to send messages directly to another provider. However, the specification does require that a JMS client must be able to accept a message created by a different JMS provider, so a message received by a subscriber to Provider A can then be published to Provider B. One caveat is that the publisher to Provider B is not required to handle a JMSReplyTo header that refers to a destination that is specific to Provider A. 

        What is the advantage of persistent message delivery compared to nonpersistent delivery?

        If the JMS server experiences a failure, for example, a power outage, any message that it is holding in primary storage potentially could be lost. With persistent storage, the JMS server logs every message to secondary storage. (The logging occurs on the front end, that is, as part of handling the send operation from the message producing client.) The logged message is removed from secondary storage only after it has been successfully delivered to all consuming clients .   

        Give an example of using the publish/subscribe model.

        JMS can be used to broadcast shutdown messages to clients connected to the Weblogic server on a module wise basis. If an application has six modules, each module behaves like a subscriber to a named ic on the server. 

        Why doesn’t the JMS API provide end-to-end synchronous message delivery and notification of delivery?

        Some messaging systems provide synchronous delivery to destinations as a mechanism for implementing reliable applications. Some systems provide clients with various forms of delivery notification so that the clients can detect dropped or ignored messages. This is not the model defined by the JMS API.
        JMS API messaging provides guaranteed delivery via the once-and-only-once delivery semantics of PERSISTENT messages. In addition, message consumers can ensure reliable processing of messages by using either CLIENT_ACKNOWLEDGE mode or transacted sessions. This achieves reliable delivery with minimum synchronization and is the enterprise messaging model most vendors and developers prefer.
        The JMS API does not define a schema of systems messages (such as delivery notifications). If an application requires acknowledgment of message receipt, it can define an application-level acknowledgment message.

        What are the various message types supported by JMS?

        Stream Messages — Group of Java Primitives
        Map Messages — Name Value Pairs. Name being a string& Value being a java primitive
        Text Messages — String messages (since being widely used a separate messaging Type has been supported)
        Object Messages — Group of serialize able java object
        Bytes Message — Stream of uninterrupted bytes 

        How is a java object message delivered to a non-java Client?

        It is according to the specification that the message sent should be received in the same format. A non-java client cannot receive a message in the form of java object. The provider in between handles the conversion of the data type and the message is transferred to the other end. 

        What is MDB and What is the special feature of that?

        MDB is Message driven bean, which very much resembles the Stateless session bean. The incoming and out going messages can be handled by the Message driven bean. The ability to communicate asynchronously is the special feature about the Message driven bean.

        What are the types of messaging?

        There are two kinds of Messaging.
        Synchronous Messaging: Synchronous messaging involves a client that waits for the server to respond to a message.
        Asynchronous Messaging: Asynchronous messaging involves a client that does not wait for a message from the server. An event is used to trigger a message from a server. 

        What are the core JMS-related objects required for each JMS-enabled application?

        Each JMS-enabled client must establish the following:
        • A connection object provided by the JMS server (the message broker)
        • Within a connection, one or more sessions, which provide a context for message sending and receiving
        • Within a session, either a queue or ic object representing the destination (the message staging area) within the message broker
        • Within a session, the appropriate sender or publisher or receiver or subscriber object (depending on whether the client is a message producer or consumer and uses a point-to-point or publish/subscribe strategy, respectively)
        Within a session, a message object (to send or to receive)

        ANT drill – One

         

        What is ant?

        Ant is a small animal who can build magnificent buildings. Ant builds!
        ANT is a Java based building tool, which is similar to make, and so much better than make.
        ANT, what a smart name for a building tool, even the original author of ANT, James Duncan Davidson, meant “Another Neat Tool”.

        A win-win ant learning method

        There is a shortcut.
        If you download a small jakarta project, such as Log4J, which is built by ant. It is a good and simple example for you to learn ant. Actually, you hit two birds with one stone.
        Ant is easy!
        The hard part is how to make a very complicated diversified system work very simple and elegant. Knowledge about ant is not enough, you need an elegant and simple design, you need great naming convention, you need to optimize the code reusability and flexibility, you need a least maintenance system…
        Then it is not easy now ..

        How do I get started to use ant? Can you give me a “Hello World” ant script?

        Simple.
            * Download the most recent version of ant from Apache; unzip it some where on your machine.
            * Install j2sdk 1.4 or above.
            * Set JAVA_HOME and ANT_HOME to the directory your installed them respectively.
            * Put %JAVA_HOME%/bin;%ANT_HOME%/bin on your Path. Use ${JAVA_HOME}/bin:${ANT_HOME}/bin on UNIX. Yes, you can use forward slash on windows.
            * Write a “Hello world” build.xml
                          <project name=”hello” default=”say.hello” basedir=”.” >
                            <property name=”hello.msg” value=”Hello, World!” />
                            <target name=”say.hello” >
                              <echo>${hello.msg}</echo>
                            </target>
                          </project>
            * Type ant in the directory your build.xml located.
            * You are ready to go!!!!

        How to delete files from a directory if it exists? The following code fails when directory does not exist!
        <delete quiet=”true” dir=”${classes.dir}” includes=”*.class”/>

        Your code has many problems.
           1. You should not use implicit fileset, which is deprecated. You should use nested fileset.
           2. If dir does not exist, the build will fail, period!
           3. If you are not sure, use a upper level dir, which exists for sure. See the following fileset.
          <delete>
            <fileset dir=”${upperdir.which.exists}”>
              <include name=”${classes.dir}/*.class” />
            </fileset>
          </delete>

        How do I set classpath in ant?

        Here is some snippet of code
          <path id=”build.classpath”>
            <fileset dir=”${build.lib}” includes=”**/*.jar”/>
            <fileset dir=”${build.classes}” />
          </path>
          <target….>
            <javac ….>
              <classpath refid=”build.classpath” />
            </java>
          </target>
          <target….>
            <java ….>
              <classpath refid=”build.classpath” />
            </java>
          </target>

        How does ant read properties? How to set my property system?

        Ant sets properties by order, when something is set, the later same properties cannot overwrite the previous ones. This is opposite to your Java setters.
        This give us a good leverage of preset all properties in one place, and overwrite only the needed. Give you an example here. You need password for a task, but don’t want to share it with your team members, or not the developers outside your team.
        Store your password in your ${user.home}/prj.properties
        pswd=yourrealpassword
        In your include directory master prj.properties
        pswd=password
        In your build-common.xml read properties files in this order
           1. The commandline will prevail, if you use it: ant -Dpswd=newpassword
           2. ${user.home}/prj.properties (personal)
           3. yourprojectdir/prj.properties (project team wise)
           4. your_master_include_directory/prj.properties (universal)
        <cvsnttask password=”${pswd} … />
        Problem solved!

        How to modify properties in ant?

        No, you can’t!
        Properties in Ant are immutable. There is a good reason behind this, see this FAQ item for more details.
        Q. How to use ant-contrib tasks?
        A: Simple, just copy ant-contrib.jar to your ant*/lib directory
        And add this line into your ant script, all ant-contrib tasks are now available to you!
            <taskdef resource=”net/sf/antcontrib/antcontrib.properties” />

        How to loop on a list or fileset?

        Use ant-contrib <for> <foreach> tasks
        General to say, use <for> is better than use <foreach> since for each is actually open another ant property space, use more memory too.

        Why do I get en exception when I use location=”D:\\Code\\include” as attribute of includepath?

        See here.
        You need to escape the string to “D:\\\\Code\\\\include” or use “D:/Code/include” instead!
        Believe me or not? Forward slash works on windows in all ant or java code. It also works in windows environment variables. It does not work in cmd (dos) window before XP. It also works in XP dos window now!

        Can I put the contents of a classpath or fileset into a property?

        Yes, you can.
        This is very similar to the call of Java class toString() method and actually it is calling the toString() method inside ant. For example
        <fileset id=”fs1″ dir=”t1″ includes=”**/*.java”/>
        <property name=”f1.contents” refid=”fs1″/>
        <echo>f1.contents=${f1.contents}</echo>

        Where can I find the javadoc for ant API?

        Download apache ant src version. Use ant javadocs command to see generated javadoc for ant in build/docs directory.

         

        How can I use ant to run a Java application?

        Here is a real world example.
          <target name=”run” depends=”some.target,some.other.target”>
            <java classname=”${run.class}” fork=”yes”>
              <classpath>
                <path refid=”classpath” />
              </classpath>
              <jvmarg line=”${debug.jvmargs}” />
              <jvmarg line=”${my.jvmargs}” />
              <jvmarg value=”-Dname=${name}” />
              <jvmarg line=”${run.jvmargs}” />
              <arg line=”${run.args}” />
            </java>
          </target>

        How to use ant to run commandline command? How to get perl script running result?

        Use exec ant task.
        Don’t forget ant is pure Java. That is why ant is so useful, powerful and versatile. If you want ant receive unix command and result, you must think Unix. So does in MS-Windows. Ant just helps you to automate the process.

        How do I debug my ant script?

        Many ways
            * Do an echo on where you have doubt. You will find out what is the problem easily. Just like the old c printf() or Java System.println()
            * Use project.log(“msg”) in your javascript or custom ant task
            * Run Ant with -verbose, or even -debug, to get more information on what it is doing, and where. However, you might be tired with that pretty soon, since it give you too much information.

        How to exclude multi directories in copy or delete task?

        Here is an example.
          <copy todir=”${to.dir}” >
            <fileset dir=”${from.dir}” >
              <exclude name=”dirname1″ />
              <exclude name=”dirname2″ />
              <exclude name=”abc/whatever/dirname3″ />
              <exclude name=”**/dirname4″ />
            </fileset>
          </copy>

        How to use Runtime in ant?

        You don’t need to use Runtime etc. Ant have exec task.
        The class name is org.apache.tools.ant.taskdefs.ExecTask. You can create the task by using the code in your customized ant Task.
        ExecTask compile = (ExecTask)project.createTask(“exec”);

        How to rearrange my directory structure in my jar/war/ear/zip file? Do I need to unarchive them first?

        No, you don’t need to unarchive them first.
            * You don’t need to unzip the files from archive to put into your destination jar/ear/war files.
            * You can use zipfileset in your jar/war/ear task to extract files from old archive to different directory in your new archive.
            * You also can use zipfileset in your jar/war/ear task to send files from local directory to different directory in your new archive.
        See the follow example:
          <jar destfile=”${dest}/my.jar”>
            <zipfileset src=”old_archive.zip” includes=”**/*.properties” prefix=”dir_in_new_archive/prop”/>
            <zipfileset dir=”curr_dir/abc” prefix=”new_dir_in_archive/xyz”/>
          </jar>

        Why did I get such warning in ant?
        compile:
        [javac] Warning: commons-logging.properties modified in the future.
        [javac] Warning: dao\\DAO.java modified in the future.
        [javac] Warning: dao\\DBDao2.java modified in the future.
        [javac] Warning: dao\\HibernateBase.java modified in the future.

        System time problem, possible reasons:
            * You changed the system time
            * I had the same problem before, I checked out files from cvs to windows, and transfer them to a unix machine, somehow, I got huge amount of such warnings because the system timing issue.
            * If you transfer files from Australia/China/India to the United States, you will get the problem too. True enough, I did and met the problem once.

        How can I write my own ant task?

        Easy!
        Writing Your Own Task How-To from ant.
        In your own $ANT_HOME/docs/manual directory, there also is tutorial-writing-tasks-src.zip
        Use them! Use taskdef to define it in your script, define it before using it.

        How to copy files without extention?

        If files are in the directory:
        <include name=”a,b,c”/>
        If files are in the directory or subdirectories:
        <include name=”**/a,**/b,**/c”/>
        If you want all files without extension are in the directory or subdirectories:
        <exclude name=”**/*.*”/>

        How do I use two different versions of jdk in ant script?

        The followings are what I’m doing.
           1. Don’t define java.home by yourself. Ant uses an internal one derived from your environment var JAVA_HOME. It is immutable.
           2. I do the followings:
                  * In my build.properties (read first)
                    jdk13.bin=${tools.home}/jdk1.3.1_13/bin
                    jdk14.bin=${tools.home}/j2sdk1.4.2_08/bin/
                  * In my master properties file (read last), set default
                    javac.location=${jdk13.bin}
                  * In my prj.properties, if I need to use 1.4
                    javac.location=${jdk14.bin}
                  * in my javac task
                    executable=”${javac.location}/javac.exe”

        How to pass -Xlint or -Xlint:unchecked to 1.5 javac task?

        pass it as compilerarg nested <compilerarg> to specify.
          <compilerarg value=”-Xlint”/>
          <!– or –>
          <compilerarg value=”-Xlint:unchecked”/>

        Can you give me a simple ant xslt task example?

        Here is a working one!
            <xslt style=”${xslfile}” in=”${infile}” out=”${outfile}” >
              <classpath>
                <fileset dir=”${xml.home}/bin”
                  includes=”*.jar” />
              </classpath>
            </xslt>

        How to hide password input?

        Override ant Input task.
        Response every user input with a backspace. Not the best, but it works

        How do I add elements to an existing path dynamically?

        Yes, it is possible. However, you need to write a custom ant task, get the path, and add/modify it, and put it in use. What I am doing is that I define a path reference lib.classpath, then add/modify the lib.classpath use my own task.

        How to do conditional statement in ant?

        There are many ways to solve the problem.
            * Since target if/unless all depend on some property is defined or not, you can use condition to define different NEW properties, which in turn depends on your ant property values. This makes your ant script very flexible, but a little hard to read.
            * Ant-contrib has <if> <switch> tasks for you to use.
            * Ant-contrib also has <propertyregex> which can make very complicate decisions.

        Can I change/override ant properties when I use ant-contrib foreach task?

        <foreach> is actually using a different property space, you can pass any property name/value pair to it. Just use <param> nested tag inside foreach

        How to let auto-detect platform and use platform specific properties?

        Tell you a great trick, it works excellent.
        In your major build-include.xml, put in this line
          <property file=”${antutil.includes}/${os.name}-${os.arch}.properties” />
        This will auto-detect your platform, and you write one file for each environment specific variables. For example: HP-UX-PA_RISC2.0.properties SunOS-sparc.properties Windows XP-x86.properties … They work great!!!

        How to make ant user interactive? I tried to use BufferedReader to get user input, it hangs.

        See here.
        Use this class TimedBufferedReader instead of your BufferedReader will work. This is a working one in our installation process. The original author is credited in the code. I’ve made some improvement.
        TimedBufferedReader.java
        package setup;
        import java.io.Reader;
        import java.io.BufferedReader;
        import java.io.IOException;
        /**
         * Provides a BufferedReader with a readLine method that
         * blocks for only a specified number of seconds. If no
         * input is read in that time, a specified default
         * string is returned. Otherwise, the input read is returned.
         * Thanks to Stefan Reich
         * for suggesting this implementation.
         * @author: Anthony J. Young-Garner
         * @author: Roseanne Zhang made improvement.
         */
        public class TimedBufferedReader extends BufferedReader
        {
          private int    timeout    = 60; // 1 minute
          private String defaultStr = “”;
          /**
           * TimedBufferedReader constructor.
           * @param in Reader
           */
          TimedBufferedReader(Reader in)
          {
            super(in);
          }
          /**
           * TimedBufferedReader constructor.
           * @param in Reader
           * @param sz int Size of the input buffer.
           */
          TimedBufferedReader(Reader in, int sz)
          {
            super(in, sz);
          }
          /**
           * Sets number of seconds to block for input.
           * @param seconds int
           */
          public void setTimeout(int timeout)
          {
            this.timeout=timeout;
          }
          /**
           * Sets defaultStr to use if no input is read.
           * @param str String
           */
          public void setDefaultStr(String str)
          {
            defaultStr = str;
          }
          /**
           * We use ms internally
           * @return String
           */
          public String readLine() throws IOException
          {
            int waitms = timeout*1000;
            int ms     = 0;
            while (!this.ready())
            {
              try
              {
                Thread.currentThread().sleep(10);
                ms += 10;
              }
              catch (InterruptedException e)
              {
                break;
              }
              if (ms >= waitms)
              {
                  return defaultStr;
              }
            }
            return super.readLine();
          }
        }

        What is a good directory structure for main code and junit test code?

        Dev
            |_src
            |  |_com
            |     |_mycom
            |        |_mypkg
            |           |_A.java
            |_test
               |_src
                 |_com
                    |_mycom
                       |_mypkg
                          |_ATest.java

        JUnit Drill – One

        What is JUnit?

        JUnit is a simple, open source framework to write and run repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. JUnit features include:
        Assertions for testing expected results
        Test fixtures for sharing common test data
        Test runners for running tests

        How do I install JUnit?

        First, download the latest version of JUnit, referred to below as junit.zip.
        Then install JUnit on your platform of choice:
        Windows
        To install JUnit on Windows, follow these steps:
        Unzip the junit.zip distribution file to a directory referred to as %JUNIT_HOME%.
        Add JUnit to the classpath:
        set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar
        Unix (bash)
        To install JUnit on Unix, follow these steps:
        Unzip the junit.zip distribution file to a directory referred to as $JUNIT_HOME.
        Add JUnit to the classpath:
        export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit.jar
        (Optional) Unzip the $JUNIT_HOME/src.jar file.
        Test the installation by running the sample tests distributed with JUnit. Note that the sample tests are located in the installation directory directly, not the junit.jar file. Therefore, make sure that the JUnit installation directory is on your CLASSPATH. Then simply type:
        java org.junit.runner.JUnitCore org.junit.tests.AllTests
        All the tests should pass with an “OK” message.
        If the tests don’t pass, verify that junit.jar is in the CLASSPATH.

        How do I write and run a simple test?  

        Create a class:
          package junitfaq;
          import org.junit.*;
          import static org.junit.Assert.*;
          import java.util.*;
          public class SimpleTest {
        Write a test method (annotated with @Test) that asserts expected results on the object under test:
        @Test
            public void testEmptyCollection() {
                Collection collection = new ArrayList();
                assertTrue(collection.isEmpty());
            }
        If you are running your JUnit 4 tests with a JUnit 3.x runner, write a suite() method that uses the JUnit4TestAdapter class to create a suite containing all of your test methods:
            public static junit.framework.Test suite() {
                return new junit.framework.JUnit4TestAdapter(SimpleTest.class);
            }
        Although writing a main() method to run the test is much less important with the advent of IDE runners, it’s still possible:
            public static void main(String args[]) {
              org.junit.runner.JUnitCore.main(“junitfaq.SimpleTest”);
            }
          }
              Run the test:
        To run the test from the console, type:
        java org.junit.runner.JUnitCore junitfaq.SimpleTest
        To run the test with the test runner used in main(), type:
        java junitfaq.SimpleTest
        The passing test results in the following textual output:
                .
        Time: 0
        OK (1 tests)

        How do I use a test fixture?

        A test fixture is useful if you have two or more tests for a common set of objects. Using a test fixture avoids duplicating the code necessary to initialize (and cleanup) the common objects.
        Tests can use the objects (variables) in a test fixture, with each test invoking different methods on objects in the fixture and asserting different expected results. Each test runs in its own test fixture to isolate tests from the changes made by other tests. That is, tests don’t share the state of objects in the test fixture. Because the tests are isolated, they can be run in any order.
        To create a test fixture, declare instance variables for the common objects. Initialize these objects in a public void method annotated with @Before. The JUnit framework automatically invokes any @Before methods before each test is run.
        The following example shows a test fixture with a common Collection object.
            package junitfaq;
            import org.junit.*;
            import static org.junit.Assert.*;
            import java.util.*;
            public class SimpleTest {
                private Collection<Object> collection;
                @Before
                public void setUp() {
                    collection = new ArrayList<Object>();
                }
                @Test
                public void testEmptyCollection() {
                    assertTrue(collection.isEmpty());
                }
                @Test
                public void testOneItemCollection() {
                    collection.add(“itemA”);
                    assertEquals(1, collection.size());
                }
            }
              Given this test, the methods might execute in the following order:
        setUp()
        testEmptyCollection()
        setUp()
        testOneItemCollection()
        The ordering of test-method invocations is not guaranteed, so testOneItemCollection() might be executed before testEmptyCollection(). But it doesn’t matter, because each method gets its own instance of the collection.
        Although JUnit provides a new instance of the fixture objects for each test method, if you allocate any external resources in a @Before method, you should release them after the test runs by annotating a method with @After. The JUnit framework automatically invokes any @After methods after each test is run. For example:
            package junitfaq;
            import org.junit.*;
            import static org.junit.Assert.*;
            import java.io.*;
            public class OutputTest {
                private File output;
                @Before
                public void createOutputFile() {
                    output = new File(…);
                }
                @After
                public void deleteOutputFile() {
                    output.delete();
                }
                @Test
                public void testSomethingWithFile() {
                    …
                }
            }
        With this test, the methods will execute in the following order:
        createOutputFile()
        testSomethingWithFile()
        deleteOutputFile()

        How do I test a method that doesn’t return anything?

        Often if a method doesn’t return a value, it will have some side effect. Actually, if it doesn’t return a value AND doesn’t have a side effect, it isn’t doing anything.
        There may be a way to verify that the side effect actually occurred as expected. For example, consider the add() method in the Collection classes. There are ways of verifying that the side effect happened (i.e. the object was added). You can check the size and assert that it is what is expected:
            @Test
            public void testCollectionAdd() {
                Collection collection = new ArrayList();
                assertEquals(0, collection.size());
                collection.add(“itemA”);
                assertEquals(1, collection.size());
                collection.add(“itemB”);
                assertEquals(2, collection.size());
            }
              Another approach is to make use of MockObjects.
        A related issue is to design for testing. For example, if you have a method that is meant to output to a file, don’t pass in a filename, or even a FileWriter. Instead, pass in a Writer. That way you can pass in a StringWriter to capture the output for testing purposes. Then you can add a method (e.g. writeToFileNamed(String filename)) to encapsulate the FileWriter creation.
        Under what conditions should I test get() and set() methods?
        Unit tests are intended to alleviate fear that something might break. If you think a get() or set() method could reasonably break, or has in fact contributed to a defect, then by all means write a test.
        In short, test until you’re confident. What you choose to test is subjective, based on your experiences and confidence level.

        Under what conditions should I test get() and set() methods?

        Unit tests are intended to alleviate fear that something might break. If you think a get() or set() method could reasonably break, or has in fact contributed to a defect, then by all means write a test.

        Under what conditions should I not test get() and set() methods?

        Most of the time, get/set methods just can’t break, and if they can’t break, then why test them? While it is usually better to test more, there is a definite curve of diminishing returns on test effort versus “code coverage”. Remember the maxim: “Test until fear turns to boredom.”
        Assume that the getX() method only does “return x;” and that the setX() method only does “this.x = x;”. If you write this test:
        @Test
        public void testGetSetX() {
            setX(23);
            assertEquals(23, getX());
        }
              then you are testing the equivalent of the following:
        @Test
        public void testGetSetX() {
            x = 23;
            assertEquals(23, x);
        }
        or, if you prefer,
        @Test
        public void testGetSetX() {
            assertEquals(23, 23);
        }
        At this point, you are testing the Java compiler, or possibly the interpreter, and not your component or application. There is generally no need for you to do Java’s testing for them.
        If you are concerned about whether a property has already been set at the point you wish to call getX(), then you want to test the constructor, and not the getX() method. This kind of test is especially useful if you have multiple constructors:
        @Test
        public void testCreate() {
            assertEquals(23, new MyClass(23).getX());
        }

        How do I write a test that passes when an expected exception is thrown?

        Add the optional expected attribute to the @Test annotation. The following is an example test that passes when the expected IndexOutOfBoundsException is raised:
            @Test(expected=IndexOutOfBoundsException.class)
            public void testIndexOutOfBoundsException() {
                ArrayList emptyList = new ArrayList();
            Object o = emptyList.get(0);
            }

        How do I write a test that fails when an unexpected exception is thrown?

        Declare the exception in the throws clause of the test method and don’t catch the exception within the test method. Uncaught exceptions will cause the test to fail with an error.
        The following is an example test that fails when the IndexOutOfBoundsException is raised:
            @Test
            public void testIndexOutOfBoundsExceptionNotRaised()
                throws IndexOutOfBoundsException {
                ArrayList emptyList = new ArrayList();
                Object o = emptyList.get(0);
            }

        How do I test protected methods?

        Place your tests in the same package as the classes under test.

        Why does JUnit only report the first failure in a single test?

        Reporting multiple failures in a single test is generally a sign that the test does too much, compared to what a unit test ought to do. Usually this means either that the test is really a functional/acceptance/customer test or, if it is a unit test, then it is too big a unit test.
        JUnit is designed to work best with a number of small tests. It executes each test within a separate instance of the test class. It reports failure on each test. Shared setup code is most natural when sharing between tests. This is a design decision that permeates JUnit, and when you decide to report multiple failures per test, you begin to fight against JUnit. This is not recommended.
        Long tests are a design smell and indicate the likelihood of a design problem. Kent Beck is fond of saying in this case that “there is an opportunity to learn something about your design.” We would like to see a pattern language develop around these problems, but it has not yet been written down.
        Finally, note that a single test with multiple assertions is isomorphic to a test case with multiple tests:
        One test method, three assertions:
        public class MyTestCase {
            @Test
            public void testSomething() {
                // Set up for the test, manipulating local variables
                assertTrue(condition1);
                assertTrue(condition2);
                assertTrue(condition3);
            }
        }
              Three test methods, one assertion each:
        public class MyTestCase {
            // Local variables become instance variables
            @Before
            public void setUp() {
                // Set up for the test, manipulating instance variables
            }
            @Test
            public void testCondition1() {
                assertTrue(condition1);
            }
            @Test
            public void testCondition2() {
                assertTrue(condition2);
            }
            @Test
            public void testCondition3() {
                assertTrue(condition3);
            }
        }
              The resulting tests use JUnit’s natural execution and reporting mechanism and, failure in one test does not affect the execution of the other tests. You generally want exactly one test to fail for any given bug, if you can manage it.     

        How do I test things that must be run in a J2EE container (e.g. servlets, EJBs)?

        Refactoring J2EE components to delegate functionality to other objects that don’t have to be run in a J2EE container will improve the design and testability of the software.
        Cactus is an open source JUnit extension that can be used to test J2EE components in their natural environment.

        Do I need to write a test class for every class I need to test?

        No. It is a convention to start with one test class per class under test, but it is not necessary.
        Test classes only provide a way to organize tests, nothing more. Generally you will start with one test class per class under test, but then you may find that a small group of tests belong together with their own common test fixture.[1] In this case, you may move those tests to a new test class. This is a simple object-oriented refactoring: separating responsibilities of an object that does too much.
        Another point to consider is that the TestSuite is the smallest execution unit in JUnit: you cannot execute anything smaller than a TestSuite at one time without changing source code. In this case, you probably do not want to put tests in the same test class unless they somehow “belong together”. If you have two groups of tests that you think you’d like to execute separately from one another, it is wise to place them in separate test classes.
        [1] A test fixture is a common set of test data and collaborating objects shared by many tests. Generally they are implemented as instance variables in the test class.

        Is there a basic template I can use to create a test?

        The following templates are a good starting point. Copy/paste and edit these templates to suit your coding style.
        SampleTest is a basic test template:
        import org.junit.*;
        import static org.junit.Assert.*;
        public class SampleTest {
            private java.util.List emptyList;
            /**
             * Sets up the test fixture.
             * (Called before every test case method.)
             */
            @Before
            public void setUp() {
                emptyList = new java.util.ArrayList();
            }
            /**
             * Tears down the test fixture.
             * (Called after every test case method.)
             */
            @After
            public void tearDown() {
                emptyList = null;
            }
            @Test
            public void testSomeBehavior() {
                assertEquals(“Empty list should have 0 elements”, 0, emptyList.size());
            }
            @Test(expected=IndexOutOfBoundsException.class)
            public void testForException() {
                Object o = emptyList.get(0);
            }
        }

        When should tests be written?

        Tests should be written before the code. Test-first programming is practiced by only writing new code when an automated test is failing.
        Good tests tell you how to best design the system for its intended use. They effectively communicate in an executable format how to use the software. They also prevent tendencies to over-build the system based on speculation. When all the tests pass, you know you’re done!
        Whenever a customer test fails or a bug is reported, first write the necessary unit test(s) to expose the bug(s), then fix them. This makes it almost impossible for that particular bug to resurface later.

        Why not just use System.out.println()?

        Inserting debug statements into code is a low-tech method for debugging it. It usually requires that output be scanned manually every time the program is run to ensure that the code is doing what’s expected.
        It generally takes less time in the long run to codify expectations in the form of an automated JUnit test that retains its value over time. If it’s difficult to write a test to assert expectations, the tests may be telling you that shorter and more cohesive methods would improve your design.

        The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP
        consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls.

        Can servlet have a constructor ?

        Servlet can have a constructor. But you never call the constructor for the servlet / instantiate them , because the container handles it.
        So you are better of doing initialization / one-time setup code in the init method of the servlet. Also, the container passes the ServletConfig object to the servlet only when it calls the init method. So ServletConfig will not be accessible in the constructor.However, you might still need the init parameters, so initialization is done in init instead of a constructor.

        How SOAP server process the requests

        1. The SOAP server receives the request from the client as an HTTP request.

        2. The request is passed to the HTTP request handler that redirects the request to the appropriate SOAP servlet. This SOAP servlet is responsible for decoding the HTTP request.

        3. The SOAP servlet directs the request to the HTTP/SOAP decoder. The decoder extracts the original service call from the HTTP request.

        4. The request is processed by the SOAP server, and the result is passed to the HTTP/SOAP encoder.

        5. The HTTP/SOAP encoder wraps the result in an HTTP response and passes it back to the SOAP servlet.

        6. The SOAP servlet, in turn, passes the response to the client.

        Explain SOAP messaging model

        1. The client application discovers a server application by using its discovery document and makes a service call to the server application by invoking its appropriate method.

        2. The SOAP serializer converts the invocation by the client application to a SOAP request.

        3. The SOAP serializer sends the SOAP request to an HTTP encoder, which wraps the SOAP request in an HTTP request, because the request needs to be sent from the client to the SOAP server as an HTTP request.

        4. The response from the server is received in the HTTP format by the HTTP decoder module.

        5. The HTTP decoder module decodes the HTTP response and extracts the SOAP message from the response. The SOAP message is sent to the SOAP deserializer.

        6. The SOAP deserializer decodes the SOAP message and passes the result to the client application.

        Explain SOAP messaging model

        1. The client application discovers a server application by using its discovery document and makes a service call to the server application by invoking its appropriate method.

        2. The SOAP serializer converts the invocation by the client application to a SOAP request.

        3. The SOAP serializer sends the SOAP request to an HTTP encoder, which wraps the SOAP request in an HTTP request, because the request needs to be sent from the client to the SOAP server as an HTTP request.

        4. The response from the server is received in the HTTP format by the HTTP decoder module.

        5. The HTTP decoder module decodes the HTTP response and extracts the SOAP message from the response. The SOAP message is sent to the SOAP deserializer.

        6. The SOAP deserializer decodes the SOAP message and passes the result to the client application.

        What are SOAP attribtutes

        A client can use SOAP attributes to specify how SOAP messages should be processed.

        SOAP attributes are generally used to specify the serialization rules to indicate the recipient of the Header element of the SOAP message.

        Attributes also indicate whether or not the recipient should process certain header entries.

        example1:

        The mustUnderstand attribute states whether or not the SOAP processor should process the header information. The usage of this attribute is given below:

        soap:mustUnderstand = "true"

        After the mustUnderstand attribute is set to true, the SOAP toolkit needs to compulsorily process the statement. If the toolkit is unable to process the statement, it should return a fault code signifying that there was an error in interpreting the statement.

        example 2:

        The actor attribute of a SOAP message specifies URI to indicate who should receive the Header element of the SOAP message. If no URI is specified, it is assumed that the ultimate SOAP receiver should receive the SOAP message.

        The actor attribute has the following syntax:

        soap:actor="URI"

        What is SOAP fault

        SOAP defines a Fault element that is used to indicate errors that might be raised when the SOAP message is processed. The Fault element is defined below:

        <soap:Fault>
           <faultcode>SOAP-ENV:Server.BadTargetObjectURI</faultcode>
           <faultstring>Unable to resolve target object:
           HelloWorld</faultstring>
        </soap:Fault>

        After you include the Fault element described above, every time the target URI is irresolvable, the application will return a fault packet.

        Why SOAP header is optional

        Tthe Header element is optional in a SOAP message. If the Header element is present in a SOAP message, it should be the first child element of the Envelope element.

        To understand why a SOAP header element is optional, consider a scenario in which you want to invoke a Web method of a Web service by using the SOAP protocol. The Web method might expect three parameters. However, to ensure that the call to the Web method is secure, you might have to encrypt the request that is sent to the Web service.

        The Web method is not concerned with the encrypted information. Instead, the Web method only expects three parameters to process business logic. To have the call to the Web method decrypted before the method is executed, you can add the necessary encoded information in the Header element.

        However, if the request to the Web method is sent in an unencrypted form, you might not need the Header element.

        Explain different Web Services communication Models

        RPC-Based Communication Model

        The RPC-based communication model defines a request/response-based synchronous communication. When the client sends a request, the client waits until a response is sent back from the server before continuing any operation. Typical to implementing CORBA or RMI communication, the RPC-based Web services are tightly coupled and are implemented with remote objects to the client application.

         

        Messaging-Based Communication Model

        The messaging-based communication model defines a loosely coupled and document-driven communication. The service requestor invoking a messaging-based service provider does not wait for a response.

        Define ebXML

        ebXML provides a standard framework for building an electronic marketplace by enabling the standardization of business processes, business partner profiles, and partner agreements. In general, ebXML complements other Web services standards like SOAP, WSDL, and UDDI.

        The following are major features of ebXML:

        • ebXML Messaging Service (MS) is a value-add over SOAP that provides reliability and security mechanisms.

        • ebXML BPSS enables business processes to be described.

        • ebXML CPP/CPA is a value-add over WSDL that enables business partner profiles and partner agreements to be described.

        • ebXML reg/rep provides a registry and repository, while UDDI is just a registry.

        • ebXML Core components provide a catalogue of business process components for the business community.

        Define UDDI

        Universal Description, Discovery, and Integration, or UDDI, defines a mechanism to register and categorize Web services in a general-purpose registry that users communicate to in order to discover and locate registered services. While querying a UDDI registry for a service, the WSDL description describing the service interface will be returned. Using the WSDL description, the developer can construct a SOAP client interface that can communicate with the service provider.

        UDDI can be implemented as a public registry to support the requirements of a global community or as a private registry to support an enterprise or a private community.

        Define SOAP

        SOAP is an XML-based protocol that is used to access services, objects, and servers in a platform- and vendor- independent manner.it is an XML-based protocol.SOAP generally uses HTTP, a firewall-friendly protocol, as its transport protocol.

        SOAP includes three components: SOAP messages, SOAP attributes, and SOAP encoding.

        SOAP Messages

        SOAP is an XML-based protocol, SOAP messages are encoded in the XML format. A SOAP message contains the following XML elements:

        Envelope: It is a mandatory element of SOAP message and it identifies the XML document as SOAP message. It contains other elements, declarations and attributes required for processing SOAP message.

        Header: The SOAP header, which is an optional element, defines the header information. it should be the first child element of the Envelope element. It is used to provide encription information.

        Body: The SOAP body, which is a mandatory element, contains all the information that the message recipient needs. It typically contains method calls and response information for the SOAP message.

        Example:

        <soap:Envelope>
            <soap:Header>
                  ...Header informations ...
            </soap:Header>
            <soap:Body>
               <GetStockValue>
                    <Item>Cake</Item>
               </GetStockValue>
            </soap:Body>
        </soap:Envelope>

        Explain benefits of web services

        • Provides a simple mechanism for applications to become services that are accessible by anyone, anywhere, and from any device.

        • Defines service-based application connectivity facilitating EAI, and intra-enterprise and inter-enterprise communication.

        • Defines a solution for businesses, which require flexibility and agility in application-to-application communication over the Internet.

        • Enables dynamic location and invocation of services through service brokers (registries).

        • Enables collaboration with existing applications that are modeled as services to provide aggregated Web services.

        What are disadvantages/challenges in web services

        Distributed transactions. If the environment requires distributed transactions with heterogeneous resources, it should be studied and tested with standard solutions based on BTP, WS-Transactions, and WS-Coordination.

        Quality of Service (QoS). In case of a mission-critical solution, the service providers must examine the reliability and performance of the service in peak load and uncertain conditions for high availability. The exposed infrastructure must provide load balancing, and fail-over and fault tolerance, to resolve these scenarios.

        Security. Web services are exposed to the public using http-based protocols. As Web services is publicly available, it must be implemented using authentication and authorization mechanisms and using SSL-enabling encryption of the messages for securing the usage. Adopting open security standards like SAML, XML Encryption, XML Signature, or XACML may be a solution.

        What is WSDL

        • The Web Services Definition Language (WSDL) standard is an XML format for describing the network services and its access information.
        • WSDL is used as the metadata language for defining Web services and describes how service providers and requesters communicate with one another.
        • WSDL describes the Web services functionalities offered by the service provider, where the service is located, and how to access the service.
        • Usually the service provider creates Web services by generating WSDL from its exposed business applications. A public/private registry is utilized for storing and publishing the WSDL-based information.

        Explain Basic Architecture of Web Services

        Service provider. The service provider is responsible for developing and deploying the Web services. The provider also defines the services and publishes them with the service broker.

        Service broker. The service broker (also commonly referred to as a service registry) is responsible for service registration and discovery of the Web services. The broker lists the various service types, descriptions, and locations of the services that help the service requesters find and subscribe to the required services.

        Service requestor. The service requestor is responsible for the service invocation. The requestor locates the Web service using the service broker, invokes the required services, and executes it from the service provider.

        Why to use webservices

        1. Web services can be invoked through XML-based RPC mechanisms across firewalls.
        2. Web services provide a cross-platform, cross-language solution based on XML messaging.
        3. Web services facilitate ease of application integration using a lightweight infrastructure without affecting scalability.
        4. Web services enable interoperability among heterogeneous applications.

        What are Web Services

        • Web services are based on the concept of service-oriented architecture (SOA). SOA is the latest evolution of distributed computing, which enables software components, including application functions, objects, and processes from different systems, to be exposed as services.
        • Web services are loosely coupled software components delivered over Internet standard technologies.”
        • Web services are self-describing and modular business applications that expose the business logic as services over the Internet through programmable interfaces and using Internet protocols for the purpose of providing ways to find, subscribe, and invoke those services.
        • Web services can be developed as loosely coupled application components using any programming language, any protocol, or any platform. This facilitates delivering business applications as a service accessible to anyone, anytime, at any location, and using any platform.
        • Web services are typically implemented based on open standards and technologies specifically leveraging XML. The XML-based standards and technologies, such as Simple Object Access Protocol (SOAP); Universal Description, Discovery, and Integration (UDDI); Web Services Definition Language (WSDL); and Electronic Business XML (ebXML), are commonly used as building blocks for Web services.

        Design Patterns : Drill

        What is a design pattern.
        ————————————–
        “Design patterns are recurring solutions to design problems you see over
        Alpert, et. al., 1998).
        “Design patterns constitute a set of rules describing how to accomplish
        certain tasks in the realm of software development.” (Pree, 1994)

        How many catogeries are there in Java patterns.
        ————————————————–
        Creational patterns are ones that create objects for you, rather than
        having you instantiate objects directly. This gives your program more
        flexibility in deciding which objects need to be created for a given case.
        Structural patterns help you compose groups of objects into larger
        structures, such as complex user interfaces or accounting data.
        Behavioral patterns help you define the communication between objects
        in your system and how the flow is controlled in a complex program.

        Design Patterns is a catalog of 23 generally useful patterns for writing objectoriented software.

        Give me an example of Creational Patterns.
        ——————————————————
        All of the creational patterns deal with the best way to create instances of objects. This is important because your program should not depend on how objects are created and arranged. In Java, of course, the simplest way to create an instance of an object is by using the new operator.

        Sharat = new Sharat(); //instance of Fred class

        However, this really amounts to hard coding how you create the object within your program. In many cases, the exact nature of the object that is created could vary with the needs of the program from time to time and abstracting the creation process into a special “creator” class can make your program more flexible and general.

        The Factory Pattern is used to choose and return an instance of a class from a number of similar classes based on data you provide to the factory.
        The Abstract Factory Pattern is used to return one of several groups of classes. In some cases it actually returns a Factory for that group of classes.
        The Builder Pattern assembles a number of objects to make a new object, based on the data with which it is presented. Frequently, the choice of which way the objects are assembled is achieved using a Factory.
        The Prototype Pattern copies or clones an existing class rather than creating a new instance when creating new instances is more expensive.
        The Singleton Pattern is a pattern that insures there is one and only one instance of an object, and that it is possible to obtain global access to that one instance.

        What is Singleton pattern. Where did you use it.
        ——————————————————
        Definition: Singleton pattern is used whenever we require a class to have only one instance throughout the application. Sometimes it’s appropriate to have exactly one instance of a class: If we need some data to be stored , used and manipulated the same instance by the whole application, we will use singleton pattern. 

        • Ensure that only one instance of a class is created
        • Provide a global point of access to the object
        • Allow multiple instances in the future without affecting a singleton class’s clients

        Examples:

        • window managers, print spoolers, and filesystems are prototypical examples.
        • Search window in Microsoft word, even if multiple documents are open, only one search window will be opened.  
        • One important usage of singleton pattern is when you need to instantiate a subclass and check which class to be instantiated during run time. For example there are two subclasses one for production and one for development and we need to instantiate one during run time depending on the environment.

        Syntax:

        public class ClassicSingleton {
        private static ClassicSingleton instance = null;
        protected ClassicSingleton() {
        // Exists only to defeat instantiation.
        }
        public static ClassicSingleton getInstance() {
        if(instance == null) {
        instance = new ClassicSingleton();
        }
        return instance;
        }
        The ClassicSingleton class maintains a static reference to the lone singleton instance and returns that reference from the static getInstance() method.

        public class SingletonInstantiator {
          public SingletonInstantiator() {
           ClassicSingleton instance = ClassicSingleton.getInstance();
        ClassicSingleton anotherInstance =
        new ClassicSingleton();
               …
          }
        }
        Explanation: In the first line we have created an instance of this class as null. We have declared a private constructor for the class to make sure that no object of class can be created outside the class.

        getInstance() method is the entry point for the class which will return the only instance present for the class. This method is marked as static as it will be called directly from other classes. In this method we check if the instance of singletonExample is already present, if yes, return that instance else create the instance and return it. This makes sure that only one instance of the class is present at any point.

        In the user class, that is calling our singleton class, we just need to call our singletonExample.getinstance() method which will return us the instance of singletonExample.

        Types:

        • we create an instance of singleton class only when it is called for the first time is called lazy instantiation.
        • Another variation can be creating the instance before it is called, this kind of instantiation is called eager instantiation.

        Problems:

        • A side effect of using singleton class: as the constructor of the singleton class is private, you cannot create a subclass of a singleton class, but in most of the cases that is desirable.
        • Additionally you can declare the class as final to explicitly show that the class can’t be subclassed. But in case if it is required to create a subclass of singleton class one can define the constructor of singleton class as protective instead of private.
        • Another point to note is that the singleton classes are not thread-safe.

        Making your singleton class thread-safe is easy, you just have to make your getinstance method synchronized.

        Public synchronized static singletonExample getInstance()
        {
        //if instance is null create else return old instance
        }

        What is Factory pattern. Explain it.
        ——————————————————

        • if we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern.
        • provides a simple decision making class which returns one of several possible subclasses of an abstract base class depending on data it is provided.
        • Usually all of the classes it returns have a common parent class and common methods,but each of them performs a task differently and is optimized for differentkinds of data.

        You should consider using a Factory pattern when
        · A class can’t anticipate which kind of class of objects it must create.
        · A class uses its subclasses to specify which objects it creates.
        · You want to localize the knowledge of which class gets created.

        Needs to isolate concrete classes from their super classes.

      • A system needs independent of how its products are created, composed, and represented.
      • Java Design Pattern

        1.What is a design pattern.
        2.How many catogeries are there in Java patterns.
        3. How many patterns did you use in your project.
        4.Give me an example of Creational Patterns.
        5.What is Singleton pattern. Where did you use it.
        6.How do you use Factory pattern.
        7.Can explaing examples of Structural Patterns.
        8.What is difference between adapter pattern and decorator pattern.
        9.What is Facade Pattern. Give an example.
        10.Did you use proxy pattern.
        11.Give me some examples of Behavioral Patterns.
        12.What is Observer Pattern.
        13.Do you know the difference between Command pattern and interpreter pattern.
        14.What is Visitor Pattern.

        Java Drill – 2

        1.Can a private method of a superclass be declared within a subclass?
        2.Why Java does not support multiple inheritence ?
        3.What is the difference between final, finally and finalize?
        4.Where and how can you use a private constructor.
        5.In System.out.println(),what is System,out and println,pls explain?
        6.What is meant by “Abstract Interface”?
        7.Can you make an instance of an abstract class? For example – java.util.Calender is an abstract class with a method getInstance() which returns an instance of the Calender class.
        8.What is the output of x<y? a:b = p*q when x=1,y=2,p=3,q=4?
        9.Why Java does not support pointers?
        10.Parsers? DOM vs SAX parser
        11.What is the main difference between Java platform and other platforms?
        12.What is the Java Virtual Machine?
        13.What is the Java API?
        14.What is the package?
        15.What is native code?
        16.Is Java code slower than native code?
        17.What is the serialization?
        18.How to make a class or a bean serializable?
        19.How many methods in the Serializable interface?
        20.How many methods in the Externalizable interface?
        21.What is the difference between Serializalble and Externalizable interface?
        22.What is a transient variable?
        23.What is synchronization and why is it important?
        24.What are synchronized methods and synchronized statements?
        25.What are three ways in which a thread can enter the waiting state?
        26.Can a lock be acquired on a class?
        27.What is thread?
        28.What is multithreading?
        29.How does multithreading take place on a computer with a single CPU?
        30.What is the purpose of the wait(), notify(), and notifyAll() methods?
        31.What are the high-level thread states?
        32.What is the Collections API?
        33.How does Java handle integer overflows and underflows?
        34.What is the Vector class?
        35.If a method is declared as protected, where may the method be accessed?
        36.What is an Iterator interface?
        37.What is the difference between yielding and sleeping?
        38. Is sizeof a keyword?
        39.What are wrapped classes?
        40.What is the difference between preemptive scheduling and time slicing?
        41.How can you write a loop indefinitely?
        42.Can an anonymous class be declared as implementing an interface and extending a class?
        43.Which class is the superclass for every class.
        44. What is the difference between the Boolean & operator and the && operator?
        45.What is the GregorianCalendar class?
        46.What is the SimpleTimeZone class?
        47.What is the Properties class?
        48.What is the purpose of the Runtime class?
        49.What is the purpose of the System class?
        50.What is the purpose of the finally clause of a try-catch-finally statement?
        51.What must a class do to implement an interface?
        52.What is a static method?
        53.What is the difference between a static and a non-static inner class?
        54.What is an object’s lock and which object’s have locks?
        55.When can an object reference be cast to an interface reference?
        56.What’s the difference between J2SDK 1.5 and J2SDK 5.0?
        57.Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
        58.Can an inner class declared inside of a method access local variables of this method?
        59.What can go wrong if you replace && with & in the following code:
        String a=null; if (a!=null && a.length()>10) {…}
        60.What’s the main difference between a Vector and an ArrayList
        61.When should the method invokeLater()be used?
        62.How can a subclass call a method or a constructor defined in a superclass?
        63.What’s the difference between a queue and a stack?
        64.You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?
        65.What comes to mind when someone mentions a shallow copy in Java?
        66.What comes to mind when you hear about a young generation in Java?
        67.You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
        ArrayList or LinkedList?
        68.How would you make a copy of an entire Java object with its state?
        69.There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
        70.How can you minimize the need of garbage collection and make the memory use more effective?
        71.What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
        72.How do I deserilaize an Object?
        73.What are different types of inner classes ?
        74.Difference Between String and String Buffer?
        75.difference between verses (==) and .equals().

        Java Drill – 1

        1.What is the difference between an Interface and an Abstract class?
        2.What is the purpose of garbage collection in Java, and when is it used?
        3.Describe synchronization in respect to multithreading.
        4.Explain different way of using thread?
        5.What are pass by reference and passby value?
        6.What is HashMap and Map?
        7.Difference between HashMap and HashTable?
        8.Difference between Vector and ArrayList?
        9.Difference between Swing and Awt?
        10.What is the difference between a constructor and a method?
        11.What is an Iterator?
        12.State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
        13.What is an abstract class?
        14.What is static in java?
        15.What is final?
        16.What if the main method is declared as private?
        17.What if the static modifier is removed from the signature of the main method?
        18.What if I write static public void instead of public static void?
        19.What if I do not provide the String array as the argument to the method?
        20.What is the first argument of the String array in main method?
        21.If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?
        22.How can one prove that the array is not null but empty using one line of code?
        23.What environment variables do I need to set on my machine in order to be able to run Java programs?
        24.Can an application have multiple classes having main method?
        25.Can I have multiple main methods in the same class?
        26.Do I need to import java.lang package any time? Why ?
        27.Can I import same package/class twice? Will the JVM load the package twice at runtime?
        29.What are Checked and UnChecked Exception?
        30.What is Overriding?
        31.What are different types of inner classes?
        32.Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?
        33.Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
        34.What is the difference between declaring a variable and defining a variable?
        35.What is the default value of an object reference declared as an instance variable?
        36.Can a top level class be private or protected?
        37.What type of parameter passing does Java support?
        38.Primitive data types are passed by reference or pass by value?
        39.Objects are passed by value or by reference?
        40.What is serialization?
        41.How do I serialize an object to a file?
        42.Which methods of Serializable interface should I implement?
        43.How can I customize the seralization process? i.e. how can one have a control over the serialization process?
        44.What is the common usage of serialization?
        45.What is Externalizable interface?
        46.When you serialize an object, what happens to the object references included in the object?
        47.What one should take care of while serializing the object?
        48.What happens to the static fields of a class during serialization?
        49.Does Java provide any construct to find out the size of an object?
        50.Give a simplest way to find out the time a method takes for execution without using any profiling tool?
        51.What are wrapper classes?
        52.Why do we need wrapper classes?
        53.What are checked exceptions?
        54.What are runtime exceptions?
        55.What is the difference between error and an exception??
        56.How to create custom exceptions?
        57.If I want an object of my class to be thrown as an exception object, what should I do?
        58.If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?
        59.How does an exception permeate through the code?
        60.What are the different ways to handle exceptions?
        61.What is the basic difference between the 2 approaches to exception handling…1> try catch block and 2> specifying the candidate exceptions in the throws clause?
        62.When should you use which approach?
        63.Is it necessary that each try block must be followed by a catch block?
        64.If I write return at the end of the try block, will the finally block still execute?
        65.If I write System.exit (0); at the end of the try block, will the finally block still execute?
        66.How are Observer and Observable used?
        67.What is synchronization and why is it important?
        68.How does Java handle integer overflows and underflows?
        69.Does garbage collection guarantee that a program will not run out of memory?
        70.What is the difference between preemptive scheduling and time slicing?
        71.When a thread is created and started, what is its initial state?
        72.What is the purpose of finalization?
        73.What is the Locale class?
        74.What is the difference between a while statement and a do statement?
        75.What is the difference between static and non-static variables?
        76.How are this() and super() used with constructors?
        77.What are synchronized methods and synchronized statements?
        78.What is daemon thread and which method is used to create the daemon thread?
        79.Can applets communicate with each other?
        80.What are the steps in the JDBC connection?
        81.How does a try statement determine which catch clause should be used to handle an exception?
        82.Can an unreachable object become reachable again?
        83.What method must be implemented by all threads?
        84.What are synchronized methods and synchronized statements?
        85.What is Externalizable?
        86.What modifiers are allowed for methods in an Interface?
        87.What are some alternatives to inheritance?
        88.What does it mean that a method or field is “static”? ?
        89.What is the difference between preemptive scheduling and time slicing?
        90.What is the catch or declare rule for method declarations?

        91.Is Empty .java file a valid source file?
        92.Can a .java file contain more than one java classes?
        93.Is String a primitive data type in Java?
        94.Is main a keyword in Java?
        95.Is next a keyword in Java?
        96.Is delete a keyword in Java?
        97.Is exit a keyword in Java?
        98.What happens if you dont initialize an instance variable of any of the primitive types in Java?
        99.What will be the initial value of an object reference which is defined as an instance variable?
        100.What are the different scopes for Java variables?
        101.What is the default value of the local variables?

        102.How many objects are created in the following piece of code?
        MyClass c1, c2, c3;
        c1 = new MyClass ();
        c3 = new MyClass ();

        104.Can a public class MyClass be defined in a source file named YourClass.java?
        105.Can main method be declared final?

        106.What will be the output of the following statement?
        System.out.println (“1″ + 3);

        107.What will be the default values of all the elements of an array defined as an instance variable?

        Java Coding Drill – On