Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

December 26, 2010

Program to Shuffle a pack of card in O(n)

public class Shuffle {

public static void shuff(int[] arr) {
for(int i=0; i
int rand  = (int)(Math.random() * arr.length);
int temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
for(int i=0; i
System.out.println(" "+arr[i]);
}
}
}

December 23, 2010

MarkIT Telephonic Interview Questions

1. Difference between ArrayList and LinkedList. Why search in ArrayList is faster than in LL. When to use what

Ans : Array List is implemented as an Array and since arrayList is indexed, we just need to go to array+i th position directly. We do not have to traverse the whole list as in case of LL

2. HashCode and Equals contract

3. Difference between HashTable and HashMap
(If have inserted lakhs of objects in a HashTable and these threads simultaneously want to access a method(lets say equals() method)... one thread will accquire lock on the method, so others will have to wait. This will be a performance hit.
This is the reason why HashMap (not synchronised) came into picture. HashTable is legacy datastructure.

4. Difference between IOC and Dependency Injection

5. Difference between Error and Exception. Are all Errors Irrecoverable. (Think about NoClassDefFoundError)

December 8, 2010

java.lang.ThreadDeath

java.lang.Object
          |
java.lang.Throwable
          |
java.lang.Error
          |
java.lang.ThreadDeath (implements Serializable interface)

This Error is thrown by the Thread when the stop method with zero arguments is called.

October 31, 2010

ServletResponse : getWriter() and getOutputStream()

getWriter() : returns PrintWriter Object that is used for writing character text.

getOutputStream() : returns ServletOutputStream Object used for writing binary data in response.

October 28, 2010

Mean - Median - Mode

Mean - Median - Mode are three words which I often confuse.

Mean : Average 
  • Arithmetic Mean (AM) : (a+b+c+....+n)/n 
  •                                                               1/n
  • Geometric Mean (GM) : (a*b*c*.....*n)

  • Harmonic Mean (HM) 
     AM >= GM >= HM

Median : Middle Value
     If we have a set of values, then mean of those can be found by arranging those values in ascending/      descending order and the middle value will be median.

Mode : Most frequently occuring value. Mode may / may not be unique.

September 29, 2010

MaxEmail : Send and Receive Fax by Email

With MaxEmail, you can send and receive fax on your email account.You do not need any Fax machine or dedicated phone line for this. The Fax would come as a PDF in the email. You can also receive an audio file, which will be stored as wav file.

With this, you can also ask for a dedicated Fax number.

September 6, 2010

ECF : Eclipse Communication Framework - Installation

Got to explore ECF - Eclipse Communication Framework (Introduces the concept of communications container)
It is a framework build to integrate Communication into projects. It includes various tools like Instant Messenger, Chat Client , File Sharing, Project Sharing, Simultaneous edits to a file by various developers, Real Time Collaboration etc.
Really nice Communication Framework with plenty of features.


Installation steps :


1. Open Eclipse 3.5 or higher.
2. Open Help -> Install New Software...


3. Then click on Add button on 'Install' window and add the following details:


Name : ECF 3.3
Location : http://download.eclipse.org/rt/ecf/3.3/helios/site.p2





4. Click 'OK'.
This would start the installation. This might take several minutes.

After the installation , you are ready to communicate :)

August 26, 2010

Important points : java.util.Logger

The Logger class implements Factory patter to return logger instance.
The getLogger() method will either create a new logger instance or return a suitable(having same name as specified) existing instance. Each logger has a level associated with it, which specifies the minimum level the logger takes care of. If a  logger level is null, then its level is inherited from its parent.So, if the log level is changed for a class, the change would effect its child loggers which have the log level set as null.

Also, all methods in a logger are thread-safe.

RequestDispatcher : forward()

The argument to forward method is the name of the resource we want the request to be forwarded to. This can be a jsp file or a Servlet. In case it is a servlet, the argument should be whatever we have specified in the url-pattern for that servlet declaration in web.xml.

So, the point to be noted here is that in case we want to forward the request to some other servlet, the argument to forward method should be the url-pattern of that servlet.

Also, as we (probably) already know, the URL in the browser is not changed in case of forward. i.e. the client does not get to know that internally the request has been forwarded to some other resource.

August 2, 2010

Response : sendRedirect()

sendRedirect() method takes String as an argument. This string can start with a forward slash.

E.g.

Lets say the current URL we are accessing is : http://localhost:8080/MyApp/MyServlet/welcome.do

Now in our Servlet, we can do either :
response.sendRedirect("thanks.jsp");
OR
response.sendRedirect("/thanks.jsp");

Both of these would hit differnet URLs

In first case, i.e. response.sendRedirect("thanks.jsp");
The server will hit URL that is relative to the original URL, i.e http://localhost:8080/MyApp/MyServlet/thanks.jsp

and in second case,
the server builds the complete URL, relative to the web application itself.(instead of relative to original URL)
i.e.  http://localhost:8080/MyApp/thanks.jsp

One more thing to note here is that the argument to sendRedirect() is a String only and not an object and the URL should be something that the server can generate a complete URL from the relative. i.e. it should be relative to something (be it relative to current URL or to the web-app).
So, any argument like "www.pragyarawal.tk/welcome.jsp" would not work as the server would try to create a complete URL from it. and in this case, the server would throw an "IllegalStateException".

PrintWriter : print() vs write()

Today while reading Servlets, I came across the class PrintWriter.


I found that there we have two methods (both with various overloaded versions) : write() and print()
and I saw that print() internally calls write() only. So I was wondering that why there are different methods although they are doing the same thing. So, this seemed to be kind of redundancy to me.


Then I realized that print() is actually used as a utility method there, to which u can pass any literal value say whether it is boolean/char/int/float/double (to its overloaded versoins), but in write u have a limitaion of using only int /char array or string.So print() is just encapsulating the implementation of write() method by providing number of overlaoded method by which u can call the write().



August 1, 2010

HttpServletRequest

Some not very frequently used methods :

getServerPort():  Returns the port number to which the request was sent. (8080 in my case)
getServerName(): Name of the server (I used localhost)
getLocalAddr(): I got 0.0.0.0
getLocalPort() : This returns the port at which the request actually ends up. This is as the requests are made to the same port, but the server forwards them to different ports so that the application it can handle multiple threads.
getRemotePort(): Since the server asks for remote port, it is the client that is remote for the server. So, it returns the port number on the client on which the request was sent.

July 27, 2010

Overriding both doGet() and doPost() in a Servlet

We can override either doGet() or doPost() or both in a Servlet and based upon whether the request is GET or POST, the corresponding method will be called.

The Servlet would compile and run fine.

July 21, 2010

Eclipse Shortcuts

Adding JavaDoc comments : Alt  + Shift + J
Close All                            : Ctrl + Shift + W / Ctrl + Shift + F4
Collapse All                       : Ctrl + Shift + Numpad_Divide
Copy                                 : Ctrl + C / Ctrl + Insert
Cut                                    : Ctrl + x / Shift + del
Debug                               : F11 
Delete Line                        : Ctrl+ D
Expand All                        : Ctrl + Numpad_Multiply / Ctrl + Numpad_Add
Find next item                   : Ctrl+K
Fine previous Item            : Ctrl+ Shift + K
Format the selected text    : Ctrl+ Shift + F
Go To Line                       : Ctrl + L
Go to matching bracket     : Ctrl+ Shift + P
New                                 : Ctrl + N
Open Type                       : Ctrl + Shift + T
Open Type Hierarchy       : F4
Organize Imports              : Ctrl + Shift + O
Previous Editor                 : Ctrl + Shift + F6
Previous perspective         : Ctrl + Shift + F8
Previous view                   : Ctrl + Shift + F7
Quick Hierarchy               : Ctrl + T
Quick Outline                   : Ctrl + O
References in Workspace : Ctrl + Shift + G
Rename                            : Alt + Shift + R
Run                                  : Ctrl + F11
Show pkg hierarchy in Breadcrumb : Alt + Shift + B
Step Into                         : F5
Step Over                       : F6
Step Return                    : F7
Terminate Debugging      : Ctrl + F2
Toggle Breakpoint          : Ctrl + Shift + B
Toggle Comment            : Ctrl + Shift + C / Ctrl + 7 / Ctrl + /

July 20, 2010

Java Program without main method

When JVM finds a class, it first executes the static block and then searches for main method.
So, to avoid the JVM from searching for main method, we can execute the required code (iff possible) in static block and then exit .. before the main method is called.

Below is the code :


/**
* @Author : Pragya Rawal
*
*/
public class NoMain {


static {
System.out.println("I am in static block");
System.exit(0);
}
}

Please note that you would not be able to run this program using Eclispe IDE. You will have to run using command line

javac NoMain.java
java NoMain

you would see the output : "I am in static block"

July 11, 2010

Implementing one-to-many relationship

One-to-many relation can be implemented by using two tables.. in two ways :

e.g we have a Department table and a Student Table

1. Department :
DeptID -> Primary Key
DeptName
DeptHead

Student :
StudentID -> Primary Key
StudentName
DeptID -> Foreign Key

2. Department :
DeptID -> Primary Key
DeptName
DeptHead

Student :
StudentID -> Composite Primary Key - 1
StudentName
DeptID -> Composite Primary Key - 2

July 8, 2010

Generics and Unboxing

When using legacy (non-type safe) collections—watch out for unboxing problems! If you declare a non-generic collection, the get() methodALWAYS returns a reference of type java.lang.Object. Remember that unboxing can't convert a plain old Object to a primitive, even if that Object reference points to an Integer (or some other primitive) on the heap. Unboxing converts only from a wrapper class reference (like an Integer or a Long) to a primitive.

Generics exist only till compile time. They do not exist at run time

All your generic code is strictly for the compiler. Through a process called "type erasure," the compiler does all of its verifications on your generic code and then strips the type information out of the class bytecode. At runtime, ALL collection code—both legacy and new Java 5 code you write using generics—looks exactly like the pre-generic version of collections. None of your typing information exists at runtime. In other words, even though you WROTE

List myList = new ArrayList();


By the time the compiler is done with it, the JVM sees what it always saw before Java 5 and generics:

List myList = new ArrayList();

The compiler even inserts the casts for you—the casts you had to do to get things out of a pre-Java 5 collection.

Think of generics as strictly a compile-time protection. The compiler uses generic type information (the in the angle brackets) to make sure that your code doesn't put the wrong things into a collection, and that you do not assign what you get from a collection to the wrong reference type. But NONE of this protection exists at runtime.


This compiler warning isn't very descriptive, but the second note suggests that you recompile with -xlint:unchecked. If you do, you'll get something like this:

javac -Xlint:unchecked TestBadLegacy.java
TestBadLegacy.java:17: warning: [unchecked] unchecked call to
add(E) as a member of the raw type java.util.List
list.add(new String("42"));
^
1 warning

When you compile with the -Xlint:unchecked flag, the compiler shows you exactly which method(s) might be doing something dangerous.

July 3, 2010

Cloneable Interface

The clone( ) method generates a duplicate copy of the object on which it is called. Only classes that implement the Cloneable interface can be cloned.
The Cloneable interface defines no members. It is used to indicate that a class allows a bitwise copy of an object (that is, a clone) to be made. If you try to call clone( ) on a class that does not implement Cloneable, a CloneNotSupportedException is thrown. When a clone is made, the constructor for the object being cloned is not called. A clone is simply an exact copy of the original.

Cloning is a potentially dangerous action, because it can cause unintended side effects. For example, if the object being cloned contains a reference variable called obRef, then when the clone is made, obRef in the clone will refer to the same object as does obRef in the original. If the clone makes a change to the contents of the object referred to by obRef, then it will be changed for the original object, too. Here is another example. If an object opens an I/O stream and is then cloned, two objects will be capable of operating on the same stream. Further, if one of these objects closes the stream, the other object might still attempt to write to it, causing an error.

Because cloning can cause problems, clone( ) is declared as protected inside Object. This means that it must either be called from within a method defined by the class that implements Cloneable, or it must be explicitly overridden by that class so that it is public. 

June 23, 2010

Amazon telephonic interview ques

1. Write an efficient algo to find longest recurring substring in a string e.g. in banana, it would be 'ana'


Ans : We can use suffix trees to implement this. I will post the exact solution soon

2. Write a function to find intersection of two strings. i.e. characters common to the strings.

For this, the most efficient solution would be to use 26 bits .. one for each character and put zero in all and then wen u encounter a character, just make the corresponding bit 1. For this, we ll need to traverse both the strings only once ands the extra memory that would be required would only be 26 bits :) O(n) solution

