Saturday, April 30, 2011

Writing a swap function in java

Method 1 : Changing the data underneath
public class Swapper<T> {
      public Swapper(T obj) {
             data_ = obj;
      }
      public T get() { return data_; }
      public void set(T value) { data_ = value; }
      public void swap(Swapper<T> o) {
           T tmp = o.data_;
           o.data_ = data_;
           data_ = tmp;
      }
      private T data_ = null;
  }

  // .. Now you can do:
  Swapper<String> a = new Swapper("Hello");
  Swapper<String> b = new Swapper("World");
  // a.get().equals("Hello")
  a.swap(b); // now a.get().equals("World")


But we can write function which uses the above idea:
public void Swap(RefObject<Integer> p, RefObject<Integer> q)
{
   int temp;
   temp = p.argvalue;
   p.argvalue = q.argvalue;
   q.argvalue = temp;
}
public final class RefObject<T>
{
    public T argvalue;
    public RefObject(T refarg)
    {
        argvalue = refarg;
    }
}


Method 2 : Using Atomic reference
Example for integers:

public void swap(AtomicInteger a, AtomicInteger b){
     a.set(b.getAndSet(a.get()));
}
  

Above method can be written in more verbose way like this:

import java.util.concurrent.atomic.AtomicInteger;
public class TestAtomicInteger{
    private static void swap(AtomicInteger a, AtomicInteger b) {
        int val = a.get();
        a.set(b.get());
        b.set(val);
    }

    public static void main(String[] args) {
        AtomicInteger a = new AtomicInteger(1);
        AtomicInteger b = new AtomicInteger(2);

        swap(a, b);

        System.out.println("a: " + a + " b: " + b);
    }
}

Example for strings:
public void swap(AtomicReference a, AtomicReference b){
        a.set(b.getAndSet(a.get()));
}


Of course this not very satisfactory, as you hardly ever develop against AtomicReferences. But basically you need to use some kind of container as shown above, because you can't just swap the references. So you can e.g. swap the elements of a two-element array or list, but you just can't swap two strings without having access to the original variables (so you can't do it in a helper function).

Case when data is in list:
If your data happens to be a List, a better way to swap is to use Collections.swap(List, int, int).
In above function following are the function and parameters:

Swaps the elements at the specified positions in the specified list.
(If the specified positions are equal, invoking this method leaves
the list unchanged.)
Parameters:
    list - The list in which to swap elements.
    i - the index of one element to be swapped.
    j - the index of the other element to be swapped. 

Case when swap is required in sorting:
apparently the real objective is to sort an array of ints. That's a one-liner with Arrays.sort(int[]):

int[] arr = {2,3,1,378,19,25};
Arrays.sort(arr);

To check the output:
   System.out.println(Arrays.toString(arr));
   // [1, 2, 3, 19, 25, 378]

And here is a simple helper function to swap two positions in an array of ints:

public static void swap(final int[] arr, final int pos1, final int pos2){
   final int temp = arr[pos1];
   arr[pos1] = arr[pos2];
   arr[pos2] = temp;
}

Best Way to Swap Values in Java

Though not all Java applications require variables to be swapped, but those which do require are not given proper thoughts about correct and optimized implementation.


Method-1: Using temporary Variable

The most common way to swap two values is by using a temporary variable as shown below:

int a=10,b=5,c;
c=a; (c=10,a=10,b=5)
a=b; (c=10,a=5,b=5)
b=c; (c=10,a=5,b=10)

If the use of temporary variable c is not allowed, then we have the following two options:

Method-2.1 : Using the addition and subtraction operations
int a=10,b=5;
a=a+b;
b=a-b;
a=a-b

The problem with the above solution is that the addition and subtraction can cause overflows. An overflow is a condition when the value of a variable is increased/decreased beyond the maximum/minimum value of that variable. Though the output of such a program may show that the variables have been swapped but it is not guaranteed as per Specification of various programming languages including Java.

package com.vaani.swap.subtraction;
class Test{
    public static void main (String args[]) {
            int a=1999999999,b=1899999999;
            a = a + b;
            System.out.println("After operation 1, a = " + a +
                 " b = " + b);
            b = a - b;
            System.out.println("After operation 2, a = " + a +
                 " b = " + b);
            a = a - b;
            System.out.println("After operation 3, a = " + a +
                 " b = " + b);
   }
}

Output:
After operation 1, a =  -394967298 b = 1899999999
After operation 2, a =  -394967298 b = 1999999999
After operation 3, a =  1899999999 b = 1999999999

Method-3: Using the XOR operator

The XOR operator can also be used swap two variables using the logic shown below:

int a=10,b=5;
a=a^b;
b=a^b;
a=a^b

Thank you

Java timer test

Example to show java timer:

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class TestTimerTask {
    public static void main(String[] args) { 
//define a timer 
final Timer timer = new Timer("Test Timer"); 
 
timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                System.out.println("Timer fired");
            }
        }, Calendar.getInstance().getTime(), 5 * 1000);

        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                System.out.println("Canceling timer");
                timer.cancel();
            }
        });
    }
}

