Tuesday, December 25, 2007

why a servlet is preferred for JDBC

Servlet is preferred for JDBC code and not a static initializer block in a Class because the latter will be able to provide connections only when the static initializer block is run not before that ...
on the other hand ... servlet can be loaded on startup

Google : Open Social

Really interesting stuff ...
one can even make web sites that uses "Open Social API"
benefits of open social for
  • developer .. they have more clients
  • consumers ... they have more apps
Makes sense !! heres how ....


enables one to make application that can be used accross social networks !!

Wednesday, December 12, 2007

All about ADF tables

How do i make a ADF TreeTable ??
Saying it in very simple terms ... (i) first make POJOs ... using parent POJO and child POJO make a tree like hierarchy (ii) then using the ADF model classes convert them into ADF treeTable model !

Step one sounds easy .. can i have more details on step two ?
In ADF we have the following hierarchy...


has default constructor
inherits directly from java.lang.Object
The data collection underlying a DataModel instance is modeled as a collection of row objects that can be accessed by a zero-relative cursor (row index). The APIs provide mechanisms to position to a specified zero-relative row index, and to retrieve an object that represents the data that corresponds to the current row index.
DataModel is an abstraction around arbitrary data binding technologies that can be used to adapt a variety of data sources for use by JavaServer Faces components that support per-row processing for their child components
has a property rowIndex that starts from 0 ... up to max_no_of_child
has other methods like getRowData() getRowCount() .. setWrappedData() and getWrappedData() .. they set the object representing the data collection wrapped by this DataModel

implements no RowKeyIndex
has default ctor
The data model that is used by ADF Table components. This extends the faces DataModel class and adds on support for rowKeys and sorting.

*** oracle.adf.view.faces.model.TreeModel ***
It just has a default constructor ...

rows in a treeModel may contain other rows...
to figure out if current row is a container use method isContainer()
If a row is a container, use the enterContainer() method to access its child rows. Once the enterContainer() method is called all the CollectionModel API's methods (like DataModel.getRowCount()) operate on the child collection. To return back to the parent row, use the exitContainer() method.

|-Root1 (rowKey="r1", rowIndex=0)
| |-Folder1 (rowKey="r1f1", rowIndex=0)
| | |-Node1 (rowKey="r1f1n1", rowIndex=0)
| | |-Node2 (rowKey="r1f1n2", rowIndex=1)
| | |-Node3 (rowKey="r1f1n3", rowIndex=2)
| |
| |-Folder2 (rowKey="r1f2", rowIndex=1)
| |-Node4 (rowKey="r1f2n1", rowIndex=0)
|-Root2 (rowKey="r2", rowIndex=1)
|-Root3 (rowKey="r3", rowIndex=2)
|-Root4 (rowKey="r4", rowIndex=3)

so each row has a setRowKey() and setRowIndex() ... rowKey is inherited from CollectionModel and rowIndex from DataModel... the rowKey is unique accross the whole table ... rowIndex is relative to its parent ...
use setRowKey(null) to reach the root ...

To access Node4 use:

setRowIndex(0); // isContainer()==true
enterContainer(); // enter Root1, getRowCount()==2
setRowIndex(1); // isContainer()==true
enterContainer(); // enter Folder2, getRowCount()==1
setRowIndex(0); // isContainer()==false
getRowData(); // To access a particular row in the list, first make that row current, and then call the getRowData() method on the Table

Or, more simply:

*** oracle.adf.view.faces.model.ChildPropertyTreeModel ***
It extends TreeModel

Creates a TreeModel from a List of beans. To use this class you must have a tree of beans (or Maps). The structure of your tree must be a List (or array) of root beans, and each bean must have a getter method (or Map property) that returns the children List. All elements of your tree must be the same type.

Tree VS TreeModel
The Tree component displays a multi-root hierarchy in a simple UI... the TreeTabel displays a single-root hierarchy

You may find the oracle.adf.view.faces.model.ChildPropertyTreeModel class useful when constructing a TreeModel

*** the ***
The "nodeStamp" facet of the Tree is used to display the data for each element in the tree. The Tree does not create components per element; instead, the "nodeStamp" is repeatedly rendered (stamped) once per element. Because of this stamping behavior, only certain types of components are supported as children inside a Tree. Supported components include all components with no behavior and most components that implement the EditableValueHolder or ActionSource interfaces.
The Tree renders expand/collapse icons that the user can click on to expand or collapse a subtree. When these icons are clicked, the Tree generates a DisclosureEvent

The immediate children of a Table component must all be < af:column > components.
Use the "header" facet on a Column to create the column header.
The child components of each Column display the data for each row in that column.... that means it may be a textbox , a label , a textArea etc ...
Column does not create child components per row; instead, each child is repeatedly rendered (stamped) once per row... that means if there are 10 rows then the column elemnt will not create 10 children insteand 10 times rows will be created and each time one element for the column is created

Because of this stamping behavior, some components many not work inside the table. Anything that is just pure output, with no behavior, will work without problems, as will components that don't "mutate" even as they deliver events

one can have column groups ...

Columns can be rendered as row headers by setting the "rowHeader" attribute on < column > to be true. Row header columns must be the first columns in a table.

Range Navigation
When the list being displayed by a Table is huge, you can enable the Table to break up the list into ranges and display a single range at a time. Range controls are provided on the Table to let the user scroll to the next range, or to go back to the previous range.
thi smay also generate RangeChangeEvent

Displaying Details
You can configure the Table to display or hide additional details of a particular row in response to a user gesture. When the details feature is enabled, a new column containing a toggle (per row) will render in the Table. When a toggle is activated, the details for that row are displayed. When a toggle is deactivated, the details for the row are hidden. The user can also display or hide the details for all rows at the same time (the controls for this feature are enabled by setting the "allDetailsEnabled" property to true.)

To enable the details feature set the "detailStamp" facet on the Table. Place the components that are used to show the details (of a row), inside this facet. In the following example, the Person's age is displayed in the details section:

Usually, the default behavior of the Table (with respect to displaying and hiding details) is sufficient. In some cases, however, it might be desirable to programmatically display or hide the details for a particular row. This can be done via the RowKeySet object obtained from the Table by calling the getDisclosureState() method. First, make the relevant row current by calling setRowIndex(...) or setRowKey(...) on the Table, and then call add() or remove() on the RowKeySet object. Adding the row to the set displays the details of the row. Removing the row hides them.