Inefficient O(n^2) Method of finding Largest Recurring Substring in a string

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
* @author Pragya Rawal
*/
public class LargestSubstring {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String : ");
try {
String input = br.readLine();
LargestSubstring str = new LargestSubstring();
String largestSubstr = str.getLargestSubstr(input);
if (largestSubstr != null) {
System.out.println("Largest Recurring substring is : "
+ largestSubstr);
}
} catch (IOException e) {
e.printStackTrace();
}

}

public String getLargestSubstr(String input) {
if (null == input || input.length() == 0) {
System.out.println("Invalid / Empty string ...");
return null;
} else {
int length = input.length();
int subStrLen = 0;
String longestSubStr = "";
String currentStr = "";
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
int k = i;
int l = j;
while ((k < length) && (l < length) &&(input.charAt(k) == input.charAt(l)) ) {
currentStr += input.charAt(k);
k++;
l++;
subStrLen++;
}
if (longestSubStr.length() < currentStr.length()) {
longestSubStr = currentStr;
}
currentStr = "";
}

}
return longestSubStr;
}

}
}

June 22, 2010

Program(s) for finding power of a number

First, an interactive solution: (raising a to the power of b)

public double Power(double a, int b) {
if (b<=0) return 0; // we want a positive integer for the exponent
else {
double c=1;
for (int i=0; i c*=a;
}
return c;
}
}


Very easy and linear. You start from one and go on multiplying c by a so c is respectively 1, a, a^2, a^3, ... a^b.
When done, you return c. This one takes linear time.

Second, a recursive solution:

public double Power(double a, int b) {
if (b<=0) return 0;
else if (b==1) return a;
else {
return a*Power(a,b-1);
}
}


This is also an easy one. What we do here? Simple: we calculate a^b=a * a^(b-1). This is done by the recursion and takes linear time as well.

So, how can we beat these to slugs? We do this way.
Let me give you an example with b being a power of 2 (which is the easiest to understand).

Imagine you have to evaluate a^64. You could think this:

a^64 = c^32 where c=a^2
c^32 = d^16 where d=c^2
d^16 = e^8 where e=d^2
e^8 = f^4 where f=e^2
f^4 = g^2 where g=f^2
g^2 = g*g

This requires 6 operations. Using one of the two previous algorithms takes 64 operations! In fact 6=log64 (log is meant in base 2 obviously).

Now, things are different when b isn't a power of 2, but the algorithm is just a bit more complicated. Let's see an example again. We'll evaluate a^20.