Friday, April 29, 2011

Usage of class loaders

Java ClassLoader is a powerful tool that can be used in a various of ways to extend the possibilities of Java applications.
One of the most well-known usages of custom class loaders are Java Applets, where a class loader is used to dynamically download code from the webpage. Customized ClassLoaders are also the base element of Java Application Servers and Web Containers. ClassLoaders are one of things that make the Java platform so extensible and flexible.

Many J2EE application servers have a hot deployment capability, where we can reload an application with a new version of class definition, without bringing the server VM down. Such application servers make use of custom class loaders. Even if we don t use an application server, we can create and use custom class loaders to fine-control class loading mechanisms in our Java applications. So have fun with custom loaders. 

Getting the class loader of a class

Bootstrap class loader is pretty special, in that it is implemented in native code. All other class loaders are written in Java (apart from some native methods) and extend the java.lang.ClassLoader class. We could get the class loader which was used to load any particular class with class.getClassLoader() method:

public class ShowClassLoaders {

    public static void main(String[] args) {
        System.out.println("class loader for Integer: "
            + Integer.class.getClassLoader());
        System.out.println("class loader for BlowfishCipher: "
            + com.sun.crypto.provider
            .BlowfishCipher.class.getClassLoader());
        System.out.println("class loader for this class: "
            + ShowClassLoaders.class.getClassLoader());
    }
}

When we run this program, we will see the following output:
class loader for Integer: null
class loader for BlowfishCipher: sun.misc.Launcher$ExtClassLoader@9cab16
class loader for this class: sun.misc.Launcher$AppClassLoader@d9f9c3

java.lang.Integer was loaded using the bootstrap class loader. In most implementations getClassLoader() method returns null for the bootstrap class loader. com.sun.crypto.provider.BlowfishCipher class is stored inside the <JAVA_HOME>/lib/ext/sunjce_provider.jar so it was loaded with the extensions class loader. Classes implemented by us, like the class with the main method, was loaded by system class loader.

What is classloader?

The Class loader concept, one of the cornerstones of the Java virtual machine, describes the behavior of converting a named class into the bits responsible for implementing that class.
Source code to Machine code
In contrary to such languages like C++ or Fortran where source code is compiled directly to machine’s native code, Java’s source code is compiled to platform-independent Java bytecode. Normally Java Virtual Machine loads this bytecode for every required class from .class files from the local file system. Java gives us however a possibility to greatly influence the way bytecode is load – customized class loaders.

The loading of Java classes is performed by class loaders (CL), they are responsible for loading classes into the JVM. Simple applications can use the Java platform’s built-in class loading facility to load their classes, more complex applications tend to define their own custom class loaders. Because of this, the Java run time does not need to know anything about files and file systems when running Java programs.

Some points to note about class loaders
  • All class loaders are of the type java.lang.ClassLoader.
  • There are 2 types of classloaders mainly - Bootstrap loader or Primordial classloader and "other" class loaders which include extension class loaders and system class loaders
  • Root loader is bootstrap class loader which has native implementation and cannot be instantiated by Java code.
  • Other than the bootstrap class loader all class loaders have a parent class loader.
  • Chaining” of class loaders means, that every class loader has a parent class loader, and in most cases it asks its parent to load a requested class before trying to resolve it on its own. If the parent can not find the class, the class loader itself tries to load the class.

Writing custom class loader in java

Why write a ClassLoader?