*** ***
The ADF Table component uses a model to access the data in the underlying list. The specific model class is oracle.adf.view.faces.model.CollectionModel . You may also use other model instances, e.g., java.util.List , array, and javax.faces.model.DataModel . The Table will automatically convert the instance into a CollectionModel ...??? not sure how will that happen as there is only one constructor for the CollectionModel and thats the default constructor ???

*** the ***
single-root hierarchy
TreeTable's children must be ADF Column components
the tree table has a "nodeStamp" and a "pathStamp" facet ... Like the Tree, the TreeTable has a "nodeStamp" facet which renders the "Object Name" Column. The TreeTable has a "pathStamp" facet for rendering the focus path.

*** obvious ***
ifmy af:table is inside af:panelcollection .. first panelcollection is made then the table

Tuesday, December 11, 2007

ANT and versioning


Software Engineering

what THEY say ...
The idea is to create a language around the problem you're trying to solve in order to make it easier to solve the problem.
what I understood ...
yes i kind of agree to that ... as far as my experience with product development goes succesfull product development companies have made there own properiatory frameworks first and then used to it to solve the problem in hand ..
so what do they gain by making this framework ... ? wouldnt one save time by using existing framework .. ??
my take is they visualize a big problem break it down to small ones by making small components / classes / APIs and solve each of them individually
They even sav time .. how ?? if a bug comes in the framework they can solve it in less time rather than delegating it to some one else !

There's always a big difference between setting out to invent new solutions and setting out to invent new problems... confused ?? allow me to explain ... rather than solving a big problem first try to break it into new problems .. smaller and more specific ones .. then soolve each of them ... if new design or constraints come up then they too can be solved with similar approach ...
I wonder if its "Decorator Pattern" ;o)

Dont waste a lot of time and money in solving yesterdays problem ... i hope it makes sense .. and thats what JAVA is upto ...

cheerz !!

Saturday, December 8, 2007

More JSF

For a web application, all objects held in the application scope must be handled in a threadsafe manner; because all users and all requests have access to the objects in this scope, it's very likely that more than one thread will access the same object. Objects in the session scope must also be threadsafe, because they are shared by all requests from the same user. If the user makes parallel requests, e.g., by submitting the same form over and over without waiting for the response, making requests from multiple browsers tied to the same session, or requesting pages that contain references (e.g., frame references) to other pages that modify session scope objects, a session scope object's state can be corrupted.

When you use JSP as the presentation layer technology for JSF, you don't use the JSF API at all for creating and rendering components. Instead, you use the custom actions from the JSF custom tag libraries to say which components you need, and the tag handlers use the JSF API to create and render the corresponding component objects for you.

The first action element in the page, , is very important. The combination of the components that make up a specific user interface screen is called a view in JSF. A view contains an instance of the javax.faces.component.UIViewRoot class. This class is a nonvisual component type that acts as a container for all the other components in the view. Components representing UI widgets, such as input fields and buttons, are children of the UIViewRoot and can have children of their own. Together, the components form a tree, with the UIViewRoot at the top. The action element represents the UIViewRoot component and you must make sure it encloses all other JSF action elements in the page; otherwise, they aren't included in the view.

Note that there's a one-to-one relationship between a JSF view and an HTTP response. Hence, you must use only one element in the JSP page. A JSP page can, as you may know, include other JSP pages dynamically. Such included pages represent subviews in JSF, and are represented by an element.

The next JSF action element, , represents a form component, acting as a container for input components that hold values that should be processed together. Within the element

The element names for all these actions are composed from a component type name and renderer type name. The core JSF components represent pure behavior and know nothing about how they are represented on a screen. This task instead falls on renderers associated with each component, making it possible to represent the same type of component in different ways. Take < h : inputText >, for example. It represents an input field component, i.e., a component type that holds a value that can be changed by the user. Such a component can be rendered in different ways. The < h : inputText > action associates the input component with a text renderer, which renders the component as an HTML < input > element with the type attribute set to text. Another action element named < h : inputSecret > associates an input component with a renderer of type "secret," which renders the component as an HTML < input > element with the type attribute set to password.

< h : commandButton >
component Type : command
Renderer type : Button

< h : commandLink >
component Type : command
Renderer type : Link

< h : panelGroup >
component Type : panel
Renderer type : Group

< h : panelGrid >
component Type : panel
Renderer type : grid

< h : selectOneMenu >
component Type : selectOne
Renderer type : menu

Most component types can be combined with more than one renderer type, and each valid combination is supported by an action element following the naming convention.

So why doesn't the element name follow the same convention? Because the only renderer type for the form component type is the form renderer. To avoid action element names like , JSF uses an abbreviated element name when the component type and the renderer type have the same name

JSF Overview

The UIComponentBase class is the base class for all JSF UI components. Subclasses represent specific interface elements, such as text fields, links and buttons, labels, menus and selection lists.

The components fire events in response to user actions (such as clicking a button) and event listeners attached to the components handle the events (for example, by updating a database). Instead of implementing and registering listeners for each component, most JSF applications take advantage of shortcuts in the form of method bindings. A method binding is similar to a value binding, but it binds a component to an application method instead of an application property value. For instance, the UICommand component has a property that takes a method binding value. When the component fires an ActionEvent, a default ActionListener provided by JSF and automatically attached to the component invokes the method that the method binding points to. All the component writer needs to do is implement the method.

but declaring the scope as session (or others) means that a unique instance is created for each user and remains available as long as the user actively uses the application

Elements with the prefix h (short for HTML) represents the standard JSF UI components combined with HTML renderers; elements with the prefix f (short for Faces) represent validators, event listeners, etc. that can be attached to the UI components

The basic hierarchy is and inside it is

When JSP page is invoked for first time then
< h : inputText value="#{abc.emailID}" / >
i) the corresponding UIInput element is created
ii) Its property value bound to the bean value specified by the binding expression
iii) component is asked to render itslef ... i.e. renderer called !
iv) It evaluates value binding expression and if bean doesnt exist ( based on scope ) then JSF creates it!
v) The input component pulls its value from the property of the bean specified by the rest of the value binding expression and uses it as the value of the HTML < input > element it renders

When the user enters values in the form and clicks the Submit button, JSF processes the request by asking each component to get its value from the request .. so basically JSF doesnt talk to HTTPRequest .. but components ... Each input component sets the bean property it's bound to, and the command component fires an event that causes the method it's bound to be invoked. The method typically saves the new values to a database or does some other backend processing.

This is a very simplified description of what really occurs at runtime. As you will learn, there's a lot more that may happen when a form is submitted, such as input value conversion and validation, error message queuing, forced redisplay of the same page without updating any bean properties, and more. simple description helps understand understand the basics of how the application code and the JSF components fit together.