a^20 = c^10 where c=a^2
c^10 = d^5 where d=c^2
d^5 = d * e^2 where e=d^2
e^2 = e*e

This requires 5 operations. Log16=4 and log32=5 so as you can see we have here 5=Ceiling(log20). This happens when b isn't a power of 2, but the cost of the entire algorithm doesn't grow that much and we can still say that it runs in logarithmic time (this is more true when b is a medium-big number).

private double Power(double a, int b) {
if (b<0) {
throw new ApplicationException("B must be a positive integer or zero");
}
if (b==0) return 1;
if (a==0) return 0;
if (b%2==0) {
return Power(a*a, b/2);
} else if (b%2==1) {
return a*Power(a*a,b/2);
}
return 0;
}


Another solution can be :
a^b = 10^(ln[10](a) * b)

Reference : http://www.osix.net/modules/article/?id=696

Details of retainAll() in Set interface

The Set interface contains a method 'retainAll()' which gives us the intersection of two sets.

Lets say we define a Set as : Set s = new HashSet();

HashSet class extends the abstract class AbstractSet , which in turn extends the abstract class AbstractCollection. The implementation of retainAll() is present in AbstractCollecction class.

This method Retains only the elements in this collection that are contained in the
specified collection (optional operation). In other words, removes
from this collection all of its elements that are not contained in the
specified collection.



This implementation iterates over this collection, checking each
element returned by the iterator in turn to see if it's contained
in the specified collection. If it's not so contained, it's removed
from this collection with the iterator's remove method.



Note that this implementation will throw an
UnsupportedOperationException if the iterator returned by the
iterator method does not implement the remove method
and this collection contains one or more elements not present in the
specified collection.

Clock Angle Problem : Amazon Ques

Clock angle problems relate two different measurements - angles and time. To answer the problem the relationship between the time shown (or an elapsed time) and the position of the hands (as given by an angle) has to be found.
A general approach to such problems is to consider the rate of change of the angle in degrees per minute. The hour hand of a normal 12-hour analogue clock turns 360 degrees in 12 hours. This is equivalent to 360 degrees in 720 minutes or 0.5 degrees per minute. The minute hand turns 360 degrees in 60 minutes or 6 degrees per minute.

Equation for the degrees on the hour hand

(0.5 degrees per minute on the hour hand) * (the time on the hour hand * 60 minutes per hour) + (0.5 degrees per minute on the minute hand) * (the time on the minute hand)

Equation for the degrees on the minute hand

(6 degrees per minute on the minute hand) * (the time on the minute hand)

'Example: The time is 5:24'
The degree on the hour hand is (0.5*5*60)+(0.5*24)=162 degrees
It could be also calculated as
Hour hand angle = total minutes / 2
In this case Hour hand angle = total minutes / 2 = ( (total hours * 60) + (total minutes) ) / 2 = ( (5 * 60) + 24 ) / 2 = 162 degrees
The degrees on the minute hand is 6*24=144 degrees

Minute handl angle = minutes * 6
Equation for the degrees between the hands

The angle between the hands can also be found using the formula cos-1(cos(5.5x)), where x=the number of minutes past noon. This will always give an angle between 0 and 180 degrees.

'Example: The time is 1:35'

1:35 is 1(60)+35=95 minutes past noon.
cos-1(cos(5.5*95))=cos-1(cos(522.5))=cos-1(-.95372)=162.5 degrees between the hands
Angle=mod(60H-11M)/2
where H= hours and M=minutes

When are hour and minute hands of a clock superimposed?

Hour and Minute hands are superimposed only when angle between them are 0. If hour and minute hands are superimposed at time h:m
0.5*60*h + 0.5*m = 6*m
m=(30/5.5)*h
for h varies from 0...11, clock hands are superimposed at 1:05.4545,2:10.90...12:00.

June 14, 2010

Class Loader methods : Why class loaders must delegate class loading

defineClass() : This method converts the array of bytes code an instance of the class.The class must be resolved before it can be used. THis is a final method. In this, an instance of class java.lang.Class is created and cached in the Class Loader so that the byte code can not change on the further requests to load the class. This method also checks that the given class name matches the class name in the byte code. Because this method is final, no custom class loader can change this behavior.


Q : Why class loaders must delegate class loading ?
As we know, a class loader must delegate the class loading(although a developer can override loadClass() and change this behavior). On one hand, if loading of system classes is not delegated, an application could provide malicious code for JDK classes and introduce a ton of problems. On the other hand, all classes at least extend java.lang.Object, and this class must be resolved, too. Thus the custom class loader has to load this class by itself, otherwise the load fails with a linkage error. These two facts imply that a custom class loader has to delegate class loading.

However,there are some loaders like the loader for web container defined in servlet specification, tries to load the class by itself before delegating.Nevertheless, some classes, such as java.*, javax.*, org.xml.sax.* and others, are delegated first to the parent.


As long as a Java developer does not deal with his or her own class loader, all of the classes are loaded by the bootstrap and system class loader, and there will never be a conflict. Thus, it seems that a class is defined only by the fully qualified class name. As soon as there are sibling class loaders -- neither a parent of the other -- a class type can be loaded multiple times with or without different byte code. The class loader also defines the visibility of a class type because any upcast checks against the class name as well as its class loaders.

To use the currency analogy, this is expressed by the fact that you can have several currencies in your wallet, but as soon as you want to use one, the cashier will check if your money is of the local currency. Still, you can carry these currencies in your pocket wherever you go, and likewise, you can carry around instances of classes even when they are unknown or not compatible in a particular class, as long as the class of the reference is compatible there. Luckily in Java, java.lang.Object is the superclass of all instances and is loaded by the BS, which is the parent of all class loaders no matter what. This means a reference of a class java.lang.Object is always compatible. I think of this as a "tunneling through" of classes from one compatible island to the next -- something that is very important in J2EE, as will be shown in a future installment.

June 13, 2010

'Extension' Class Loader

The extension framework makes use of the class-loading delegation mechanism. When the runtime environment needs to load a new class for an application, it looks for the class in the following locations, in order:
Bootstrap classes: the runtime classes in rt.jar, internationalization classes in i18n.jar, and others.
Installed extensions: classes in JAR files in the lib/ext directory of the JRE, and in the system-wide, platform-specific extension directory (such as /usr/jdk/packages/lib/ext on the SolarisTM Operating System, but note that use of this directory applies only to JavaTM 6 and later).
The class path: classes, including classes in JAR files, on paths specified by the system property java.class.path. If a JAR file on the class path has a manifest with the Class-Path attribute, JAR files specified by the Class-Path attribute will be searched also. By default, the java.class.path property's value is ., the current directory. You can change the value by using the -classpath or -cp command-line options, or setting the CLASSPATH environment variable. The command-line options override the setting of the CLASSPATH environment variable.
The precedence list tells you, for example, that the class path is searched only if a class to be loaded hasn't been found among the classes in rt.jar, i18n.jar or the installed extensions.

Unless your software instantiates its own class loaders for special purposes, you don't really need to know much more than to keep this precedence list in mind. In particular, you should be aware of any class name conflicts that might be present. For example, if you list a class on the class path, you'll get unexpected results if the runtime environment instead loads another class of the same name that it found in an installed extension.


Class Loaders - getClassLoader() method

There is a getClassLoder() method in the class java.lang.Class which tells us about the ClassLoader that loaded the class.

Below is the javaDoc for the same :

Returns the class loader for the class. Some implementations may use
null to represent the bootstrap class loader. This method will return
null in such implementations if this class was loaded by the bootstrap
class loader.