If the JVM has a ClassLoader, then why would you want to write another one? Good question. The default ClassLoader only knows how to load class files from the local filesystem. This is fine for regular situations, when you have your Java program fully compiled and waiting on your computer. But one of the most innovative things about the Java language is that it makes it easy for the JVM to get classes from places other than the local hard drive or network. For example, browsers use a custom ClassLoader to load executable content from a Web site. There are many other ways to get class files. Besides simply loading files from the local disk or from a network, you can use a custom ClassLoader to:

  • Automatically verify a digital signature before executing untrusted code
  • Transparently decrypt code with a user-supplied password
  • Create dynamically built classes customized to the user's specific needs

Anything you can think of to write that can generate Java bytecode can be integrated into your application.

A Custom Class Loader:

We have to extend the java.lang.ClassLoader class and implement some of its crucial methods, like loadClass(String name). This method is run every time somebody requests a class inside the code, and receives as a parameter the full name of the class to load.

In our implementation we will print out this name, so to know when our method was called, and then load the class with our class loader if the class is in “com.vaani” package.(See loadClass method in code below).
 If the class is not in “com.vaani”, we will use the super.loadClass() method, which will pass the request to the parent class loader. (Please note that in this article we omit the “package” and “import” statements to make the code shorter, but every class should be inside the “com.vaani” package).

public class CustomClassLoader extends ClassLoader {

    /**
     * Parent ClassLoader passed to this constructor
     * will be used if this ClassLoader can not resolve a
     * particular class.
     */
    public CustomClassLoader(ClassLoader parent) {
        super(parent);
    }

