Sunday, 30 August 2015

Iterate over HashMap

Best way to Iterate over HashMap in Java

Here is the code example of Iterating over any Map class in Java e.g. Hashtable or LinkedHashMap. Though I have used HashMap for iteration purpose, you can apply same technique to other Map implementations. Since we are only using methods from java.uti.Map interface, solution is extensible to all kinds of Map in Java. We will use Java 1.5 foreach loop and Iterating over each Map.Entry object, which we get by calling Map.entrySet() method. Remember to use Generics, to avoid type casting. Use of Generics and foreach loop result in very concise and elegant code, as shown below.


for(Map.Entry<Integer, String> entry : map.entrySet()){
    System.out.printf("Key : %s and Value: %s %n", entry.getKey(), entry.getValue());
}

This code snippet is very handy for iterating HashMap, but has just one drawback, you can not remove entries without risking ConcurrentModificationException. In next section, we will see code using Iterator, which can help you for removal of entries from Map.



Removing Entries from Map in Java

One reason for iterating over Map is removing selected key value pairs from Map. This is a general Map requirement and holds true for any kind of Map e.g. HashMap, Hashtable, LinkedHashMap or even relatively new ConcurrentHashMap. When we use foreach loop, it internally translated into Iterator code, but without explicit handle to Iterator, we just can not remove entries during Iteration. If you do,  your Iterator may throw ConcurrentModificationException. To avoid this, we need to use explicit Iterator and while loop for traversal. We will still use entrySet() for performance reason, but we will use Iterator's remove() method for deleting entries from Map. Here code example  to remove key values from HashMap in Java:



  //code goes here
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
   Map.Entry<Integer, String> entry = iterator.next();
   System.out.printf("Key : %s and Value: %s %n", entry.getKey(), entry.getValue());
   iterator.remove(); // right way to remove entries from Map,
                      // avoids ConcurrentModificationException
}


You can see, we are using remove() method from Iterator and not from java.util.Map, which accepts a key object. This code is safe from ConcurrentModificationException.


Read more: http://java67.blogspot.com/2013/08/best-way-to-iterate-over-each-entry-in.html#ixzz3kIiWUMZU

Sorting ArryList in java

Sorting ArrayList in Java is not difficult, by using Collections.sort() method you can sort ArrayList in ascending and descending order in Java. Collections.sort() method optionally accept a Comparator and if provided it uses Comparator's compare method to compare Objects stored in Collection to compare with each other, in case of no explicit Comparator, Comparable interface's compareTo() method is used to compare objects from each other. If object's stored in ArrayList doesn't implements Comparable than they can not be sorted using Collections.sort() method in Java.


Sorting ArrayList in Java – Code Example

ArrayList Sorting Example in Java - Ascending Descending Order Code
Here is a complete code example of How to sort ArrayList in Java, In this Sorting we have used Comparable method of String for sorting String on their natural order, You can also use Comparator in place of Comparable to sort String on any other order than natural ordering e.g. in reverse order by using Collections.reverseOrder() or in case insensitive order by using String.CASE_INSENSITIVE_COMPARATOR.

public class CollectionTest {

   
    public static void main(String args[]) {
   
        //Creating and populating ArrayList in Java for Sorting
        ArrayList<String> unsortedList = new ArrayList<String>();
       
        unsortedList.add("Java");
        unsortedList.add("C++");
        unsortedList.add("J2EE");
       
        System.err.println("unsorted ArrayList in Java : " + unsortedList);
       
        //Sorting ArrayList in ascending Order in Java
        Collections.sort(unsortedList);
        System.out.println("Sorted ArrayList in Java - Ascending order : " + unsortedList);
       
        //Sorting ArrayList in descending order in Java
        Collections.sort(unsortedList, Collections.reverseOrder());
        System.err.println("Sorted ArrayList in Java - Descending order : " + unsortedList);
    }
}

Iterator vs Enumerator

Between Enumeration and Iterator, Enumeration is older and its there from JDK1.0, while iterator was introduced later. Iterator can be used with ArrayList, HashSet and other collection classes.  Another similarity between Iterator and Enumeration in Java is that  functionality of Enumeration interface is duplicated by the Iterator interface.