If a security manager is present, and the caller's class loader is
not null and the caller's class loader is not the same as or an ancestor of
the class loader for the class whose class loader is requested, then
this method calls the security manager's checkPermission
method with a RuntimePermission("getClassLoader")
permission to ensure it's ok to access the class loader for the class.

If this object
represents a primitive type or void, null is returned.

@return the class loader that loaded the class or interface
represented by this object.
@throws SecurityException
if a security manager exists and its
checkPermission method denies
access to the class loader for the class.
@see java.lang.ClassLoader
@see SecurityManager#checkPermission
@see java.lang.RuntimePermission

June 11, 2010

Around advice vs Before/ After Advice

MethodInterceptor provides the ability to do both berfore and after advices in one advice object:
public interface MethodInterceptor extends Interceptor {
Object invoke(MethodInvocation invocation) throws Throwable;
}
There are two important differences between the MethodInterceptor interface
and the previous two types of advice. First, the MethodInterceptor implementation
controls whether the target method is actually invoked. Invoking the target
method is done by calling MethodInvocation.proceed(). This is in contrast to
MethodBeforeAdvice, where the target method is always called unless you throw
an exception.
Second, MethodInterceptor gives you control over what object is returned. This
means you can return a completely different object than the one returned by proceed().
Remember, with AfterReturningAdvice you had access to the object being returned, but you could not return a different object. While MethodInterceptor
provides this added flexibility, you should use caution when returning a different
object than the one returned by the target method and only do so when necessary.

Advice in Spring AOP

Advice contains the logic of your aspect. So,when you create an advice object, you are writing the code that implements the
cross-cutting functionality. Also, remember that Spring’s joinpoint model is built
around method interception. This means that the Spring advice you write will be
woven into your application at different points around a method’s invocation.
Because there are several points during the execution of a method that Spring
can weave in advice, there are several different advice types.

Advice type Interface Description
Around org.aopalliance.intercept.MethodInterceptor Intercepts calls to the target
method
Before org.springframework.aop.BeforeAdvice Called before the target
method is invoked
After org.springframework.aop.AfterReturningAdvice Called after the target
method returns
Throws org.springframework.aop.ThrowsAdvice Called when target
method throws an
exception

Spring AOP

Spring does not create a proxied object until that proxied bean is needed by the
application. If you are using an ApplicationContext, the proxied objects will be
created when it loads all of the beans from the BeanFactory. Because Spring creates
proxies at runtime, you do not need a special compiler to use Spring’s AOP.
Spring generates proxied classes in two ways. If your target object implements
an interface(s) that exposes the required methods, Spring will use the JDK’s
java.lang.reflect.Proxy class. This class allows Spring to dynamically generate
a new class that implements the necessary interfaces, weave in any advice, and
proxy any calls to these interfaces to your target class.
If your target class does not implement an interface, Spring uses the CGLIB1
library to generate a subclass to your target class. When creating this subclass,
Spring weaves in advice and delegates calls to the subclass to your target class.
When using this type of proxy generation, you need to deploy all of the JAR files
in the lib/cglib directory of your Spring distribution with your application.
There are two important things to take note of when using this approach:
■ Creating a proxy with interfaces is favored over proxying classes, since this
leads to a more loosely coupled application. The ability to proxy classes is
provided so that legacy or third-party classes that do not implement interfaces
can still be advised. This approach should be taken as the exception,
not the rule.
■ Methods marked as final cannot be advised. Remember, Spring generates
a subclass to your target class. Any method that needs to be advised is overridden
and advice is woven in. This is not possible with final methods.

Spring implements AOP Alliance interfaces
The AOP Alliance is a joint project between several parties interested in implementing
AOP in Java. The AOP Alliance shares the same belief as Spring that AOP
can provide cleaner and easier solutions for Java enterprise applications than what
is currently offered by EJB. Their goal is to standardize Java’s AOP interface to provide
interoperability between various Java AOP implementations. This means that
AOP advice that implements their interfaces (as do some of Spring’s implementations)
will be reusable in any other AOP Alliance–compatible framework.
Spring only supports method joinpoints
As mentioned earlier, multiple joinpoint models are available through various
AOP implementations. Spring only supports method joinpoints. This is in contrast
to some other AOP frameworks, such as AspectJ and JBoss, which provide
field joinpoints as well. This prevents you from creating very fine-grained advice,
such as intercepting updates to an object’s field.
However, as Spring focuses on providing a framework for implementing J2EE
services, method interception should suit most, if not all, of your needs. Plus,
Spring’s philosophy is that field interception violates encapsulation. A fundamental
object-oriented concept is that objects initiate operations on themselves
and other objects through method calls. Having advice fired on field modification
as opposed to method invocation arguably violates this concept.

June 9, 2010

More about Internet Servers

POP3 is by far the most common type of incoming e‑mail server for personal e‑mail accounts. And SMTP is the only type of outgoing e‑mail server that works with Windows Mail, so you normally don’t even need to check the outgoing server type with your e‑mail provider. Practically all personal e‑mail accounts—with the exception of web-based e‑mail—use an SMTP server for outgoing e‑mail.

E‑mail server addresses usually have the same format. Most ISPs (named “myisp” in this example) have server addresses like this:

Incoming server: pop.myisp.com (or imap.myisp.com, if they use an IMAP server)

Outgoing server: smtp.myisp.com

You can usually substitute the name of your ISP in place of myisp in the example above. If this doesn’t work, check with your ISP. Questions about e‑mail server addresses are among the most common inquiries e‑mail providers get, so they usually have this information posted in the support section of their websites.

Here are server addresses for some of the most popular e‑mail services:

Yahoo!: pop.mail.yahoo.com (incoming) and smtp.mail.yahoo.com (outgoing)

AOL: imap.aol.com (incoming) and smtp.aol.com (outgoing)

Gmail: pop.gmail.com (incoming) and smtp.gmail.com (outgoing)

Finally, you must know whether your outgoing e‑mail server requires authentication, since there is a check box for this when you set up a new e‑mail account in Windows Mail. If you can’t find out the answer from your e‑mail provider, try sending a test message with the check box selected and another one with the check box cleared, to see which works.

E‑mail server types

Windows Mail supports three types of e‑mail servers.

Post Office Protocol 3 (POP3) servers. Most e‑mail services and ISPs use this type of server, especially for personal e‑mail accounts. They hold incoming e‑mail messages until you check your e‑mail, at which point they're transferred to your computer. Messages are typically deleted from the server when you check your e‑mail.

Internet Message Access Protocol (IMAP) servers. These servers let you work with e‑mail messages without downloading them to your computer first. You can preview, delete, and organize messages directly on the e‑mail server. Copies are stored on the server until you delete them. IMAP is commonly used for business e‑mail accounts.

Simple Mail Transfer Protocol (SMTP) servers. This outgoing mail server handles the sending of your e‑mail messages to the Internet. An SMTP server handles only the outgoing e‑mail, and is used in conjunction with a POP3 or IMAP incoming e‑mail server.

June 7, 2010

Simple java Program for sending mails

package com.abc;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendingEmail {
public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
{
boolean debug = false;

//Set the host smtp address
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = new Properties();
// props.put("mail.smtp.host", "smtp.mta"); // MS smtp
props.put("mail.smtp.host", "smtp.gmail.com"); // airtel smtp
props.put("mail.smtp.starttls.enable","true");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);

// create a message
Message msg = new MimeMessage(session);

// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);

InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);


// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");

// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
}

Main Class :


package com.abc;

import javax.mail.*;

public class SendMailMain {

/**
* @param args
*/
public static void main(String[] args) {

SendingEmail sm = new SendingEmail();
String[] recep = {"zzzz.yyyy@yahoo.co.in"};
try{
sm.postMail(recep, "HI", "From ABC", "mmmm.nnnn@gmail.com");
}catch (MessagingException e) {
e.printStackTrace();
}
}

}