    /**
     * Loads a given class from .class file just like
     * the default ClassLoader. This method could be
     * changed to load the class over network from some
     * other server or from the database.
     *
     * @param name Fully qualified class name
     */
    private Class<?> getClass(String name)
        throws ClassNotFoundException {
        // We are getting a name that looks like
        // com.vaani.ClassToLoad
        // and we have to convert it into the .class file name like 
        // com/vaani/ClassToLoad.class
        String file = name.replace('.', File.separatorChar)
            + ".class";
        byte[] b = null;
        try {
            // This loads the byte code data from the file
            b = loadClassData(file);
            // defineClass is inherited from the ClassLoader class
            // and converts the byte array into a Class
            Class<?> c = defineClass(name, b, 0, b.length);
            resolveClass(c);
            return c;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Every request for a class passes through this method.
     * If the requested class is in "com.vaani" package,
     * it will load it using the
     * CustomClassLoader.getClass() method.
     * If not, it will use the super.loadClass() method
     * which in turn will pass the request to the parent.
     *
     * @param name
     *            Full class name
     */
    @Override
    public Class<?> loadClass(String name)
        throws ClassNotFoundException {
        System.out.println("loading class '" + name + "'");
        if (name.startsWith("com.vaani")) {
            return getClass(name);
        }
        return super.loadClass(name);
    }

    /**
     * Loads a given file (presumably .class) into a byte array.
     * The file should be accessible as a resource, for example
     * it could be located on the classpath.
     *
     * @param name File name to load
     * @return Byte array read from the file
     * @throws IOException Is thrown when there
     *               was some problem reading the file
     */
    private byte[] loadClassData(String name) throws IOException {
        // Opening the file
        InputStream stream = getClass().getClassLoader()
            .getResourceAsStream(name);
        int size = stream.available();
        byte buff[] = new byte[size];
        DataInputStream in = new DataInputStream(stream);
        // Reading the binary data
        in.readFully(buff);
        in.close();
        return buff;
    }
}

Classloader types

Bootstrap class loader

There is only one Primordial Class Loader, which is an essential part of each Java VM. It cannot be overridden. The Primordial Class Loader is involved in bootstrapping the Java environment. Since most VMs are written in C, it follows that the Primordial Class Loader is typically written in C. This special class loader loads trusted classes, usually from the local disk.


ClassLoaders other than Bootstrap by jdk
There are three distinct types of Class Loader objects defined by the JDK itself:
  • Applet Class Loaders, 
  • RMI Class Loaders, and 
  • Secure Class Loaders.
From the standpoint of a Java user or a system administrator, Applet Class Loaders are the most important variety. Java developers who are interested in rolling their own Class Loaders will likely subclass or otherwise use the RMI Class Loader and Secure Class Loader classes.

Applet Class Loaders are responsible for loading classes into a browser and are defined by the vendor of each Java-enabled browser. Vendors generally implement similar Applet Class Loaders, but they do not have to. Sometimes seemingly subtle differences can have important security ramifications. For example, Netscape now tracks a class not by its name, but by a pointer to actual code, making attacks that leverage Class Loading complications harder to carry out.

Applet Class Loaders help to prevent external code from spoofing important pieces of the Java API. They do this by attempting to load a class using the Primordial Class Loader before fetching a class across the network. If the class is not found by the Primordial Class Loader, the Applet Class Loader typically loads it via HTTP using methods of the URL class. Code is fetched from the CODEBASE specified in the <APPLET> tag. If a fetch across the Web fails, a ClassNotFound exception is thrown.
It should be clear why external code must be prevented from spoofing the trusted classes of the Java API. Consider that the essential parts of the Java security model (including the Applet Class Loader class itself) are simply Java classes. If an untrusted class from afar were able to set up shop as a replacement for a trusted class, the entire security model would be toast!

The RMI Class Loader and Secure Class Loader classes were introduced with JDK 1.1 and Java 2, respectively. RMI Class Loaders are very similar to Applet Class Loaders in that they load classes from a remote machine. They also give the Primordial Class Loader a chance to load a class before fetching it across the Net. The main difference is that RMI Class Loaders can only load classes from the URL specified by Java's rmi.server.codebase property. Similar in nature to RMI Class Loaders, Secure Class Loaders allow classes to be loaded only from those directories specified in Java's java.app.class.path property. Secure Class Loaders can only be used by classes found in the java.security package and are extensively used by the Java 2 access control mechanisms.

Namespaces in class loading

In general, a running Java environment can have many Class Loaders active, each defining its own namespace. Namespaces allow Java classes to see different views of the world depending on where they originate.
Eg. - classes from some url, OR classes from local environment, classes from particular firewall.

Simply put, a namespace is a set of unique names of classes loaded by a particular Class Loader and a binding of each name to a specific class object. Though some people say that namespaces are disjoint and do not overlap, this is not true in general. There is nothing to stop namespaces from overlapping.

Most VM implementations have used different class loaders to load code from different origins. This allowed these implementations to assign a single security policy to all code loaded by the same class loader, and to make security decisions based on which class loader loaded the class that is asking to perform a dangerous operation. With the addition of code signing in JDK 1.1, there are now two characteristics for categorization of code: origin (usually represented as a URL) and signer (the identity associated with the private key used to sign the file). Only the Class Loader that loaded a piece of code knows for sure where the code was loaded from.

According to the Java specification, every Class Loader must keep an inventory of all the classes it has previously loaded. When a class that has already been loaded is requested again, the class loader must return the already loaded class.

Every different class loader represents a different namespace. Static fields of classes inside one namespace are separate from static fields of classes from other namespaces. If we set a value of a specific static field in namespace A, objects from namespace B will not be able to read it, and vice versa.

Let’s see how it works. We will have a public static Integer field in some class, and we will be trying to access this field from classes loaded with different class loaders. Here is this field:

public class StaticHolder {
    public static Integer value = null;
}

Below is also the class used to access the field. It will read the value of the field and then change it to 4. Default value for any class field is null, so that’s what we expect to see as the start value. In a normal, single-classloader program, after changing the value of the static field, the change would be visible to other objects reading that field. We will see what happens with multiple classloaders.

public class StaticAccessor {
    /**
     * Accesses the static field from StaticHolder class.
     * It reads its value and after that sets it to 4.
     */
    @Override
    public void runMe() {
        System.out.println("--- Starting runMe. Static value: "
            + StaticHolder.value);
        StaticHolder.value = 4;
        System.out.println("--- Finishing runMe. Static value: "
            + StaticHolder.value);
    }
}

In our experimental main method we will create this time two CustomClassLoaders and load our StaticAccessor field with both of them. We will then create two instances of the StaticAccessor class, each of them from the different class loader, and run their runMe() methods.

 You can find the implementation of our CustomClassLoader in the previous article.

When we run the program, we will get the following output:
loading class 'javablogging.StaticAccessor'
...
--- Starting runMe. Static value: null
loading class 'java.lang.Integer'
--- Finishing runMe. Static value: 4
loading class 'javablogging.StaticAccessor'
...
--- Starting runMe. Static value: null
loading class 'java.lang.Integer'
--- Finishing runMe. Static value: 4
When you look at the “— Starting runMe” lines, you will notice that both of them show null! Although we changed the static field to 4 in the first run of runMe(), the value read in the second runMe() shows once again null.

In normal programs it may be hard to see a usage for such tricks. Separating namespaces in such a way may be however useful for example when doing unit tests, when you want to be sure that every test runs in a completely separate sandbox, or when implementing frameworks or application servers, where every deployed application should be isolated from others.

References
You can read more about class loaders and namespaces in Java for example in this article: http://www.artima.com/underthehood/classloadersP.html.



Process of Class loading

Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So how is the very first class loaded?

Bootstrap class loading
The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. It is somewhat special because the virtual machine assumes that it has access to a repository of trusted classes which can be run by the VM without verification.

When a new JVM instance is started , the bootstrap class loader is responsible for loading key java classes like java.lang.Object and other runtime code into memory. The runtime classes are packaged inside jre/lib/rt.jar file. We cannot find the details of the bootstrap class loader in the java language specification, since this is a native implementation. For this reason the behavior of the bootstrap class loader will differ across JVMs.Java can change its class storage model simply by changing the set of functions that implements the class loader.

Non-primordial class loaders
Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader.
ex : Bootstrap (primordial) Loads JDK internal classes, java.* packages. (as defined in the sun.boot.class.path system property, typically loads rt.jar and i18n.jar) and is the parent in the Class loaders hierarchy.
Next comes the Extensions (Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system property – usually lib/ext directory of the JRE) and then System (Loads classes from system classpath (as defined by the java.class.path property, which is set by the CLASSPATH environment variable or –classpath or –cp command line options) ClassLoaders.

Classes loaded by Bootstrap class loader have no visibility into classes loaded by its descendants (ie Extensions and Systems class loaders).
The classes loaded by system class loader have visibility into classes loaded by its parents (ie Extensions and Bootstrap class loaders).
If there were any sibling class loaders they cannot see classes loaded by each other. They can only see the classes loaded by their parent class loader. For example Sibling1 class loader cannot see classes loaded by
Sibling2 class loader. Both Sibling1 and Sibling2 class loaders have visibilty into classes loaded by their parent class loaders (eg: System, Extensions, and Bootstrap)

Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true
Note : Two objects loaded by different class loaders are never equal even if they carry the same values, which mean a class is uniquely identified in the context of the associated class loader. This applies to singletons too, where each class loader will have its own singleton.

At its simplest, a class loader creates a flat name space of class bodies that are referenced by a string name. The method definition is:
         Class r = loadClass(String className, boolean resolveIt);
The variable className contains a string that is understood by the class loader and is used to uniquely identify a class implementation. The variable resolveIt is a flag to tell the class loader that classes referenced by this class name should be resolved (that is, any referenced class should be loaded as well).
We can build our own ClassLoader by being a subclass of java.lang.ClassLoader. The only abstract method that must be implemented is loadClass().

Dynamic vs Static classloading

Summary
Class loading proceeds according to the following general algorithm:
  • Determine whether the class has been loaded before. If so, return the previously loaded class.
  • Consult the Primordial Class Loader to attempt to load the class from the CLASSPATH. This prevents external classes from spoofing trusted Java classes.
  • See whether the Class Loader is allowed to create the class being loaded. The Security Manager makes this decision. If not, throw a security exception.
  • Read the class file into an array of bytes. The way this happens differs according to particular class loaders. Some class loaders may load classes from a local database. Others may load classes across the network.
  • Construct a Class object and its methods from the class file.
  • Resolve classes immediately referenced by the class before it is used. These classes include classes used by static initializers of the class and any classes that the class extends.
  • Check the class file with the Verifier.

Thursday, April 28, 2011

Easy Java Bean toString() using BeanUtils

Its always good to write toString() function for the bean, but doing it manually is really tedious for lazy developers, where one concatenates the fields in the class to create a toString() method.  This code snippet using Apache Commons (a.k.a. Jakarta Commons) is very helpful for just such occasions:
public String toString() {
  try {
    return BeanUtils.describe(this).toString();
  } catch (Exception e) {
    Logger.getLogger(this.getClass()).error("Error converting object to String", e);
  }
  return super.toString();
}

How Many String Objects Are Created ?

Consider the code fragment shown below:

String s1="abc";
String s2="def"
System.out.println(s1 + " " + s2);


The question is how many String objects are created after the last line is compiled by Java.

To solve questions like this one can use Eclipse decompiler (JAD) to see how the Java compiler actually interpreted that third line.

1) For  any java developer it will be very easy to tell that first two lines create one object each and hence two objects in first two line.

2) The third line in the above code is interpreted by JDK 1.5 compiler as:
system.out.println((new StringBuilder(string.valueOf(s1))).append(" ").append(s2).toString());

This clearly tells us that 2 more string objects (" " and "abc def") are created in the last line.
3) Hence we can say that 4 String and 1 String Builder objects are created by that piece of code.