Java Calendar VS Date

Although Date is deprecated but still we cant use a java.util.calendar abstract class when we are looking forward to make a String like "8th December 2007" coz all the members of the Calendar class are int types
so code like
Calendar cal = new GregorianCalendar();
Calendar cal=Calendar.getInstance();
int i = cal.get(Calendar.VAR_OF_I);
will always give integer ....
// Gotcha warning: months go from 0 to 11

GregorianCalendar is the actual implementation of the abstract Calendar class and supplies good behavior

If you want to compare it to a different date time, you've got all you need in the date variable. If you want to display the value, use a date formatter to build a String in the desired format, & that's it.

One can convert Calendar object to Date object using getTime() method.

Think of java.util.Date as an abstract instant in time. It has no time zone, calendar, clock or any other structuring we've put on time. A Date only knows how many milliseconds had elapsed since Jan 1, 1970 00:00 UTC when this instant occurred
Date testDate = calendarObject.getTime();

The bottom line: if you just need to keep track of a date/time as most people do, just use a Date. If you need to also remember a specific time zone with it, choose Calendar. If you need to specifically use western calendar system, use GregorianCalendar.

using java.util.Date has one more advantage if one wants to move objects around over RMI. Calendar and Gregorian Calendar do not implement serializable. one could sub-class GregorianCalendar and make it serializable.

Even the Java Date object assumes that the date value stored is GMT. The value of the datetime that is displayed will depend on your location, or the location of the system that is generating that representation. For example, if I have an application on my machine in London and I view that Date object I would see 01April2002:10:00, now if that same Date object was used by a webserver on the east coast of the US to generate a web page it would generate 01April2002:05:00

To convert Calendar object to String

Calendar cal = Calendar.getInstance(TimeZone.getDefault());
String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
String currentTime = sdf.format(cal.getTime());

Convert java.util.Date to java.sql.Date

java.sql.Date stores only date information, not times. Simply converting a java.util.Date into a java.sql.Date will silently set the time to midnight. So, to store date/times to be manipulated as java.util.Date objects, don’t do this

// BUG: loses time of day
preparedStatement.setDate(1, new java.sql.Date(date.getTime()));

do this instead:

preparedStatement.setTimestamp(1, new java.sql.Timestamp(date.getTime()));
java.sql.Timestamp is not a date

java.sql.Timestamp extends java.util.Date, but it should not be used as a Date. In JDK 1.3.1, Timestamp.getTime() (inherited from Date) returns the time to the nearest second only, but JDK 1.4.2 and JDK 1.5 it returns the time to the nearest millisecond as expected. So in JDK 1.3, when reading a timestamp from a ResultSet, don’t do this

// Java 1.3
java.util.Date d = resultSet.getTimestamp(1);
long millis = d.getTime(); // BUG: loses fractional seconds in JDK 1.3

To get the full date including milliseconds, you have to do this :

java.sql.Timestamp timestamp = resultSet.getTimestamp(1);
java.util.Date d = new java.util.Date(timestamp.getTime() +
timestamp.getNanos() / 1000000);

In JDK 1.4.2 and JDK 1.5, you can just do this, depending on what you’re going to do with the Date:

// Java 1.4+
java.util.Date d = resultSet.getTimestamp(1);

But this might be safer since it avoids any other potential Timestamp problems

// Java 1.4+
java.util.Date d = new java.util.Date(resultSet.getTimestamp(1).getTime());

If your code needs to run on JDK 1.3 and later, you’ll have to do this:

java.sql.Timestamp timestamp = resultSet.getTimestamp(1);
long millis = (timestamp.getTime() / 1000) * 1000 + timestamp.getNanos() / 1000000;
java.util.Date d = new java.util.Date(millis);

JSF Intro

What is JSF ??
JSF is a specification with implementations offered by multiple vendors. It defines a set of user interface (UI) components—basically, a one-to-one mapping to the HTML form element set plus a few extras—that can be used right out of the box, as well as an Application Programming Interface (API) for extending the standard components or developing brand new components.

JSF is not limited to HTML or any other markup language. Renderers that are separate from the UI components control the actual markup sent to the client, so the same UI component coupled with different renderers can produce very different output—for instance, either HTML and WML elements

JSF gives you lots of flexibility in how you actually develop the user interface. All JSF implementations are required to support JavaServer Pages (JSP) as a presentation layer technology, with JSF components represented by JSP custom action elements (also commonly known as custom tags). The JSF API, however, is flexible enough to support other presentation technologies besides JSP. For instance, you can use pure Java code to create JSF components, which is similar to how a Swing UI is developed. Alternatively, you can bind JSF components to nodes in templates described by plain HTML files,

JSF brings a component-based model to web application development that is similar to the model that's been used in standalone GUI applications for years. Each component has an id attribute for the elements representing dynamic content so that it can be changed !

JSF UI components declare what events they can fire, such as "value changed" and "button clicked" events, and external event listeners (representing the Controller) attached to the components handle these events

An event listener may set properties of the JSF components—for instance, adjust the set of rows shown in a table—or invoke backend code that processes the submitted data (say, verify that a credit card is valid or update a database).

A separate renderer class (representing the View) renders each JSF UI component, making it possible to render instances of the same component type in different ways (e.g., either as a button or a link, or using different markup languages) just by attaching different renderers.

Besides the UI components, JSF also defines artifacts like validators and converters, each with a well-defined

The best fit for JSF is a true web application—a web site with a lot of user interaction—rather than a web site with some dynamic content.

JSF does not necessarily replace current technologies. It's a complement that brings structure and maintainability to the application user interface. The following sections describe how JSF fits with some established Java web application technologies

As you have already seen, JSF plays nicely with JSP. In fact, all JSF implementations must support JSP and provide tag libraries with custom actions for representing the standard JSF UI components in JSP pages.

Struts and similar frameworks as application frameworks, and to JSF as a user interface framework. this to emphasize that they have different objectives. An application framework's objective is to support the development of complete applications; it's concerned with the Big Picture. This type of framework acts as a traffic cop, routing HTTP requests to request handling code and internal view requests to response rendering code based on mappings between symbolic names and the different types of application components. An application framework doesn't care about details, such as how the user interface is rendered, or make any distinction between user actions that only affect the user interface (e.g., asking for the next set of rows to be displayed in a table) and actions that need to be processed by backend code (e.g., processing an order on an e-commerce site). Struts, for instance, can use JSP, Velocity, XSLT, or any other presentation layer technology to render a response. The Struts servlet just routes requests to application classes that process them and then tell Struts which page to display next.