The idea behind this is that some SMTP servers (like gmail smtp) require authentication. So, you need to provide your credentials for them.
But for some SMTP servers (e.g. smtp.mta ) are open for all where in anyone can send mail from any id to any id, without any authentication required.


So, for the servers which requrie authentication,
u need to add the below code :


static class PopupAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("UserName", "Password");
}
}

This is extending abstract Authenticator class and overriding the getPasswordAuthentication() method.


Refer : http://forums.sun.com/thread.jspa?threadID=345884

May 22, 2010

Spring : Good Points

1. IF you are using DI using constructor .. u have to make the constructor as public ... private / protected / default wont work

May 18, 2010

ClassLoader Documentaion

A class loader is an object that is responsible for loading classes. The
* class ClassLoader is an abstract class. Given the * href="#name">binary name of a class, a class loader should attempt to
* locate or generate data that constitutes a definition for the class. A
* typical strategy is to transform the name into a file name and then read a
* "class file" of that name from a file system.
*
*

Every {@link Class Class} object contains a {@link
* Class#getClassLoader() reference} to the ClassLoader that defined
* it.
*
*

Class objects for array classes are not created by class
* loaders, but are created automatically as required by the Java runtime.
* The class loader for an array class, as returned by {@link
* Class#getClassLoader()} is the same as the class loader for its element
* type; if the element type is a primitive type, then the array class has no
* class loader.
*
*

Applications implement subclasses of ClassLoader in order to
* extend the manner in which the Java virtual machine dynamically loads
* classes.
*
*

Class loaders may typically be used by security managers to indicate
* security domains.

May 13, 2010

Life cycle of a bean with Bean Factory Container and ApplicationContext Container

1 The container finds the bean’s definition and instantiates the bean.
2 Using 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.

At this point, the bean is ready to be used by an application and will remain in the
bean factory until it is no longer needed. It is removed from the bean factory in
two ways.

1 If the bean implements the DisposableBean interface, the destroy()
method is called.
2 If a custom destroy-method is specified, it will be called.

The life cycle of a bean within a Spring application context differs only slightly
from that of a bean within a bean factory

The only difference here is that if the bean implements the ApplicationContext-
Aware interface, the setApplicationContext() method is called.

Spring : Difference between BeanFactory and ApplicationContext

ApplicationContext interface extends the BeanFactory interface.

A big difference between an application context and a bean factory is how
singleton beans are loaded. A bean factory lazily loads all beans, deferring bean
creation until the getBean() method is called. An application context is a bit
smarter and preloads all singleton beans upon context startup. By preloading
singleton beans, you ensure that they will be ready to use when needed—your
application won’t have to wait for them to be created.

DomParserExample

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DomParserExample {

//No generics
List myEmpls;
Document dom;


public DomParserExample(){
//create a list to hold the employee objects
myEmpls = new ArrayList();
}

public void runExample() {

//parse the xml file and get the dom object
parseXmlFile();

//get each employee element and create a Employee object
parseDocument();

//Iterate through the list and print the data
/*printData();
*/
}


private void parseXmlFile(){
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

try {

//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();

//parse using builder to get DOM representation of the XML file
//dom = db.parse("BOVarswaps.xml");
dom = db.parse("BOPostTrade.xml");


}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch(SAXException se) {
se.printStackTrace();
}catch(IOException ioe) {
ioe.printStackTrace();
}
}


private void parseDocument(){
//get the root elememt
Element docEle = dom.getDocumentElement();

//get a nodelist of elements
NodeList nl = docEle.getElementsByTagName("class");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {

//get the employee element
Element el = (Element)nl.item(i);

//get the Employee object
System.out.println("*"+el.getAttribute("name"));

NodeList propertyList = el.getElementsByTagName("property");
if(propertyList != null && propertyList.getLength() > 0 ){
for(int ii = 0 ; ii < propertyList.getLength();ii++){
Element inner = (Element)propertyList.item(ii);
System.out.println(" * "+inner.getAttribute("name"));
}

}
System.out.println("");
}
}
}

/*private String getClassName(el){

}
private String getPropertyName (){

}*/
/**
* I take an employee element and read the values in, create
* an Employee object and return it
* @param empEl
* @return
*/
/*private Employee getEmployee(Element empEl) {

//for each element get text or int values of
//name ,id, age and name
String name = getTextValue(empEl,"Name");
int id = getIntValue(empEl,"Id");
int age = getIntValue(empEl,"Age");

String type = empEl.getAttribute("type");

//Create a new Employee with the value read from the xml nodes
Employee e = new Employee(name,id,age,type);

return e;
}

*/
/**
* I take a xml element and the tag name, look for the tag and get
* the text content
* i.e for John xml snippet if
* the Element points to employee node and tagName is name I will return John
* @param ele
* @param tagName
* @return
*/
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}

return textVal;
}


/**
* Calls getTextValue and returns a int value
* @param ele
* @param tagName
* @return
*/
private int getIntValue(Element ele, String tagName) {
//in production application you would catch the exception
return Integer.parseInt(getTextValue(ele,tagName));
}

/**
* Iterate through the list and print the
* content to console
*/
private void printData(){

System.out.println("No of Employees '" + myEmpls.size() + "'.");

Iterator it = myEmpls.iterator();
while(it.hasNext()) {
System.out.println(it.next().toString());
}
}


public static void main(String[] args){
//create an instance
DomParserExample dpe = new DomParserExample();

//call run example
dpe.runExample();
}

}

Sample XML :




Seagull
3674
34


Robin
3675
25


Crow
3676
28

Very Simple XML DOMParser

Sample XML :












































Java Code :


import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class MyDOMParser {

Document dom;
public void runExample() {

//parse the xml file and get the dom object
parseXmlFile();

//get each element
parseDocument();


}


private void parseXmlFile(){
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

try {

//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();

//parse using builder to get DOM representation of the XML file
//dom = db.parse("BOVarswaps.xml");
dom = db.parse("BOPostTrade.xml");


}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch(SAXException se) {
se.printStackTrace();
}catch(IOException ioe) {
ioe.printStackTrace();
}
}


private void parseDocument(){
//get the root elememt
Element docEle = dom.getDocumentElement();

//get a nodelist of elements
NodeList nl = docEle.getElementsByTagName("class");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {

//get the employee element
Element el = (Element)nl.item(i);

//get the Employee object
System.out.println("*"+el.getAttribute("name"));

NodeList propertyList = el.getElementsByTagName("property");
if(propertyList != null && propertyList.getLength() > 0 ){
for(int ii = 0 ; ii < propertyList.getLength();ii++){
Element inner = (Element)propertyList.item(ii);
System.out.println(" * "+inner.getAttribute("name"));
}

}
System.out.println("");
}
}
}


public static void main(String[] args){
//create an instance
MyDOMParser dpe = new MyDOMParser();

//call run example
dpe.runExample();
}

}

http://www.totheriver.com/learn/xml/xmltutorial.html#6

May 6, 2010

What the difference between data hiding and abstraction?

Data hiding means, hiding some essential information or as you say a data from other end user or users and abstraction in simple language means hiding complex features and showing only essential features of any object.

In data hiding we hide the information by using access specifier private, public and protected..so it means we are hiding info from outside the world.But in abstrastion we express only essential feature..
Eg: Three set of customers are going to buy a bike First one wants information about the style. Second one wants about the milage. Third one wants the cost and brand of the bike.So the salesperson explains about the product which customer needs what. So he hiding some information and giving the revelant information.