So the following code shows it all:
string s1 = "abc";
string s2 = "def";
system.out.println((new StringBuilder(string.valueOf(s1))).append(" ").append(s2).toString());

JDBC Hello World program

Register the driver you want:

static{
// register Oracle JDBC driver with DriverManager
     Class.forName("oracle.jdbc.driver.OracleDriver");
}

Create a connection object:

//Create a method, in which we will create connection
public void createConnection(){
Connection conn=null;

Now just open the connection:
try{  // get a connection to the database
     conn = DriverManager.getConnection(
   "jdbc:oracle:thin:@localhost:1521:XE", 
   "scott", 
   "tiger");

     // construct a Statement
     Statement stmt = conn.createStatement();

     // run query
     ResultSet rs = stmt.executeQuery("SELECT 'Hello World' FROM DUAL;");

     // iterate through the result set
     while (rs.next()) {
           System.out.println(rs.getString(1));
     }
}
catch(Exception ex){//deal with exception}
 
}//end method 

SOLID - OOPS/OOAD Principle

The Object Oriented concepts in all OOPS language follow some common principles. These principles are guidelines for developers and architects which they need to understand as they grow their understanding of the language.

The SOLID principles are the most talked about in the Enterprise Java world. These principles deal with cohesion, coupling, inheritance, abstract types in the Object Oriented Analysis and Design (OOAD)

The five principles are also asked about in Java or JEE interview. SOLID is an acronym for 5 principles of the Java language which are listed here:

1) S - Single Responsibility Principle: This principle is very closely related to the highly cohesive design methodology. This principle says that each class, method and variable should have single responsibility to perform. If there are multiple responsibilities assigned to a class then it becomes very difficult to maintain as the Java application scales. So sufficient time should be given to think what responsibility will be assigned to which class, method or variable.