A user interface framework, on the other hand, focuses on the user interface details and isn't concerned with how the rest of the application is implemented. It defines a detailed API for user interface components, for how user actions result in user interface events and how these events are handled, how the components are tied to the business data they visualize, and so on.

Thursday, November 22, 2007

Web Services : Just Right Clicking Java Files ??

Lot of Application servers give the provison of directly deploying a java file as webservice very easily ... hiding everything beneath it ... I tried something similar today and noticed something ...

The java functions that are being exposed as web services they must throw Pre Defined Exceptions ... or may be Custom Java Excpetions coz throwing a Exception object is not a good idea as it may throw a Checked or Unchecked exception and user will have to always catch it no matter what the excpetion may be then check the class type using instance of and act accordingly ...

DiSaDvAnTaGeS of Using ~ Throws Exception ~ and ~ Throws Throwable ~

Using throws Throwable and throws Exception subverts the exception checking system. If you do this, callers are forced to catch Throwable or Exception, which may catch both unchecked and checked exceptions. This forces callers to use instanceof to see whether the exception is one that they can deal with.

Essentially, this defers the exception-checking mechanism from compile-time to runtime, which of course converts compile-time errors to runtime errors.

On a related note, there’s not much point in specifying unchecked exception types in a throws clause, for example throws RuntimeException or throws NullPointerException. This serves no purpose except documentation, and it’s better to use a @throws javadoc comment for this, as you can include more information in the javadoc comment.

Thursday, September 27, 2007

Power Of Flex

Came across this cool Rich Internet application ... It sure is a surfers delight
With such cool desktop like web interfaces i some how feel that the flex platforma has a long way to go ...
See the Tab2 "Mobile Phone Sales" It shows three graphs they are inter-related in good way if you click on one then the corresponding graph changes on other graph
Seeing such UIs i am very much inclined to Rich Internet Applications or Flex more specifically


Strange Error

Today instaed of using "if" i used "If" and starnge enough compiler gave me ';' expected error... couldnt figure out why ??

Jab4Trans Version 0.1 Released

Recently have been busy with my open source project http://sourceforge.net/projects/jab4trans today released version 0.1 of it.

I called it jab4trans based on the popular nomeclature thats being followed in the java world like jab4log :). The name itself is self explanatory "jab4trans" i.e. "jabber for translation". An attempt to extended the jabber protcol to translate language text. The first question that comes up which two languages are being considered for it ... I assumed two fictious languages "UPPER" and "lower" and tried converting them vice versa. May be if someone has made open source / licensed tool for language translation pls allow me to use it or any pointers to same will be higjly apreciated.

The major concerns here are ...
1. Writing server - i havent written a robust or secure server or a server that can handle thousands of clients just a plain server in its simplest form that waits for incoming connections and handles them.
2 Implemnting Jabber protocol - Jabber protocol handels thre types of packet and i have just implemented the only type of message i required ( thats what i have judged till now)
3. Converting the chat packets - converted packets from UPPER to lower and vice versa using an extra tag that is kept to allow extending the protocol
4. Two languages for translation - As said earlier have used two fictious languages "UPPER" and "lower" looking forward to use some APIs for same that implies i will have to use a different encoding for xml packets ... lets see how much succesful i will be for same. I tried google language tools but it seems as if they are not relased as APIs for third party developers .. pls correct me if i am wrong !!

I kept the version as 0.1 coz i feel its a "proof of concept" code and not even close for 1.0 release need to atleast implement the point number 2 and 3 mentioned fully ... Its still ininfancy i would say.

Bug -> No software complete without a BUG he he he... just kidding had less time so released it with a know bug ... the packets to be translated are being added "twice" as of now .. and converted twice too ... need to rectify it asap

Wat Say ??

Tuesday, September 25, 2007

Friday, September 14, 2007

FLEX 2.0

I tried flex and the so called RIA(Rich Internet Application) today ... made a Hello world .. understaood the basics of MXML , ActionScript , Class Libraries , and DataServices.How all these pieces fit together .... Beleive me flex is so so powerful ... i can now create applications so easily at just click of mouse ...

Moreover the IDE "Flex Builder" is a*w*e*s*o*m*e* i mean just take a simple example of making a simple page that has "Name Label" and "TextBox" and "Address Label" and "TextArea" in order to make this page in design view the IDE gave me so good aligmnet indications ( both vertical and horizontal) i never saw that in an IDE befor ( may be u can say at least the ones i used )

Another plus point .. using flex i guess i can make the same application easily for desktops and mobiles ... withput much of a coding headache... i need to explore more on that ...

But i get an error during debugging mode

Flex Builder cannot locate the required debug version of the Flash Player. You may need to install the debug version of Flash Player 9.0 or reinstall Flex Builder. Do you want to try to debug with the current version?

Trying to figure out what does that mean ... on forums

Monday, August 20, 2007

Saturday, August 18, 2007

String VS StringBuffer : Bytecode level

found this article on String VS String Buffer and the interesting part is difference is explained in terms of bytecode ...
The byte code didnt make MUCH sense to me ... EXCEPT that StringBuffer creates less bytecode that string.


Tuesday, August 14, 2007

Java Puzzlers

see this .. best java puzzles ever
wat say ??

Adding my bit of cheese on it try predicting output of