May 5, 2010

Features of Hibernate

* Hibernate 3.0 provides three full-featured query facilities: Hibernate Query Language, the newly enhanced Hibernate Criteria Query API, and enhanced support for queries expressed in the native SQL dialect of the database.

* Filters for working with temporal (historical), regional or permissioned data.

* Enhanced Criteria query API: with full support for projection/aggregation and subselects.

* Runtime performance monitoring: via JMX or local Java API, including a second-level cache browser.

* Eclipse support, including a suite of Eclipse plug-ins for working with Hibernate 3.0, including mapping editor, interactive query prototyping, schema reverse engineering tool.

* Hibernate is Free under LGPL: Hibernate can be used to develop/package and distribute the applications for free.

* Hibernate is Scalable: Hibernate is very performant and due to its dual-layer architecture can be used in the clustered environments.

* Less Development Time: Hibernate reduces the development timings as it supports inheritance, polymorphism, composition and the Java Collection framework.

* Automatic Key Generation: Hibernate supports the automatic generation of primary key for your.

* JDK 1.5 Enhancements: . While Hibernate3 still runs perfectly with JDK 1.2, Hibernate3 will make use of some new JDK features. JSR 175 annotations, for example, are a perfect fit for Hibernate metadata

* EJB3-style persistence operations: EJB3 defines the create() and merge() operations, which are slightly different to Hibernate's saveOrUpdate() and saveOrUpdateCopy() operations. Hibernate3 will support all four operations as methods of the Session interface.

* Hibernate XML binding enables data to be represented as XML and POJOs interchangeably.

* The EJB3 draft specification support for POJO persistence and annotations.

April 29, 2010

Singleton Class (very Good one)

public class Singleton {
private static Singleton instance;
//public static int i =1 ;

private Singleton() {
}

public static Singleton getInstance() { // Using Double Checked Locking method
if (instance == null) {
synchronized (instance) {
if (instance == null) {
instance = new Singleton();
}
}
}
//i++;
return instance;
}

protected Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
}

http://www.roseindia.net/javatutorials/J2EE_singleton_pattern.shtml


We need to override clone() method as well so no one should create a new Instance using clone.

After this even, one can create multiple instances of a Sing class in a Clustered Enviroonment coz in a clustered enviro, we have a heap for each node. So, even if we create an instance, a new instance can be created on other node.
How to avoid this : we'll talk in next post :)

Depth First Polymorphism - Java

public class DepthFirstPoly {

public void Test(Object obj){
System.out.println("Obj");
}
public void Test(String obj){
System.out.println("String");
}
/*public void Test(StringBuffer obj){
System.out.println("String");
}*/
public static void main(String[] args) {
//System.out.println();
DepthFirstPoly dfs = new DepthFirstPoly();
dfs.Test(null);

}

}


Output :
String

April 23, 2010

Primitive Assignments - V. Important

The equal ( = ) sign is used for assigning a value to a variable, and it's cleverly named the assignment operator. There are actually 12 assignment operators, but only the five most commonly used

You can assign a primitive variable using a literal or the result of an expression.

Take a look at the following:

int x = 7; // literal assignment
int y = x + 2; // assignment with an expression
// (including a literal)
int z = x * y; // assignment with an expression

The most important point to remember is that a literal integer (such as 7) is always implicitly an int and an int is a 32-bit value. No big deal if you're assigning a value to an int or a long variable, but what if you're assigning to a byte variable? After all, a byte-sized holder can't hold as many bits as an int-sized holder. Here's where it gets weird. The following is legal,

byte b = 27;

but only because the compiler automatically narrows the literal value to a byte. In other words, the compiler puts in the cast. The preceding code is identical to the following:

byte b = (byte) 27; // Explicitly cast the int literal to a byte