2) O - Open Closed Principle: This principle says that when a class is inherited by other class then the superclass should not be a candidate for change just because it is going to be inherited by some other class. Thus it can be said that a class may be open for inheritance but closed for change because of inheritance.

3) L - Liskov Substitution Principle: This principle says that when multiple classes inherit or implement a class/interface and we have reference of super type which references to an object of one of the sub type then changing the subtype object from one class to another should not make any change.
Vehicle v = new Suzuki();
v = new Benz();
The change of object in the above Java sample code should not make any change to the various methods being invoked other than the fact that the methods will now be invoked on Benz object instead of the Suzuki object.

4) I - Interface Segregation Principle: This principle says that instead of having a big fat interface or class, split the functionality into multiple parts.This is different from the Single Responsibility Principle because even if a class has a single responsibility, it can be split into multiple parts for better understanding and maintainability. One common method to split a fat class is to make it implement/inherit other thin interface/class.

5) D - Dependency Inversion Principle: This principle is very much similar to the Open Closed Principle it states that the super type should not be dependent on the sub type but the sub type should be dependent on the super type. The above is possible if abstract entities are super types and concrete types as sub types. The sub types can anytime changed without affecting the super types.

Here is the analysis for the above discussion:

S and I are similar but with the difference that I can be used when S makes a single class grow fat. I have seen some classes having 2000 lines of code and 10-15 methods. It really makes life Hell

O, L and D are similar but O to not changing the super type just because of inheritance relationship, L asks us to make sure that multiple sub type objects are substitutable for a reference of super type and D emphases on coding to interfaces or abstract classes

Interview Questions : JEE Web Application Development

The answers are very brief and are intended to provide the direction towards which one should format his answer. Be more detailed and clear with your answers. All the best.


1) How do you differentiate between Core Java and Enterprise Java?
Expected Ans: Core Java is something that provides the API's like regular expression, String handling, collections. But enterprise java involves writing scalable, secure and per-formant applications which can have large user base.

2) What do you generally do after you have resolved a problem?
Expected Ans: Perform the Root Cause Analysis and make sure the changes done have not effected any other module.

3) What is JSON? Can you represent JSON as Java Object?
Expected Ans: JSON stands for Javascript object notation and is used to initialize Javascript objects. Yes it can be used as Java object also. Provide more info here