class Some_Runnable implements Runnable {
public void run() {

class Some_Thread extends Thread {
Some_Thread() {}
Some_Thread(Runnable r) {
public void run() {

class Some_Other_Thread extends Thread {
Some_Other_Thread() {}
Some_Other_Thread(Runnable r) {
public void run() {

class default_thread extends Thread {
default_thread() {
System.out.println("IN default thread ");
default_thread(Runnable r ){

public class Class2 {
public static void main(String args[]) {
// lang.Thread class implements Runnable
new Some_Thread().start();
new Some_Thread(new Some_Runnable()).start();
new Some_Thread(new Some_Other_Thread()).start();

new Thread(new Some_Runnable()).start();
new Thread(new Some_Other_Thread()).start();

System.out.println("Default Thread ... doesnt override run()");
new default_thread().start(); // ok
new default_thread(new Some_Runnable()).start();
new default_thread(new Some_Other_Thread()).start();


Monday, August 13, 2007

Oscars of the Software Industry

I am hearing it for the first time ..
may be coz i am not that much aware of the industry awards
never thought of exploring the same
But the findngs are interesting

Oracle Database 10g' is the winner of the best enterprise database and 'Oracle ADF Business Components' the best Java Component as announced by the 'Oscars of the Software Industry'.

Check out this link:

Thursday, August 9, 2007

Observable Collection

came accross this observable collection

something useful and nice ..
didnt get time to try it out ...
but soon will ...

this thread talks more about it

Wednesday, August 1, 2007

Out of Box : Java Tuts

Found these ..
Best way for a novice to start learning java ...
Out of box thinking my friend ...
Just doing my bit to promote them

Start with installing JDK

Make a Hello World

Learn about Variable and Arithmetic

World Famous If statements

Java and OOP


Switch Statement

Java Arrays

Cheerz !!

Child Class Should do all Initialization


consider the following code... it will give compile time error

class memberClass
System.out.println("Member Class constructor called");

class ParentClass
System.out.println("Parent Class constructor called");

public class ChildClass
private memberClass = new memberClass();

public ChildClass()
// super has to be the 1st call in the constructor ..
// cant pass it memberClass as argument : ERROR
// SOLUTION : do all initialization in Child

public static void main(String[] args)
System.out.println("Hello World!");

Error : cannot reference this before superclass constructor has been called

package try_project1;

class memberClass
System.out.println("Member Class constructor called");

class ParentClass
ParentClass( )
System.out.println("Parent Class constructor NO INITIALIZATION ");

public class ChildClass extends ParentClass
private memberClass memc= new memberClass();

public ChildClass()
System.out.println("do ALL INITIALIZATION in child Class");

public static void main(String[] args)
System.out.println("Child Class Hello World!");
ChildClass cc = new ChildClass();

Saturday, July 28, 2007

Beyond Sun Java Certification

came across this site
someting i was always looking for ...
certification by sun on java includes only basic things
not popular framework like spring , hibernate ..

nice job friends !!

Cool Tool to colorize code

my friend suggested me this cool tool ...
i wanted to colorize my code .. using the color scheme as in IDE
this is cool copy cust paste tool ...
sth we all programmers (??) are used too

he he he

Good Servlet Bad Servlet

lest try to code the same servlet in good way and bad way

public class Bad_Servlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html";
// BAD : this line created one more java object to be GC

public void init(ServletConfig config)
throws ServletException
System.out.println("LOG : Init called");
// BAD : using sop is bad it will require Servlet
// to synchronize disk actions and http response.

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
PrintWriter out = response.getWriter();
String output="<html>";
output+="<head><title>Bad Servlet</title></head>";
output+="<p>The servlet has received a GET. This is the reply.</p>";
// BAD : pat ur backs once if u judged using variable will create one
// more object for Garbage Colection PAT ur back many times if u judged
// that using + operator with "temp" will cr8 many temp string objects 4 GC


//BAD : overriding destroy() will help u freeing ur resources ..
// that will reduce burden on webServer GC cant go ahead until
// it is sure resources re free

now the same code in Good servlet

public class Good_Servlet extends HttpServlet {

public void init(ServletConfig config)
throws ServletException

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

PrintWriter out = response.getWriter();
out.println("<head><title>Good Servlet</title></head>");
out.println("<p>received a GET. This is reply.</p>");
for ( int i = 10; i > 0; i-- )
out.print( "<h1>" );
out.print( i );
out.println( "</h1>" );
// make sure the browser see the count
// another use of using println()
Thread.sleep( 1000 );
// this loop takes time
// BUT user wont experience difference
catch ( InterruptedException e ) { }
If a page contains a number of graphics
(in a header, for example), each of those graphics
needs a separate HTTP request to be loaded.
If the servlet calls flush() after writing the
IMG tags for the graphics into the PrintWriter,
the browser can start loading the graphics
while the servlet is still processing the original request.
This reduces the amount of time required to display the
complete page in the browser because the separate requests
can be handled concurrently.

// The difference here is that all output is written directly
// to the PrintWriter, which does not require creating any
// intermediate objects

public void destroy(){

Monday, July 2, 2007

Guruji .... a guru ??

came accross http://www.guruji.com/ the first thing i did not like is the punch line ...
"the indian search engine"
guys why do you want to regionalise technology ... and why are people trying to cash on region wise ... its a big world out there ... go compete.... may the best technology win ... !!

and the funnier part ...
try searching ... "flex coders india" ( mind you tried searching something specific to india )
and the FIRST result i got was ....
based on following highlighted text

man that was pathetic ...
try the same on THE Search Engine .. i mean google ... and u get
http://www.flexcoders.net/ ( international registry for flex coders )
and second result ...
google group ... groups.google.com/group/bombayflexcoders
second is more relevant than 1st ...

and DEFYING the "dont be eveil motto"
guruji started a contest ... for everyine to use there search engine .. and win prizes
ok ... quite a few people will start using this service if promoted like this
but what after the offer is gone ..

as the saying goes ... 1st impression is the last impression ...

all i can say is that
(i) guruji u need improve a lot ...
(ii) guruji pls dont bias in terms of regionalism ...
(iii) dont bribe guruji ... that is not good in long term ...

hope to see gurji in better shape soon
cheerz !!

Thursday, June 14, 2007

Safari for windows ... BUGGY ??

continuing the browser war ... apple recently (June 12, 2007 ) introduced "safari" for windows ... as always being bitten by tech bug to try out new software .. i installed it and started using it ... but using popular web2.0 sites on safari is not a possible as of now...

try out using yahoo mail beta .. you get a screen saying your browser is currently not supported ... and even if one continues using it .. surely safari will crash ...

on the other hand ... try using gmail .. google suggests work fine on it ... infact i read it somewhere google pages that they are currently working to make there sites compatible with safari ... guess they are already on way .. moreover the way safari displays text box etc .... is really nice .. i mean all that blueish light around login text box .. cooollllll

talking of bright side ... the 'search feature ' on safari is something really out of box ... excellent i must say ... as soon as you search a text all the occurences get highlighted (obvious ... ) but the best part is rest of page turns greyish ... making the searched text easily viewable ...

movable tabs ... i dont think its a great feature ... ok kinda thing ...

moreover ... security is a big big drawback ... find posts here and here ... about secuirty issues of theis browser ...

moreover ... i found a bug in the 3.0 release ... and logged it against apple .. Bug ID#5271889 ... lets see how they track it ...

introducing safari for windows is a nice move ... but the first impression is ... its buggy ... and moreover they shouldnt have released it as Beta version .. looks more like an alpha to me ...

Sunday, May 6, 2007

www.indianrail.gov.in : usability & accesibilty issues

Software has been a growth sector in India. But has software really changed our lives ... the way it should have .. or to its maximum potential ... ??

I am talking of government sites in particular ... I don't think that the Indian government web sites live up to the reputation that the Indian software industry has !!

I was not so much in favor of using the Indian railways web site for bookings until recently started using internet reservation... and not surprisingly found the following MAJOR BUGS in the same

  1. The page picks up date of reservation from the client ... and does calculation accordingly .. if i change my computer date by a month then the it will be shown on the journey date ... but the worst part is the three months reservation period will be calculated based on the wrong date .... yikesss !! Only a novice web programmer can do such a thing ... taking clients date instead of server date ... i wonder which software company has developed the site
  2. I wonder what will the output be on linux systems ... or mac systems .. as using javascript to get clients date ... that part needs to be checked on all platforms ... what will happen for symbian OS ?? ;o)
  3. Site being slow .... and ... bank being debited for ticket charges while not getting the tickets is a common error !!
  4. The look and feel is not at all professional .... Off track ... not talking of bugs .. but general ... while going for e-ticket one is asked to carry the identity proof ... as if the normal tickets have a photo or some other identity mechanism ... so why this rule for e-tickets ?? i find no logic ... for same !! possibly a way to get
  5. Using outdated DOS based reservation system at the ticketing counter ,,,, phew !! ontop of that the dot matrix printers may give you un readable print outs ...
laloo bhai ... with so much reformation going around in the railway industry i think its high time you also pay attention to the old software & printers being used in the system

Wednesday, April 18, 2007

Interesting observation about JSF

i came across an interesting fact
due to my usual habit of copy_cut_paste
but will find about the reason for it later ... when i have more time in hand

If I have the following code on a page ... ( neglect the wrong syntax .. lib name excluded )
** NOTE ** that the id of both the <:selectOneMenu>
so how does JSF handles it ...

<:outputText value="SOME_OPTION" />
<:selectOneMenu id="id_one" >
<:selectItem itemValue="option_1" itemLabel="option_1"/>
<:selectItem itemValue="option_2" itemLabel="option_2"/>
<:selectItem itemValue="option_3" itemLabel="option_3"/>

<:outputText value="ANOTHER_OPTION" />
<:selectOneMenu id="id_one" >
<:selectItem itemValue="another_option_1" itemLabel="another_option_1"/>
<:selectItem itemValue="another_option_2" itemLabel="another_option_2"/>
<:selectItem itemValue="another_option_3" itemLabel="another_option_3"/>

well ..
It doesnt give a Compile time error
NOR does it give a Runtime error
... instead ...
when the page is displayed then the second option is silently removed

wonder why ??

Tuesday, April 17, 2007

securityException : package is sealed

Recently came across a securityException .. package is sealed
on doinga lil bit of search came to know that the reason is
classes14.jar was being some how imported twice in the project
so i removed one of the jar files which in turn had classes14.jar
and the code executed normally

but there are still some things which i will like to study and post later
more info here and here

Saturday, March 31, 2007

Java Version 1.5.0 or 5.0?

Already knew the fact that ... Java 5 and 1.5 are the same thing but the following article at suns site clearly spotlights the similarity in exact technical jargon ....

Thought it would be useful for my friends also
cheerz !!

Monday, March 26, 2007


I happen to go through useful tutorials on oracle's 'Explain plan' utility ... but it was a bit cranky(at first) ... so thought would share answers to some questions that would " probably " come in mind of anyone who starts with it

What is it ??
A statement's execution plan is the sequence of operations Oracle performs to run the statement.
Basically EXPLAIN PLAN statement displays execution plans chosen by the Oracle optimizer for SELECT, UPDATE, INSERT, and DELETE statements

When do i use use ??
To tune SQL statements.. Tuning problematic SQL statements is no magic. Oracle generates an execution plan for the submitted SQL. This execution plan then tells it how to retrieve the data, or, how to perform the data-related tasks. The better one understand how to interpret these explain plans, the better one can resolve possible performance issues with the SQL.

Any Pre-Requisites ??
Yes .... Before issuing an EXPLAIN PLAN statement, you must have a table to hold its output called plan_table. Use the SQL script UTLXPLAN.SQL to create a sample output table called PLAN_TABLE in your schema. For description of the plan_table click here...

How to get the execution plan ??
In sql prompt simply type

FOR SQL_Statement

You can get the execution plan from the EXPLAIN PLAN SQL statement, from querying V$SQL_PLAN, or from SQL trace.
It can also be invoked in a button-click fashion in a variety of GUI tools such as Oracle Enterprise Manager (OEM), TOAD, SQL Navigator, and Oracle SQL Developer. But in opinion of some SQL gurus... single-click Explain Plan tools, frequently show the wrong plan; ie. not the plan that is used by the live production code. The Cost Based Optimizer (which generates the SQL execution plan )is sensitive to a number of session-level database parameters, any of which may be overridden either by the production code or the GUI tool.

OTHER ... synatx(es) for explain plan
SET STATEMENT_ID = identifier
FOR SQL_Statement

INTO different_table
FOR SQL_Statement

How can execution plan change for same SQL ??
Execution plans can differ due to the following:
* Different Schemas
* Different Costs

Different Schemas
* The execution and explain plan happen on different databases.
* The user explaining the statement is different from the user running the statement. Two users might be pointing to different objects in the same database, resulting in different execution plans.
* Schema changes (usually changes in indexes) between the two operations.

Different Costs
Even if the schemas are the same, the optimizer can choose different execution plans if the costs are different. Some factors that affect the costs include the following:
* Data volume and statistics
* Bind variable types
* Initialization parameters (set globally or at session level)

Some examples ??


EXPLAIN PLAN SET statement_id = 'example1' FOR
SELECT full_name FROM per_all_people_f
WHERE UPPER(full_name) LIKE 'Pe%' ;


This plan shows execution of a SELECT statement. The table PER_ALL_PEOPLE_F is accessed using a full table scan.
* Every row in the table PER_ALL_PEOPLE_F is accessed, and the WHERE clause criteria is evaluated for every row.
* The SELECT statement returns the rows meeting the WHERE clause criteria.


EXPLAIN PLAN SET statement_id = 'example2' FOR
SELECT full_name FROM per_all_people_f
WHERE full_name LIKE 'Pe%' ;


This plan shows execution of a SELECT statement.
* Index PER_PEOPLE_F_N54 is used in a range scan operation.
* The table PER_ALL_PEOPLE_F is accessed through ROWID. ROWIDs are obtained from the index in the previous step for keys that meet the WHERE clause criteria. When the table is accessed, any additional WHERE clause conditions that could not be evaluated during the range scan (because the column is present in the table and not in the index) are also evaluated.
* The SELECT statement returns rows satisfying the WHERE clause conditions (evaluated in previous steps).


EXPLAIN PLAN SET statement_id = 'example3' FOR
SELECT segment1, segment2, description, inventory_item_id
FROM mtl_system_items msi
WHERE segment1 = :b1
AND segment2 LIKE '%-BOM'
AND NVL(end_date_active,sysdate+1) > SYSDATE ;


This plan shows execution of a SELECT statement.
* Index MTL_SYSTEM_ITEMS_N8 is used in a range scan operation. This is an index on (SEGMENT1, SEGMENT2, SEGMENT3). The range scan happens using the following condition:
segment1 = :b1
The rows that come out of this step satisfy all the WHERE clause criteria that can be evaluated with the index columns. Therefore, the following condition is also evaluated at this stage:
segment2 LIKE '%-BOM'
* The table PER_ALL_PEOPLE_F is accessed through ROWIDs obtained from the index in the previous step. When the table is accessed, any additional WHERE clause conditions that could not be evaluated during the range scan (because the column is present in the table and not in the index) are also evaluated. Therefore, the following condition is evaluated at this stage:
NVL(end_date_active,sysdate+1) > SYSDATE
* The SELECT statement returns rows satisfying the WHERE clause conditions (evaluated in previous steps).


EXPLAIN PLAN SET statement_id = 'example4' FOR
SELECT h.order_number, l.revenue_amount, l.ordered_quantity
FROM so_headers_all h, so_lines_all l
WHERE h.customer_id = :b1
AND h.date_ordered > SYSDATE-30
AND l.header_id = h.header_id ;


This plan shows execution of a SELECT statement.

* Index so_headers_n1 is used in a range scan operation. This is an index on customer_id. The range scan happens using the following condition:
customer_id = :b1
* The table so_headers_all is accessed through ROWIDs obtained from the index in the previous step. When the table is accessed, any additional WHERE clause conditions that could not be evaluated during the range scan (because the column is present in the table and not in the index) are also evaluated. Therefore, the following condition is evaluated at this stage:
h.date_ordered > sysdate-30
* For every row from so_headers_all satisfying the WHERE clause conditions, a range scan is run on so_lines_n1 using the following condition:
l.header_id = h.header_id
* The table so_lines_all is accessed through ROWIDs obtained from the index in the previous step. When the table is accessed, any additional WHERE clause conditions that could not be evaluated during the range scan (because the column is present in the table and not in the index) are also evaluated. There are no additional conditions to evaluate here.
* The SELECT statement returns rows satisfying the WHERE clause conditions (evaluated in previous steps).

Found the same on other sites too ... didnt understand them.. completely
In examining examples , it is easy to follow the explain plan indentations. Basically, Oracle works from the most indented item outwards, so Oracle will work on the most indented item first.

Its tough to inter prate which one is the most indented one ... ??
Well the answer is one may use Dan Hotka's query to see the corresponding child id and parent id with indentedation

rem Dan Hotka Pinnacle Professional article
rem Show_Plan.sql - used to print contents from Plan_Table
rem Install utlxplan.sql for each user, then put this line in front of sql statement
rem --> explain plan set statement_id = '' for
rem --> run this script --> sqlplus userid/pwd @show_plan
set pagesize 20
set linesize 80
column id format 999 heading 'ID'
column parent_id format 999 heading 'P_ID'
column cost format 999 heading 'Cost'
column access_plan format a30 heading 'Access|Plan'
column access_path format a15 heading 'Access|Path'
column object_name format a15 heading 'Object|Name'
select cost,id, parent_id, lpad (' ', 2 * level) || operation Access_Plan, options Access_Path,
from plan_table
where statement_id = '&1'
connect by prior id = parent_id
start with id = 0;
delete from plan_table where statement_id = '&1';

save the above as Show_Plan.sql and use it

Explain plan descriptions ??
FILTERs apply 'other criteria' in the query to further qualify the matching rows such as correlated subqueries.
FULL Table Scan
Table being accessed from beginning to end, not using an Index.HAVING clause.
SQL statement utilized a unique index to search for a specific value.
SQL statement contains a non-equality or BETWEEN condition.
SQL statement initiated a hash-join operation, tables are read and put into a memory structure accessed via a mathematical calcuation (known as a HASH key).
A join method used when more than one table appears in the FROM clause. Oracle will sort the two result sets being joined over the join columns and then merging the results via the join columns.
This operation is another form of joining tables. One row is retrieved from the row source identified by the first statement ID under the NESTED LOOP, and then joined to all matching rows in the other table referenced by the NESTED LOOP.

Each of the join conditions — NESTED LOOP, MERGE JOIN, and HASH JOINS — makes an intermediate result set that is passed to the parent ID.

Plan Steps ??
You may also divide the plan steps in
i) Plan steps with no children
ii) Plan steps with 1 child
iii) Plan steps with 2 children

Plan steps with no children

A step in the plan with no dependents is a leaf of the tree. A leaf step will be either a Table Access or an Index Scan; the Rows (or Cardinality) column tells us how many rows the scan should return. Simple? Well, not quite; there is a vital piece of information missing: How many times will the step be executed? An Index Range Scan that returns 500 rows is hardly cause for alarm; but if it is going to be exectued 2 million times then we have a problem.

Looking at a step in isolation (and this applies to branch steps as well as leaf steps), you cannot tell how many times it will be executed; you need to look at its ancestors in the tree.

Watch for:
1. INDEX RANGE SCAN. This is probably the most insidious performance hole in Oracle. A Range Scan can return any number of rows; 1, 100, 100 million - the Rows column in Explain Plan often gets it wrong.
2. TABLE ACCESS FULL. Full table scans (with high row counts) when you are performing low-volume transactional SQL. Full table scans are OK for high-volume batch processes and reports.

Plan steps with 1 child
Plan steps with one child fall into three main classes:

1. Passive Operations
Operations such as VIEW and PX SEND simply pass data through unaltered to a parent step. They may be ignored.

2. Iterative Operations
Even though we cannot tell from the plan how many times the child steps will be executed, the Rows column displays the expected number of rows for all iterations, not the average per iteration. Note that this is in contrast to plan steps with 2 children (see below).

3. Active Operations
All other operations with a single child are active; they receive the row set from the child, do something to it, then pass it on to the parent.

Note: the terms Passive, Iterative, and Active are just a learning-aid; they are not used by Oracle. If you use them, don't expect anyone to understand what you are talking about.

Watch for:

1. SORT operations with high row counts. If a result set is small enough then Oracle will perform a very efficient in-memory sort. Beyond a certain size (depending on the setup of your database and session) the sort will need to page to disk; this can double the sort time or much worse. This means that execution times for small volumes will not scale proportionally to larger volumes.
2. FILTER is an unusual step in its single-child form. Look at the Filter condition in the Predicate Information section of the plan. If the condition references any table columns from subordinate steps, then the filter is applied after the child step, filtering non-matching rows as they are returned. If the condition references only bind variables and constants, then it is evaluated before the child step; if the expression evaluates False, the the child step is not executed at all.
3. PARTITION ALL and any operation containing the word ITERATOR are iterative; they execute the child step many times. Note that the Rows column shows the total number of rows expected for all iterations; not per iteration.
4. A VIEW operation is often encountered when selecting from a database view, an inline view, or simply when joining a large number of tables. It is a popular misconception that a VIEW operation will cause the result set to be materialised in TEMP space before proceeding with parent steps. This is not true; the VIEW operation appears to have no effect on the plan at all.

Plan steps with 2 children
There are two ways to interpret steps with two children:
1. Active: Do A, then do B.
2. Iterative: For each A, do B.

The difference is one of the most critical aspects of performance tuning. NESTED LOOPS, FILTER, and MERGE JOIN CARTESIAN are the only iterative operations; all others are active. Unlike the single-child iterative operations described above, the Rows measure is the expected number of rows for a single iteration of step 2.

Watch for:
1. NESTED LOOPS and FILTER operations with a large number of rows in the first child step, especially when the second child step returns more than one row or has subordinate steps; the cost of repeating the second child step so many times can be prohibitive. Exception: if the second child step is a unique index scan without a TABLE ACCESS, it can be very efficient in a NESTED LOOPS or FILTER operation.
2. MERGE JOIN CARTESIAN has a bad reputation from the days of the Rule Based Optimizer because it usually signalled a programming error, and was the cause of a performance problem. Under the Cost Based Optimizer, MERGE JOIN CARTESIAN is often used to join two unrelated tables where one table will return just a single row (or no rows). A cartesian join is only a problem if both row sources in the join have a large number of rows.
3. HASH JOIN is especially efficient when one of the sources is small (say, <10000 href="http://www.dbazine.com/oracle/or-articles/hotka1">DonHotka

Thursday, March 22, 2007

boolean and JVM

Booelan one of little cryptic primitive types in Java
Here are a few things i noticed about the same

1) depth of a boolean, is virtual-machine dependent

2) JVM spec syas that ....
Although the Java virtual machine defines a boolean type, it only provides very limited support for it. There are no Java virtual machine instructions solely dedicated to operations on boolean values. Instead, expressions in the Java programming language that operate on boolean values are compiled to use values of the Java virtual machine int data typ

3) When the Java source is compiled into bytecode, then in the bytecode booleans are treated the same way as ints. For the Java programmer this isn't relevant, because when you're programming in Java you are only working on the level of the Java language, and not on the bytecode level.
' There's a difference between the Java programming language and the bytecode - don't confuse them '

Thursday, March 1, 2007

Seriosity ... Serious problem .... Email Overload

Talking of coming back to work from a long leave ... It has mixed feelings both good and bad ... good ?? i must be joking ... but no ... thats the best thing .. enjoying ones work ...
bad .... i bet you have experienced that
  • Vacations over :(
  • PENDING emails .... phew !!
at least now there is a solution to the second problem .... seriosity
well its a good solution to the problem of overly crowded emails ....

forget about vacations on daily basis we all receive so many un-wanted mails .. what was the last time when you missed out an important email .... coz it was hidden in a big pile of mails .. not spam exactly ?? i guess not too long ...

but now we have a solution.... read what cnet has to say about it ...

just a thought ... cant we include the solution to such problem in at protocol level itself... ??
instead of letting proprietary technology step in ... ??

Tuesday, February 27, 2007

NING ... is IN ??

I happen to come across a cool web application ...
Ning http://www.ning.com/
.. and they have a v good idea ...
It allows even the most novice of web users to create their own and highly customized social network in moments.
Unlike there beta release ... a year back ... it required some knowledge but not now in this new version
its quite possible the scene of social networking may soon change ..
who knows ??

JAVA PUZZLES ... session @ sun tech days 07

JAVA PUZZLES by Raghavan N. Srinivas

This was undoubtedly the best session of the conference
Over all presentation goal was .. learning some of the quirks of programming in general and Java Programming language in particular

try getting the answer to the following code snippets
Keep in mind that i didn't try checking and running these programs .. so its quite possible that a syntax error might have crept it ... as i concentrated on concept not syntax when posting

lets start with an easy one ...

Class Example1

public static void main(String args[])

this is a good one ...

Class Example2

public Example2(Object o)




public Example2(double[] d_a)

System.out.println("double array");


public static void main(String args[])

new Example2(null);


this one is simply awesome ...

Class Example3

public void main(String[] args)


Set s = new HashSet();

for(int i=0;i<100;i++)




private static Integer randomInt()

return new Integer(new Random().nextInt());



a little tricky .. but comparatively easy ...

class Example4

public static synchronized void main (String args[])


Thread t = new Thread()


public void run()








static synchronized void pong()

again a very good one ... must try

class Example5

public static void main(String args[])
// NOte : \u000A this is a comment
Char c =0x000A;


a simple one again ...

class Example6

public static void main(String args[])



public boolean func()


return true;



return false;



Ans : Example 1
the output will be Ha169
Moral of story ...
use string con cation operator with care .. at least one of the two must be a string .. If it isn't then cast or convert

Ans : Example2
double array .. the most specific constructor is called and not the most GENERIC
We must use casting to fix it

Ans : Example3
the output will be a number close to 1
because the seed of the pseudo random number generator don't change .. as its time stamp based
may be if we put a sleep in between then the output is a number close to 100
but .. later after the session a guy came up with his laptop and ran the program in Java6 or may be java5 and the answer was a number close to 100.
when he showed it Raghavan he was surprised too said that he had checked the output on many JVMs .. ans was number close to one but strange that its 100

Ans : Example4
Wat'sthe output of above program
a) PingPong
b) PngPing
c) It varies

ans is pongping .. as its not a multi threaded program at all ... as it didn't call the start()

Ans : Example5
there will be a compile time error ,,as the \u000A in the comments will cause the comment to break up
and that in turn will give error

Ans : Example6
the ans will be false as the finally block will always be executed

There was another Example in which he tried to make a class called 'String'
and surprisingly ... it gave run time error and not compile time error