It looks as though the compiler gives you a break, and lets you take a shortcut with assignments to integer variables smaller than an int. (Everything we're saying about byte applies equally to char and short, both of which are smaller than an int.)

We know that a literal integer is always an int, but more importantly, the result of an expression involving anything int-sized or smaller is always an int. In other words, add two bytes together and you'll get an int—even if those two bytes are tiny. Multiply an int and a short and you'll get an int. Divide a short by a byte and you'll get…an int. OK, now we're at the weird part. Check this out:

byte b = 3; //No problem, 3 fits in a byte
byte c = 8; // No problem, 8 fits in a byte
byte d = b + c; // Should be no problem, sum of the two bytes
// fits in a byte

The last line won't compile! You'll get an error something like this:

TestBytes.java:5: possible loss of precision
found : int
required: byte
byte c = a + b;
^

We tried to assign the sum of two bytes to a byte variable, the result of which (11) was definitely small enough to fit into a byte, but the compiler didn't care. It knew the rule about int-or-smaller expressions always resulting in an int. It would have compiled if we'd done the explicit cast:

byte c = (byte) (a + b);

April 11, 2010

Futures vs Forwards

FUTURES are simply Fixed Date Forwards

Forward and Futures Contracts are essentially the same, the differences being largely in conventions regarding the quotation of prices. Since we are familiar with Forward Contracts, the similarities/ differences of the Futures contracts are set off against the features of Forward Contracts, as below:

Forwards

Futures

1. Traded in the OTC (over the counter) or Interbank market, with buyer/ seller bearing mutual counterparty risk.

1. Traded on Exchanges, with the Exchange bearing counterparty risk with respect to the buyer/ seller.

2. Can have any maturity date, customized to the requirement of the Buyer.

2. Has Fixed maturity dates. In the case of Dollar-Rupee Futures, the maturity dates will be the last working day of a calendar month, going out to 12 months.

3. Can be for any amount, customized to the requirement of the Buyer.

3. Lot Size is fixed. Transactions can be in multiples of the fixed Lot Size, not in broken/ odd amounts.

4. The Forward Rate = Spot Rate + Forward Difference, where Forward Difference <> 0.

4. The Futures Rate = Spot Rate + Forward Difference, where Forward Difference <> 0

5. In case of USD-INR, the Forward Rate is quoted as X INR per 1 USD. For example, the current Forward Rate for 31-Aug-08 is 42.3350 INR per USD 1.

5. Some clarity is needed on this, but our understanding, so far, is that for Dollar-Rupee futures, the Futures Rate will also be quoted in the same manner as the Forward Rate.

6. No margin requirement

6. Margin required

7. Avowedly non-speculative for Corporates in the Indian context, because trades (hedges) can be done only against and to the extent of actual exposures.

7. Fully speculative, because the contracts will be cash-settled on expiry. No delivery of Dollars can either be taken or given.

8. Account for, by far, the lion's share of the market volume. Estimates range from 80-95%.

8. Accounts for a small part of the total market volume, with estimates ranging from 5-20%.

9. Client (corporate) trades/ hedges with a bank.

9. Client will trade/ hedge with a broker who is a member of the exchange.

In the proposed Futures market, any resident Indian can buy/ sell Dollar-Rupee Futures (lot size USD 1000) upto a maximum of USD 5 million with a broker, at rates similar to the currently quoted Forward Rates. The Contract may be squared off at or before maturity, the difference in rates being settled in cash.


http://www.kshitij.com/inr/forwards&futures.shtml

March 30, 2010

Complied vs Interpreted languages

Programming languages generally fall into one of two categories: Compiled or Interpreted. With a compiled language, code you enter is reduced to a set of machine-specific instructions before being saved as an executable file. With interpreted languages, the code is saved in the same format that you entered. Compiled programs generally run faster than interpreted ones because interpreted programs must be reduced to machine instructions at runtime. However, with an interpreted language you can do things that cannot be done in a compiled language. For example, interpreted programs can modify themselves by adding or changing functions at runtime. It is also usually easier to develop applications in an interpreted environment because you don't have to recompile your application each time you want to test a small section.

March 26, 2010

Puzzle : The Elder Twin

One day Kerry celebrated her birthday. Two days later her older twin brother, Terry, celebrated his birthday. How come?

Sol : At the time she went into labor, the mother of the twins was traveling by boat. The older twin, Terry, was born first early on March 1st. The boat then crossed the international date line (or anytime zone line) and Kerry, the younger twin, was born on February the 28th. In a leap year the younger twin celebrates her birthday two days before her older brother..

http://www.bellaonline.com/articles/art39652.asp

March 24, 2010

Why can’t variable names start with numbers?

Because then a string of digits would be a valid identifier as well as a valid number.

int 17 = 497;
int 42 = 6 * 9;
String 1111 = "Totally text";

int 2d = 42;
double a = 2d;
What is a? 2.0? or 42?

Hint, if you don't get it, d after a number means the number before it is a double literal

http://stackoverflow.com/questions/342152/why-cant-variable-names-start-with-numbers

January 21, 2010

Correlated SubQuery -- Find Nth maximum value in SQL Server

Use Pubs
Go

Create table Employee
(
Eid int,
Name varchar(10),
Salary money
)
Go

Insert into Employee values (1,'harry',3500)
Insert into Employee values (2,'jack',2500)
Insert into Employee values (3,'john',2500)
Insert into Employee values (4,'xavier',5500)
Insert into Employee values (5,'steven',7500)
Insert into Employee values (6,'susana',2400)
Go
A simple query that can find the employee with the maximum salary, would be:

Select * from Employee where salary = (Select max(Salary) from Employee)
How does this query work?

The SQL Engine evaluates the inner most query and then moves to the next level (outer query). So, in the above example inner query i.e. Select max(Salary) from Employee is evaluated first. This query will return a value of 7500 (based on the sample data shown as above). This value is substituted in the outer query and it is evaluated as:

Select * from Employee where salary = (7500)
Returns:

Eid Name Salary
5 steven 7500
If the same syntax is applied to find out the 2nd or 3rd or 4th level of salary, the query would become bit complex to understand. See the example below:

Select * from Employee where salary =
(Select max(Salary) from Employee where salary
< (Select max(Salary) from Employee where Salary < (Select max(Salary) from Employee where Salary <…………………………………………… N The above query would go on and on, depending on the level of salary that is to be determined. As mentioned earlier, the SQL Engine evaluates the inner most query first and moves the next outer level. One wouldn’t want to write such a big query just to find out this simple information. The same result can be achieved with a simple syntax and easily understandable logic, by using a CORRELATED SUBQUERY.
 As a "Rule of Thumb" keep these points in mind, when you use a correlated sub-query :
1) Correlated sub-query is a performance overhead to the database server and so, you have to use it only if it is required
2) Avoid using Correlated subquery on large tables, as the inner query is evaluated for each row of the outer query Having said that, let’s look at the query that captures the Nth maximum value: Select * From Employee E1 Where (N-1) = (Select Count(Distinct(E2.Salary)) From Employee E2 Where E2.Salary > E1.Salary)
(Where N is the level of Salary to be determined)

In the above example, the inner query uses a value of the outer query in its filter condition meaning; the inner query cannot be evaluated before evaluating the outer query. So each row in the outer query is evaluated first and the inner query is run for that row. Let’s look into the background process of this query, by substituting a value for N i.e. 4,(Idea is to find the 4th maximum salary):

Select * From Employee E1 Where
(4-1) = (Select Count(Distinct(E2.Salary)) From Employee E2 Where
E2.Salary > E1.Salary)
Since the outer query’s value is referred in the inner query, the operation is done row-by-row. Based on the sample data as shown above, the process starts with the following record:

Employee E1
----------------------------------
Eid Name Salary
1 harry 3500
The salary of this record is substituted in the inner query and evaluated as:

Select Count(Distinct(E2.Salary)) From Employee E2
Where E2.Salary > 3500
Above query returns 2 (as there are only 2 salaries greater than 3500). This value is substituted in the outer query and will be evaluated as:

Select * From Employee E1 Where (4-1) = (2)
The "where" condition evaluates to FALSE and so, this record is NOT fetched in the result.

Next the SQL Engine processes the 2nd record which is:

Employee E1
----------------------------------
Eid Name Salary
2 jack 2500
Now the inner query is evaluated as:

Select Count(Distinct(E2.Salary)) From Employee E2
Where E2.Salary > 2500
This query returns a value of 3 (as there are 3 salaries greater than 2500). The value is substituted in the outer query and evaluated as:

Select * From Employee E1 Where (4-1) = (3)
The "where" condition evaluates to TRUE and so, this record IS fetched in the result. This operation continues for all the remaining records. Finally the result shows these 2 records:

Eid Name Salary
2 jack 2500
3 john 2500
The above query works in the same manner in Oracle and Sybase as well. Applying the same logic, to find out the first maximum salary the query would be:

Select * From Employee E1 Where
(1-1) = (Select Count(Distinct(E2.Salary)) From Employee E2 Where
E2.Salary > E1.Salary)
If you are able to understand this functionality, you can workout various other queries in the same manner. The bottom line is, the query should be efficient and NOT resource hungry.

http://www.sqlteam.com/article/find-nth-maximum-value-in-sql-server

Important SQL Queries

Deleting only dupes from a table

DELETE FROM mytable
WHERE EXISTS
( SELECT name1, age1, MIN(id) as cf_prog
FROM mytable TAB02
WHERE ( mytable.name1 = TAB02.name1 ) AND
( mytable.age1 = TAB02.age1 )
GROUP BY name1, age1
HAVING ( count(*) > 1 ) AND
( mytable.id <> cf_prog ) )

Selecting Dupes from a table

select cargo_id, dest_id
from routing t1
where
( select count(*)
from routing t2
where t2.dest_id = t1.dest_id ) > 1


Finding the Nth maximum from a table

select *
from yourTable X
where n-1 =
(select count(*)
from yourTable
where salary > X.salary)
order by salary desc

Selecting the top n rows from a table


select *
from employee X
where n >
(select count(*)
from employee
where dept = X.dept
and salary > X.salary)
order by dept, salary desc

Where vs Having

SQL Standard says that WHERE restricts the result set before returning rows and HAVING restricts the result set after bringing all the rows. So WHERE is faster. On SQL Standard compliant DBMSs in this regard, only use HAVING where you cannot put the condition on a WHERE (like computed columns in some RDBMSs.)
HAVING clauses should be used to apply conditions on group functions, otherwise they can be mvoed into the WHERE condition.

http://stackoverflow.com/questions/328636/which-sql-statement-is-faster-having-vs-where

January 20, 2010

SQL - Cursors

SQL Server is very good at handling sets of data. For example, you can use a single UPDATE statement to update many rows of data. There are times when you want to loop through a series of rows a perform processing for each row. In this case you can use a cursor.

Please note that cursors are the SLOWEST way to access data inside SQL Server. The should only be used when you truly need to access one row at a time. The only reason I can think of for that is to call a stored procedure on each row. In the Cursor Performance article I discovered that cursors are over thirty times slower than set based alternatives.
The basic syntax of a cursor is:

DECLARE @AuthorID char(11)

DECLARE c1 CURSOR READ_ONLY
FOR
SELECT au_id
FROM authors

OPEN c1

FETCH NEXT FROM c1
INTO @AuthorID

WHILE @@FETCH_STATUS = 0
BEGIN

PRINT @AuthorID

FETCH NEXT FROM c1
INTO @AuthorID

END

CLOSE c1
DEALLOCATE c1
The DECLARE CURSOR statement defines the SELECT statement that forms the basis of the cursor. You can do just about anything here that you can do in a SELECT statement. The OPEN statement statement executes the SELECT statement and populates the result set. The FETCH statement returns a row from the result set into the variable. You can select multiple columns and return them into multiple variables. The variable @@FETCH_STATUS is used to determine if there are any more rows. It will contain 0 as long as there are more rows. We use a WHILE loop to move through each row of the result set.

The READ_ONLY clause is important in the code sample above. That dramatically improves the performance of the cursor.

In this example, I just print the contents of the variable. You can execute any type of statement you wish here. In a recent script I wrote I used a cursor to move through the rows in a table and call a stored procedure for each row passing it the primary key. Given that cursors are not very fast and calling a stored procedure for each row in a table is also very slow, my script was a resource hog. However, the stored procedure I was calling was written by the software vendor and was a very easy solution to my problem. In this case, I might have something like this:

EXEC spUpdateAuthor (@AuthorID)
instead of my Print statement. The CLOSE statement releases the row set and the DEALLOCATE statement releases the resources associated with a cursor.

If you are going to update the rows as you go through them, you can use the UPDATE clause when you declare a cursor. You'll also have to remove the READ_ONLY clause from above.

DECLARE c1 CURSOR FOR
SELECT au_id, au_lname
FROM authors
FOR UPDATE OF au_lname
You can code your UPDATE statement to update the current row in the cursor like this

UPDATE authors
SET au_lname = UPPER(Smith)
WHERE CURRENT OF c1

http://www.sqlteam.com/article/cursors-an-overview

SQL interview Questions

Q: 1. What are two methods of retrieving SQL?
A: SELECT statement, cursors

Master list of Java interview questions - 115 questions

What is the difference between procedural and object-oriented programs?
 a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code. b) In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code.

What are Encapsulation, Inheritance and Polymorphism?
 Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse.
Inheritance is the process by which one object acquires the properties of another object.
Polymorphism is the feature that allows one interface to be used for general class actions.

What is the difference between Assignment and Initialization?
Assignment can be done as many times as desired whereas initialization can be done only once.

What is OOPs?
 Object oriented programming organizes a program around its data, i. e. , objects and a set of well defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.

What are Class, Constructor and Primitive data types?
Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform. Constructor is a special kind of method that determines how an object is initialized when created. Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean, char.

What is an Object and how do you allocate memory to it?
Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. When an object is created using new operator, memory is allocated to it.

What is the difference between constructor and method?
 Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.

What are methods and how are they defined?
Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes. Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A method’s signature is a combination of the first three parts mentioned above.
What is the use of bin and lib in JDK?- Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.

What is casting?
Casting is used to convert the value of one type to another.

How many ways can an argument be passed to a subroutine and explain them?-
An argument can be passed in two ways. They are passing by value and passing by reference. Passing by value: This method copies the value of an argument into the formal parameter of the subroutine. Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.

What is the difference between an argument and a parameter?- While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.

What are different types of access modifiers?- public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private can’t be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package.

What is final, finalize() and finally?- final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can’t be overridden. A final variable can’t change from its initialized value. finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection. finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.

What is UNICODE?- Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other.

What is Garbage Collection and how to call it explicitly?-
When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.

What is finalize() method?- finalize () method is used just before an object is destroyed and can be called just prior to garbage collection.

What are Transient and Volatile Modifiers?
 Transient: The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized.
Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

What is method overloading and method overriding?- Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.

What is difference between overloading and overriding?
a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method. b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass. c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass. d) Overloading must have different method signatures whereas overriding must have same signature.