4) What kind of HTTP request does the <a href="url">text</a> generate?
Expected Ans: It will generate HTTP GET request

5) What are the common browser issues you will keep in mind while creating a web application?
Expected Ans: 1) User pressing back/refresh button
                            2) Browser crashing
                            3) Session issues
                            4) Compatibility across web browsers

6) What steps will you take for ensuring the proper security of an web application?
Expected Ans: Stuff like Encryption, Authentication and Authorization

7) The Server and Database are working fine at your end but not on customer machine. What will you do?
Expected Ans: 1) Check if the customer has not done any customizations
                             2) Provide a test build same as running at my end (ask customer to take a backup of their  app)
                             3) Check out how the customer is using the application


8) A web application is running but pages are loading slow. How will you figure out what the problem is?
Expected Ans: Look for threading, database, caching issues.

9) What is the difference between frameworks like Jquery/DOJO and AJAX?
Expected Ans: Jquery and DOJO are java script frameworks for writing rich web applications but AJAX is a server communication mechanism which can issue requests without page reload.

10) What are the reasons for a page not found error and how will you sort it out?
Expected Ans: 1) The URL being sent is wrong
                             2) The web.xml mapping is wrong 
                             3) The web server is down 
                             4) The application has not been deployed

11) How will you know whether a Java file is a servlet or not?
Expected Ans: It will extend from HttpServlet class

12) When will you use Servlet and JSP or MVC framework?
Expected Ans: While framework provides a number of components and allows one to concentrate more on the business logic but Servlets and JSP are used for controller and view layer respectively.
13) What are the common issues you have faced in web applications and how did you resolve them?
Expected Ans: 1) Server not starting up. Proper heap size not set
                             2) Migrating from JBoss to Weblogic. Wrote a number of XML configurations
                             Any other generic problems faced during development/support


14) How do you keep yourself updated about the latest web technologies?
Expected Ans: Whatever websites/blogs/forums/authors you follow.

15) What was the last technical book you read?
Expected Ans: Whatever you have read

Obtaining annotations at runtime using reflection

You can use getAnnotation method on Class of object, which has annotation attached to it.

Defining an annotation

package com.vaani.annotations;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface HelloAnno {
String value();
String greetTo();
}

 

Using the annotations


Note that I have kept value as German words, corresponding to greetTo which is in english lanaguage.

@HelloAnno(value = "Gooten Morgen", greetTo = "GoodMorning")
public class AnnotationUser{
@HelloAnno(value = "Gooten Tag", greetTo = "Hi")
public void sayHi() {
}
//
@HelloAnno(value = "Gute Nacht", greetTo = "GoodNight")
public void sayHello() {
try {
Method m = getClass().getMethod("sayHello");
HelloAnno anno = m.getAnnotation(HelloAnno.class);

System.out.println(anno.value() + " " + anno.greetTo());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}


 


Method to print all annotation




public static void printAnnotations(Class clazz){
Class clazz = demo.getClass();
Annotation[] annotations = clazz.getAnnotations();
for (Annotation anno : annotations) {
       System.out.println("Annotation Type: " + anno.annotationType());

//Prints Annotation Type: interface com.vaani.annotations


}

HelloAnno anno = (HelloAnno) clazz.getAnnotation(HelloAnno.class);
System.out.println("Anno Value : " + anno.value());
System.out.println("Anno GreetTo: " + anno.greetTo());
//Outputs
Anno value : Gooten Morgen
Anno GreetTo : GoodMorning


try {
Method m = clazz.getMethod("sayHi");

anno = m.getAnnotation(HelloAnno.class);
System.out.println("Anno Value : " + anno.value());
System.out.println("Anno GreetTo: " + anno.greetTo());

 

//Outputs
Anno value : Gooten Tag
Anno GreetTo : Hi



} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}





Runner or tester class to show annotation:


public static void main(String[] args) {
GettingAnnotation demo = new GettingAnnotation();
Class clazz = demo.getClass();
printAnnotation(clazz);
}

Annotations in java5

  1. Java defines seven built-in annotations.
  2. Four are imported from java.lang.annotation: @Retention, @Documented, @Target, and @Inherited.
  3. Three, @Override, @Deprecated, and @SuppressWarnings, are included in java.lang.
Seeing them one by one:
@Override
@Deprecated
@SuppressWarnings
@Retention
@Documented
@Target
@Inherited

Chitika