Only major difference between Enumeration and iterator is Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as by using Iterator we can manipulate the objects like adding and removing the objects from collection e.g. Arraylist.

Also Iterator is more secure and safe as compared to Enumeration because it  does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException. This is by far most important fact for me for deciding between Iterator vs Enumeration in Java.

In Summary both Enumeration and Iterator will give successive elements, but Iterator is new and improved version where method names are shorter, and has new method called remove. Here is a short comparison:

Enumeration
hasMoreElement()
nextElement()
N/A


Iterator
hasNext()
next()
remove()

So Enumeration is used when ever we want to make Collection objects as Read-only.

Thursday, 27 August 2015

Maven Failsafe plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>2.17</version>
    <executions>
        <execution>
            <id>integration-test</id>
            <goals>
                <goal>integration-test</goal>
            </goals>
            <configuration>
                <includes>
                    <include>**/it/SIPTResourceTestSuite.java,**/it/SIPTResourceTest.java</include>
                </includes>
            </configuration>
        </execution>
        <execution>
            <id>verify</id>
            <goals>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Maven Surefire plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.17</version>
    <configuration>
        <includes>
            <include>**/ut/ProvTestSuite.java, **/ut/*Test.java</include>
                </includes>
    </configuration>
</plugin>

Cargo Maven2 plugin

<plugin>
    <groupId>org.codehaus.cargo</groupId>
    <artifactId>cargo-maven2-plugin</artifactId>
    <version>1.4.10</version>
    <configuration>
        <container>
<containerId>jetty9x</containerId>
<type>remote</type>
        </container>
        <configuration>
<type>runtime</type>
<properties>
<cargo.runtime.args>force=true</cargo.runtime.args>
                <cargo.hostname>localhost</cargo.hostname>
                <cargo.servlet.port>${servlet.port}</cargo.servlet.port>
                <cargo.remote.username>admin</cargo.remote.username>
                <cargo.remote.password>admin</cargo.remote.password>                      
            </properties>
        </configuration>
        <deployables>
            <deployable>
                <groupId>${project.groupId}</groupId>
                <artifactId>${project.artifactId}</artifactId>
                <properties>
                    <context>/sipt-rs</context>
                    </properties>
                        <pingTimeout>300000</pingTimeout>
            </deployable>
        </deployables>
    </configuration>
    <executions>
        <execution>
            <id>redeploy-war-with-cargo</id>
            <phase>pre-integration-test</phase>
            <goals>
                <goal>deployer-redeploy</goal>
            </goals>
        </execution>
    </executions>
</plugin>



The above plug-in look for the cargo-jetty-7-and-onwards-deployer-1.4.11.war in side jetty/web-apps  folder and before that it identifies the jetty running on the specified host and port , later the binding with plug in and jetty happens via cargo war.

Once the binding is over, plug in will deploy the application war into the identified jetty. Later you can run the web/rest test cases from your java module.

Maven war plugin


<plugin>

         <artifactId>maven-war-plugin</artifactId>
          <version>2.5</version>

         <configuration>
                <warName>sipt-rest</warName>
          </configuration>

 </plugin>

Friday, 21 August 2015

Maven jar plugin

<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<!-- <addClasspath>true</addClasspath> -->
<!-- <classpathPrefix>lib/</classpathPrefix> -->
<mainClass>com.bt.noas.sipt.exportprofiles.ProfileExporter</mainClass>
</manifest>
</archive>
</configuration>
</plugin>

Thursday, 20 August 2015

SQL interview questions

How do you change the value for gender field in a table from Male to Female and vice versa.

update employees set gender = case gender when 'Male' then 'Female' when 'Female' then 'Male'     else 'Other' end

Monday, 10 August 2015

volatile Keyword in Java

In Java, each thread has its own stack, including its own copy of variables it can access. When the thread is created, it copies the value of all accessible variables into its own stack. The volatile keyword basically says to the JVM “Warning, this variable may be modified in another Thread”.

One common example for using volatile is for a flag to terminate a thread. If you’ve started a thread, and you want to be able to safely interrupt it from a different thread, you can have the thread periodically check a flag (i.e., to stop it, set the flag to true). By making the flag volatile, you can ensure that the thread that is checking its value will see that it has been set to true without even having to use a synchronized block. For example:

public class Foo extends Thread {
    private volatile boolean close = false;
    public void run() {
        while(!close) {
            // do work
        }
    }
    public void close() {
        close = true;
        // interrupt here if needed
    }
}


sleep() vs wait()

Compare the sleep() and wait() methods in Java, including when and why you would use one vs. the other.

sleep() is a blocking operation that keeps a hold on the monitor / lock of the shared object for the specified number of milliseconds.

wait(), on the other hand, simply pauses the thread until either (a) the specified number of milliseconds have elapsed or (b) it receives a desired notification from another thread (whichever is first), without keeping a hold on the monitor/lock of the shared object.

sleep() is most commonly used for polling, or to check for certain results, at a regular interval. wait() is generally used in multithreaded applications, in conjunction with notify() / notifyAll(), to achieve synchronization and avoid race conditions.

Thread.UncaughtExceptionHandler

This can be done using Thread.UncaughtExceptionHandler.

Here’s a simple example:

// create our uncaught exception handler
Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread th, Throwable ex) {
        System.out.println("Uncaught exception: " + ex);
    }
};

// create another thread
Thread otherThread = new Thread() {
    public void run() {
        System.out.println("Sleeping ...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted.");
        }
        System.out.println("Throwing exception ...");
        throw new RuntimeException();
    }
};

// set our uncaught exception handler as the one to be used when the new thread
// throws an uncaught exception
otherThread.setUncaughtExceptionHandler(handler);

// start the other thread - our uncaught exception handler will be invoked when
// the other thread throws an uncaught exception
otherThread.start();

Java Interview Questions - 2

Q: Is abstract keyword allowed for interface declaration ?
A: Yes, it is allowed. (static,final are not allowed)

Only public,abstract are permitted.

public abstract interface InterfaceTest {

} //perfect

Note: 
  • public,private,protected,default,static and abstract keywords are allowed for an interface declared inside a class.

Q: What are allowed types for a class ?
A: Only public,abstract,final,default(nothing) is allowed for outer class declarations.

Note: 
  • An inner class can be declared as public,private,protected,default,static,final and abstract.
  • Only either of final , abstract are allowed for inner class declaration.

Q: How do you find odd numbers in 1 to 100 ?

Q: How do you reverse a list ?

Q: How do you fetch data from multiple databases and merge and sort them in java ?

Q: What happens if hashcode produces same value in collections ?

Q: Query find duplicate entries in table ?
  • SELECT firstname, lastname, list.address FROM list INNER JOIN (SELECT address FROM list GROUP BY address HAVING count(id) > 1) dup ON list.address = dup.address
  • SELECT address, count(id) as cnt FROM list GROUP BY address HAVING cnt > 1

ThreadLocal Class

java.lang
Class ThreadLocal<T>

java.lang.Object
java.lang.ThreadLocal<T>
Direct Known Subclasses:
InheritableThreadLocal

public class ThreadLocal<T>
extends Object
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).
For example, the class below generates unique identifiers local to each thread. A thread's id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.

 import java.util.concurrent.atomic.AtomicInteger;

 public class ThreadId {
     // Atomic integer containing the next thread ID to be assigned
     private static final AtomicInteger nextId = new AtomicInteger(0);

     // Thread local variable containing each thread's ID
     private static final ThreadLocal<Integer> threadId =
         new ThreadLocal<Integer>() {
             @Override protected Integer initialValue() {
                 return nextId.getAndIncrement();
         }
     };

     // Returns the current thread's unique ID, assigning it if necessary
     public static int get() {
         return threadId.get();
     }
 }

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

Since:
1.2

Strings vs character array


In Java, Strings are immutable and are stored in the String pool. What this means is that, once a String is created, it stays in the pool in memory until being garbage collected. Therefore, even after you're done processing the string value (e.g., the password), it remains available in memory for an indeterminate period of time thereafter (again, until being garbage collected) which you have no real control over. Therefore, anyone having access to a memory dump can potentially extract the sensitive data and exploit it.

In contrast, if you use a mutable object like a character array, for example, to store the value, you can set it to blank once you are done with it with confidence that it will no longer be retained in memory.

Why would it be more secure to store sensitive data (such as a password, social security number, etc.) in a character array rather than in a String?

Strings are immutable in Java it means once created you cannot modify content of String. If you modify it by using toLowerCase(), toUpperCase() or any other method,  It always result in new String. Since String is final there is no way anyone can extend String or override any of String functionality.

ArrayList vs LinkedList vs Vector

ArrayList, LinkedList, and Vector are all implementations of the List interface. Which of them is most efficient for adding and removing elements from the list? Explain your answer, including any other alternatives you may be aware of.
View the answer ?


Of the three, LinkedList is generally going to give you the best performance. Here’s why:

ArrayList and Vector each use an array to store the elements of the list. As a result, when an element is inserted into (or removed from) the middle of the list, the elements that follow must all be shifted accordingly. Vector is synchronized, so if a thread-safe implementation is not needed, it is recommended to use ArrayList rather than Vector.

LinkedList, on the other hand, is implemented using a doubly linked list. As a result, an inserting or removing an element only requires updating the links that immediately precede and follow the element being inserted or removed.

However, it is worth noting that if performance is that critical, it’s better to just use an array and manage it yourself, or use one of the high performance 3rd party packages such as Trove or HPPC.

fail-fast vs fail-safe


The main distinction between fail-fast and fail-safe iterators is whether or not the collection can be modified while it is being iterated. Fail-safe iterators allow this; fail-fast iterators do not.

Fail-fast iterators operate directly on the collection itself. During iteration, fail-fast iterators fail as soon as they realize that the collection has been modified (i.e., upon realizing that a member has been added, modified, or removed) and will throw a ConcurrentModificationException. Some examples include ArrayList, HashSet, and HashMap (most JDK1.4 collections are implemented to be fail-fast).

Fail-safe iterates operate on a cloned copy of the collection and therefore do not throw an exception if the collection is modified during iteration. Examples would include iterators returned by ConcurrentHashMap or CopyOnWriteArrayList.

Examples:

public class FailFastExample
{
   
    public static void main(String[] args)
    {
        Map<String,String> premiumPhone = new HashMap<String,String>();
        premiumPhone.put("Apple", "iPhone");
        premiumPhone.put("HTC", "HTC one");
        premiumPhone.put("Samsung","S5");
       
        Iterator iterator = premiumPhone.keySet().iterator();
       
        while (iterator.hasNext())
        {
            System.out.println(premiumPhone.get(iterator.next()));
            premiumPhone.put("Sony", "Xperia Z");
        }
    }
}

public class FailSafeExample
{
    public static void main(String[] args)
    {
        ConcurrentHashMap<String,String> premiumPhone =
                               new ConcurrentHashMap<String,String>();
        premiumPhone.put("Apple", "iPhone");
        premiumPhone.put("HTC", "HTC one");
        premiumPhone.put("Samsung","S5");
       
        Iterator iterator = premiumPhone.keySet().iterator();
       
        while (iterator.hasNext())
        {
            System.out.println(premiumPhone.get(iterator.next()));
            premiumPhone.put("Sony", "Xperia Z");
        }
   
   }
 

}

Sunday, 9 August 2015

Object class

public class Object
{

    public Object()
    {
    }

    private static native void registerNatives();

    public final native Class getClass();

    public native int hashCode();

    public boolean equals(Object obj)
    {
        return this == obj;
    }

    protected native Object clone()
        throws CloneNotSupportedException;

    public String toString()
    {
        return (new StringBuilder()).append(getClass().getName()).append("@").append(Integer.toHexString(hashCode())).toString();
    }

    public final native void notify();

    public final native void notifyAll();

    public final native void wait(long l)
        throws InterruptedException;

    public final void wait(long l, int i)
        throws InterruptedException
    {
        if(l < 0L)
            throw new IllegalArgumentException("timeout value is negative");
        if(i < 0 || i > 999999)
            throw new IllegalArgumentException("nanosecond timeout value out of range");
        if(i >= 500000 || i != 0 && l == 0L)
            l++;
        wait(l);
    }

    public final void wait()
        throws InterruptedException
    {
        wait(0L);
    }

    protected void finalize()
        throws Throwable
    {
    }

    static
    {
        registerNatives();
    }
}

Native methods

The native keyword is applied to a method to indicate that the method is implemented in native code using JNI(Java Native Interface). It marks a method, that it will be implemented in other languages, not in Java. It works together with JNI (Java Native Interface).

Main.java:
public class Main {
    public native int intMethod(int i);
    public static void main(String[] args) {
        System.loadLibrary("Main");
        System.out.println(new Main().intMethod(2));
    }
}

Main.c:
#include <jni.h>
#include "Main.h"

JNIEXPORT jint JNICALL Java_Main_intMethod(
    JNIEnv *env, jobject obj, jint i) {
  return i * i;
}

Compile and run:
javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
  -I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main

Output:

4

Groovlets


public class GroovyServlet extends AbstractHttpServlet

This servlet will run Groovy scripts as Groovlets. Groovlets are scripts with these objects implicit in their scope:

request - the HttpServletRequest
response - the HttpServletResponse
application - the ServletContext associated with the servlet
session - the HttpSession associated with the HttpServletRequest
out - the PrintWriter associated with the ServletRequest

Your script sources can be placed either in your web application's normal web root (allows for subdirectories) or in /WEB-INF/groovy/* (also allows subdirectories).

To make your web application more groovy, you must add the GroovyServlet to your application's web.xml configuration using any mapping you like, so long as it follows the pattern *.* (more on this below). Here is the web.xml entry:

    <servlet>
      <servlet-name>Groovy</servlet-name>
      <servlet-class>groovy.servlet.GroovyServlet</servlet-class>
    </servlet>

    <servlet-mapping>
      <servlet-name>Groovy</servlet-name>
      <url-pattern>*.groovy</url-pattern>
      <url-pattern>*.gdo</url-pattern>
    </servlet-mapping>

The URL pattern does not require the "*.groovy" mapping. You can, for example, make it more Struts-like but groovy by making your mapping "*.gdo".

Monday, 3 August 2015

JAX-RS Annotations


JAX-RS Annotations
Annotation
Description
@Path
The @Path annotation’s value is a relative URI path indicating where the Java class will be hosted: for example, /helloworld. You can also embed variables in the URIs to make a URI path template. For example, you could ask for the name of a user and pass it to the application as a variable in the URI:/helloworld/{username}.
@GET
The @GET annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP GET requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@POST
The @POST annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP POST requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@PUT
The @PUT annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP PUT requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@DELETE
The @DELETE annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP DELETE requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@HEAD
The @HEAD annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP HEAD requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@PathParam
The @PathParam annotation is a type of parameter that you can extract for use in your resource class. URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation.
@QueryParam
The @QueryParam annotation is a type of parameter that you can extract for use in your resource class. Query parameters are extracted from the request URI query parameters.
@Consumes
The @Consumes annotation is used to specify the MIME media types of representations a resource can consume that were sent by the client.
@Produces
The @Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client: for example, "text/plain".
@Provider
The @Provider annotation is used for anything that is of interest to the JAX-RS runtime, such asMessageBodyReader and MessageBodyWriter. For HTTP requests, the MessageBodyReaderis used to map an HTTP request entity body to method parameters. On the response side, a return value is mapped to an HTTP response entity body by using a MessageBodyWriter. If the application needs to supply additional metadata, such as HTTP headers or a different status code, a method can return aResponse that wraps the entity and that can be built using Response.ResponseBuilder.

Maven - archetype:generate

Basic Maven project:

mvn archetype:generate -DgroupId=com.mycompany.app
 -DartifactId=my-app 
 -DarchetypeArtifactId=maven-archetype-quickstart
 -DinteractiveMode=false

Maven Web project:

mvn archetype:generate -DgroupId=com.mycompany.app 
 -DartifactId=RESTfulExample
 -DarchetypeArtifactId=maven-archetype-webapp
 -DinteractiveMode=false

mvn archetype:generate -DgroupId={project-packaging}
 -DartifactId={project-name}
 -DarchetypeArtifactId=maven-archetype-webapp
 -DinteractiveMode=false 

mvn archetype:generate -DgroupId=com.deegeu.dockerapp
 -DartifactId=dockerapp
 -DarchetypeArtifactId=maven-archetype-quickstart
 -DinteractiveMode=false 


Introduction to RESTful Web Services


RESTful web services are built to work best on the Web. Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability, that enable services to work best on the Web. In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web. The resources are acted upon by using a set of simple, well-defined operations. The REST architectural style constrains an architecture to a client/server architecture and is designed to use a stateless communication protocol, typically HTTP. In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.

The following principles encourage RESTful applications to be simple, lightweight, and fast:

Resource identification through URI: A RESTful web service exposes a set of resources that identify the targets of the interaction with its clients. Resources are identified by URIs, which provide a global addressing space for resource and service discovery. See The @Path Annotation and URI Path Templates for more information.

Uniform interface: Resources are manipulated using a fixed set of four create, read, update, delete operations: PUT, GET, POST, and DELETE. PUT creates a new resource, which can be then deleted by using DELETE. GET retrieves the current state of a resource in some representation. POST transfers a new state onto a resource. See Responding to HTTP Methods and Requests for more information.

Self-descriptive messages: Resources are decoupled from their representation so that their content can be accessed in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others. Metadata about the resource is available and used, for example, to control caching, detect transmission errors, negotiate the appropriate representation format, and perform authentication or access control. See Responding to HTTP Methods and Requests and Using Entity Providers to Map HTTP Response and Request Entity Bodies for more information.

Stateful interactions through hyperlinks: Every interaction with a resource is stateless; that is, request messages are self-contained. Stateful interactions are based on the concept of explicit state transfer. Several techniques exist to exchange state, such as URI rewriting, cookies, and hidden form fields. State can be embedded in response messages to point to valid future states of the interaction. See Using Entity Providers to Map HTTP Response and Request Entity Bodies and “Building URIs” in the JAX-RS Overview document for more information.

JAX-RS: Java API for RESTful Web Services (JAX-RS) is a Java
programming language API that provides support in creating
web services according to the Representational State
Transfer (REST) architectural pattern.[1] JAX-RS uses
annotations, introduced in Java SE 5, to simplify the
development and deployment of web service clients and
endpoints.

From version 1.1 on, JAX-RS is an official part of Java EE
6. A notable feature of being an official part of Java EE is
that no configuration is necessary to start using JAX-RS.
For non-Java EE 6 environments a (small) entry in the
web.xml deployment descriptor is required.

Implementations of JAX-RS include:
    Apache CXF, an open source Web service framework
    Jersey, the reference implementation from Sun (now
Oracle)
    RESTeasy, JBoss's implementation
    Restlet
    Apache Wink, Apache Software Foundation Incubator
project, the server module implements JAX-RS
    WebSphere Application Server from IBM:
        Version 7.0: via the "Feature Pack for
Communications Enabled Applications"
        Version 8.0 onwards: natively
    WebLogic Application Server from Oracle, see notes
    Apache Tuscany

Throw before return statement



  • The following code gives compilation error as return is unreachable when the throw is not handled.


public class TestThrow {
public static void main(String[] args) throws Exception {
throw new Exception();
return; //Unreacheble code
}
}


  • The following code is alright and the return is reachable with no compilation error as throw is handled.

public class TestThrow {
public static void main(String[] args) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return; // Now it's alright
}
}

Polymorphism works for static ??

No, polymorphism will not work at all for static methods. Method will be executed based on the type of the reference type not on the type of type of object pointed to.

Please find the example below.


public class StaticTest
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
       
        BaseClass bc = new SubClass();
        bc.method1();
    }
}


class BaseClass{

public static void method1(){

System.out.println("Base class");

}
}

class SubClass extends BaseClass{

public static void method1(){

System.out.println("Sub class");

}
}


Output:  Hello World!
                Base class