http://www.techinterviews.com/master-list-of-java-interview-questions

Queue Interface

Queue Interface
A Queue is designed to hold a list of "to-dos," or things to be processed in some way. Although other orders are possible, queues are typically thought of as FIFO (first-in, first-out). Queues support all of the standard Collection methods and they also add methods to add and subtract elements and review queue elements.

PriorityQueue This class is new with Java 5. Since the LinkedList class has been enhanced to implement the Queue interface, basic queues can be handled with a LinkedList. The purpose of a PriorityQueue is to create a "priority-in, priority out" queue as opposed to a typical FIFO queue. A PriorityQueue's elements are ordered either by natural ordering (in which case the elements that are sorted first will be accessed first) or according to a Comparator. In either case, the elements' ordering represents their relative priority.

Map Interface

Map Interface
A Map cares about unique identifiers. You map a unique key (the ID) to a specific value, where both the key and the value are, of course, objects. You're probably quite familiar with Maps since many languages support data structures that use a key/value or name/value pair. The Map implementations let you do things like search for a value based on the key, ask for a collection of just the values, or ask for a collection of just the keys. Like Sets, Maps rely on the equals() method to determine whether two keys are the same or different.

HashMap The HashMap gives you an unsorted, unordered Map. When you need a Map and you don't care about the order (when you iterate through it), then HashMap is the way to go; the other maps add a little more overhead. Where the keys land in the Map is based on the key's hashcode, so, like HashSet, the more efficient your hashcode() implementation, the better access performance you'll get. HashMap allows one null key and multiple null values in a collection.


Hashtable Like Vector, Hashtable has existed from prehistoric Java times. For fun, don't forget to note the naming inconsistency: HashMap vs. Hashtable. Where's the capitalization of t?
Anyway, just as Vector is a synchronized counterpart to the sleeker, more modern ArrayList, Hashtable is the synchronized counterpart to HashMap. Remember that you don't synchronize a class, so when we say that Vector and Hashtable are synchronized, we just mean that the key methods of the class are synchronized. Another difference, though, is that while HashMap lets you have null values as well as one null key, a Hashtable doesn't let you have anything that's null.

LinkedHashMap Like its Set counterpart, LinkedHashSet, the LinkedHash-Map collection maintains insertion order (or, optionally, access order). Although it will be somewhat slower than HashMap for adding and removing elements, you can expect faster iteration with a LinkedHashMap.

TreeMap You can probably guess by now that a TreeMap is a sorted Map. And you already know that by default, this means "sorted by the natural order of the elements." Like TreeSet, TreeMap lets you define a custom sort order (via a Comparable or Comparator) when you construct a TreeMap, that specifies how the elements should be compared to one another when they're being ordered.

Collection - Set

Set Interface
A Set cares about uniqueness—it doesn't allow duplicates. Your good friend the equals() method determines whether two objects are identical (in which case only one can be in the set). The three Set implementations are described in the following sections.

HashSet : A HashSet is an unsorted, unordered Set. It uses the hashcode of the object being inserted, so the more efficient your hashCode() implementation the better access performance you'll get. Use this class when you want a collection with no duplicates and you don't care about order when you iterate through it.

LinkedHashSet : A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order. When you iterate through a HashSet the order is unpredictable, while a LinkedHashSet lets you iterate through the elements in the order in which they were inserted.

Important : 
When using HashSet or LinkedHashSet, the objects you add to them must override hashCode(). If they don't override hashcode(), the default object. hashcode() method will allow multiple objects that you might consider "meaningfully equal" to be added to your "no duplicates allowed" set.


TreeSet: The TreeSet is one of two sorted collections (the other being TreeMap). It uses a Red-Black tree structure, and guarantees that the elements will be in ascending order, according to natural order. Optionally, you can construct a TreeSet with a constructor that lets you give the collection your own rules for what the order should be (rather than relying on the ordering defined by the elements' class) by using a Comparable or Comparator.