Sunday, April 15, 2012

Java 1.5 Feature : Varargs


In past releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method.

It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs.

Public static String format(String pattern,
Object... arguments);
The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments. Varargs can be used only in the final argument position.

Much more simpler example here..

public class VarArgs {
public static void main(String[] args) {
String[] newArgs = {"a", "b", "c"};
vaMethod(newArgs);
}

public void vaMethod(String[] args) {
System.out.println("You gave me " + args.length + " args! Yay.");
}
}
You can declare it more easily, and not have to construct the array ahead of time:

public class VarArgs {
public static void main(String[] args) {
vaMethod("a", "b", "c");
}

public void vaMethod(String... args) {
System.out.println("You gave me " + args.length + " args! Yay.");
}
}


Java 1.5 Language Features


Generics

This long-awaited enhancement to the type system allows a type or method to operate on objects of various types while providing compile-time type safety. It adds compile-time type safety to the Collections Framework and eliminates the drudgery of casting. Refer to JSR 14.

Enhanced for Loop

This new language construct eliminates the drudgery and error-proneness of iterators and index variables when iterating over collections and arrays. Refer to JSR 201 .

Autoboxing/Unboxing

This facility eliminates the drudgery of manual conversion between primitive types (such as int) and wrapper types (such as Integer). Refer to JSR 201 .

Typesafe Enums

This flexible object-oriented enumerated type facility allows you to create enumerated types with arbitrary methods and fields. It provides all the benefits of the Typesafe Enum pattern ("Effective Java," Item 21) without the verbosity and the error-proneness. Refer to JSR 201.

Varargs

This facility eliminates the need for manually boxing up argument lists into an array when invoking methods that accept variable-length argument lists. Refer to JSR 201.

Static Import

This facility lets you avoid qualifying static members with class names without the shortcomings of the "Constant Interface antipattern." Refer to JSR 201.

Metadata (Annotations)

This language feature lets you avoid writing boilerplate code under many circumstances by enabling tools to generate it from annotations in the source code. This leads to a "declarative" programming style where the programmer says what should be done and tools emit the code to do it. Also it eliminates the need for maintaining "side files" that must be kept up to date with changes in source files. Instead the information can be maintained in the source file. Refer to JSR 175.


Friday, April 13, 2012

Difference between Layer and Tier


Layer and Tier are really two very different things:

Layers are a means of logical separation, and are an architectural pattern to separate concerns. Typical layers are the storage / data layer, the data access layer, a business logic layer, and a presentation layer. When deploying an application, these layers might exist either on one machine, or on multiple machines.

When architecting the layers of an application, one must consider various factors:

What is this layer responsible for?
Will this layer translate to a tier at any point?
Are other applications expected to communicate with this layer?
What are the dependencies for this layer?
Tiers are the physical separation of an application. Typically, a regular web application will have a data tier which maps to the database, a business and presentation tier (potentially together) that map to the underlying business logic and web pages respectively, and a front-end tier that maps to the browser. There are scenarios wherein the business and presentation layers are split, so the business layer components reside on a separate node, and the web application itself resides on another node. Tiers necessarily imply layers, but not vice versa.

While layer decisions are driven primarily by separation of concerns, a tiering decision is driven differently. In fact decisions around tiers need to be well thought-out, especially since physical tiers may result in a performance degrade, due to network latency, and marshalling / unmarshalling overheads. For the most part, having the data sit in a separate tier on a database server is fairly well accepted, but the decision of whether or not to separate web pages into a tier separate from business logic components is a question that is often debated. A few points that support this separation are:

If the web server is expected to serve up a large amount of static content, it is more feasible to scale out the web servers independent of the business logic processing, and hence keep them on separate tiers.
If the processing of the businss logic requires a significant amount of processing, and this acts as a bottleneck for the rest of the web page processing, then it is more feasible to scale out the application servers independent of the web servers, and hence keep them on separate tiers.
If the functionality encapsulated by the business logic components is expected to be consumed by clients other than the presentation layer, then it is better to have these hosted on a separate tier, and front-end it with a web service / WCF facade.
If there is a need to have more security for the business functionality, then it is better to host the businss logic components in a separate tier, and separate it from the web server using a firewall.
If, on the other hand, the intent is only to scale out, without a deep need to scale out business and presentation tiers independently, then keeping them in one tier is better: Consider the case when I have five machines, and I use all five to host both my presentation and business tiers. In comparison, if I use two of these for my presentation tier, and three for my business tier, then I still have the same compute power, but now have to contend with the additional overhead of marshal/unmarshal, and latency. I’m hence better off with the single tier in such a case.

All said though, while a physical separation improves scale-out capability and security, it does impose overheads due to the network. The design for tiers needs to take into account the communication between tiers – too chatty, and performance degrades rapidly. The choice of protocol is equally important – the protocol of communication should be the most lightweight, and be as native as possible – so if both the web pages and the business logic components are built on the .Net stack, then a NetTcp binding is more suitable than a Http-based binding.


Tuesday, November 22, 2011

What is HTTP multipart request?


A HTTP multipart request is a type of HTTP request that a HTTP client construct to send file and data to the server.


Sunday, November 20, 2011

Synchronizing a HashMap


How to make hashmap operations synchronized?

For JDK 5 or after, we can use ConcurrentHashMap . This is an efficient implementation of a concurrent hash map using different locks for different portions of the HashMap . This reduces the contention of the lock and hence increase throughput tremendously as compared to a synchronized Map.

For JDK versions before JDK5 there is a back port of the same, if we do not want to use that, then we can use Collections.synchronizedMap() method to create a synchronized map. The new map will be backed with the original map and all the access will be synchronized on a single monitor. Also, we have to do external synchronization while iterating over the map entries.


Simple SAX parser example (count number of elements in an xml file)


Example Xml File :



<?xml version = "1.0" ?>

<Employees>



<Employee>

<Emp_Id> 1 </Emp_Id>

<Emp_Name> Bob </Emp_Name>

<Emp_E-mail> bob@hotmail.com </Emp_E-mail>

</Employee>



<Employee>

<Emp_Id> 2 </Emp_Id>

<Emp_Name> Nick </Emp_Name>

<Emp_E-mail> nick@yahoo.com </Emp_E-mail>

</Employee>



<Employee>

<Emp_Id> 3 </Emp_Id>

<Emp_Name> John </Emp_Name>

<Emp_E-mail> john@gmail.com </Emp_E-mail>

</Employee>



</Employees>

Java code to parse the above xml file and provides the elements count

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;

public class ElementCount{
int startTag = 0;
public static String ele;
public static void main(String args[])throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter XML file name:");
String xmlFile = bf.readLine();
File file = new File(xmlFile);
if (file.exists()){
System.out.print("Enter tag name for which the count should be calculated:");
ele = bf.readLine();
ElementCount tagCount = new ElementCount(xmlFile);
}
else{
System.out.println("File not found!");
}
}
public ElementCount(String str){
try{
SAXParserFactory parserFact = SAXParserFactory.newInstance();
SAXParser parser = parserFact.newSAXParser();
DefaultHandler dHandler = new DefaultHandler(){
public void startElement(String uri, String name, String element,
Attributes atri)throws SAXException{
if (element.equals(ele)){
startTag++;
}
}
public void endDocument(){
System.out.println("Total elements: " + startTag);
}
};
parser.parse(str,dHandler);
}
catch (Exception e){
e.printStackTrace();
}
}
}


What is a constructor and difference between this and super


A constructor is a special type of function that gets called every time you initialize a class, constructor has the same name as class name. Constructor has no return type not even void. We can pass the parameters to the constructor.

-this() is used to invoke a constructor of the same class.

-super() is used to invoke a super class constructor.

Constructor is called immediately after the object is created before the new operator completes.

For example, say you have this class called Person:
class Person
{
public Person ()
{
Console.WriteLine("We're making a new person");
}
}

Now you can create a new object of type Person, like this:
Person Tim= new person();

The program will write the line "We're making a new person" to the screen.

  • Constructor can use the access modifiers public, protected, private or have no access modifier
  • Constructor can not use the modifiers abstract, static, final, native, synchronized or strictfp
  • Constructor can be overloaded, we cannot override.
  • You cannot use this() and Super() in the same constructor.
  • You can not have both super() and this() invocation in the same constructor.
  • Either super() or this() should be the first statement in the constructor.


What is the difference between SAX and DOM parsers?


DOM Parser:

  1. A DOM (Document Object Model) parser creates a tree structure in memory from an input document and then waits for requests from client.
  2. A DOM parser always serves the client application with the entire document no matter how much is actually needed by the client.
  3. A DOM parser is rich in functionality. It creates a DOM tree in memory and allows you to access any part of the document repeatedly and allows you to modify the DOM tree. But it is space inefficient when the document is huge, and it takes a little bit longer to learn how to work with it.

SAX Parser:

  1. A SAX (Simple API for XML) parser does not create any internal structure. Instead, it takes the occurrences of components of an input document as events, and tells the client what it reads as it reads through the input document.
  2. A SAX parser serves the client application always only with pieces of the document at any given time.
  3. A SAX parser, however, is much more space efficient in case of a big input document (because it creates no internal structure). What’s more, it runs faster and is easier to learn than DOM parser because its API is really simple. But from the functionality point of view, it provides a fewer functions, which means that the users themselves have to take care of more, such as creating their own data structures.


What are the differences between finalize(), final and finally


  • finalize() – method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.
  • finally – The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. It allows the programmer to avoid having clean up code accidentally bypassed by a return, continue, or break. Keeping the clean up code in a finally block is always a good practice, even when no exceptions are anticipated.
  • final – This is useful in several ways...
When it is used with variable declaration, it becomes constant
When it is used with method, the method cant be overridden by the child class
When it is used with the class, the class cant have child classes.


What are the differences between HashMap and Hashtable?


Both provide key-value access to data. The Hashtable is one of the original collection classes in Java. HashMap is part of the new Collections Framework, added with Java 2, v1.2.

The key difference between the two is that access to the Hashtable is synchronized on the table while access to the HashMap isn't. You can add it, but it isn't there by default.

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

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


Tuesday, November 15, 2011

Java Faq


differentiate between Java Bean and Enterprise Java Bean?

Java Bean as is a plain java class with member variables and getter setter methods. Java Beans are defined under JavaBeans specification as Java-Based software component model. which lets in the features like introspection, customization, events, properties and persistence.

What is binding (JSF) ?

Wiring UI components to back-end data sources such as backing bean properties.

What is J2EE?

J2EE is a Java 2 Enterprise Edition. J2EE is an environment for developing and deploying enterprise applications. J2EE specification is defined by Sun Microsystems Inc. The J2EE platform is lies of a set of services, application programming interfaces (APIs), and protocols, which provides the functionality necessary for developing multi-tiered, web-based applications. The J2EE platform is one of the richest platform for the development and deployment of enterprise applications.

What do you understand by a J2EE module?

A J2EE module is a software building block that consists of one or more than J2EE components of the same container type along with one deployment descriptor of that type. J2EE specification specifies four characters of modules: a) Web module b) EJB module c) resource adapter d) application client and Modules can also be assembled into J2EE applications.

What is J2EE component?

J2EE component is a collected functional software unit supported by a container and configurable at deployment time. The J2EE specification shows the following J2EE component part: Application clients and applets that run on the client machine. Java servlet and JavaServer Pages (JSP) technology are Web components that run on the server machine. Enterprise JavaBeans (EJB) (enterprise beans) are business components that run on the server.

What is bean-managed transaction ?

Transaction whose boundaries are defined by an enterprise bean.

What is binding (XML) ?

Generating the code needed to process a well-defined portion of XML data.

What is build file ?

The XML file that contains one or more asant targets.

What is business logic ?

The code that implements the functionality of an application.

What is business method ?

A method of an enterprise bean that implements the business logic or rules of an application.

What is callback methods ?

Component methods called by the container to notify the component of important events in its life cycle.

What is caller principal ?

It is principal that identifies the invoker of the enterprise bean method.

What is caller ?

Same as caller principal.

What are the components of web module?

There are the following modules: a) Java classes b) JSP files c) gif and html files and d) web component deployment descriptors

Differentiate .ear, .jar and .war files?

These files are created for different uses .These files are only zipped file using java jar tool. Here is the description of these files: .ear files: The .ear file comprises the EJB modules of the application. .jar files: are with the .jar extension. The .jar files comprises the libraries, resources and accessories files like property files. .war files: are with the .war extension. The war file comprises the web application that can be deployed on the any servlet/jsp container. The .war file contains jsp, html, JavaScript and other files for necessary for the development of web applications.

Differentiate between Session Bean and Entity Bean?

Session Bean: Session is one of the EJB and it shows a single client inside the Application Server. Stateless session bean is easy to develop and its efficient. As compare to entity beans session beans needs few server resources. Entity Bean: An entity bean represents persistent global data from the database. Entity beans data are stored into database.

Why J2EE is suitable for the development of distributed multi-tiered enterprise applications?

J2EE application program allows the developers to design and implement the business logic into components according to business requirement. J2EE architecture allows the development of multi-tired applications and the developed applications can be installed on different machines depending on the tier in the multi-tiered J2EE environment . The J2EE application parts are: a) Web-tier components. b) Client-tier components . c) Business-tier components . d) Enterprise information system (EIS)-tier software.

what is a container?

containers are the interface between a component and the low-level platform specific functionality that supports the component.
What services provided by a container?

The services provided by container are as follows: a) Transaction management for the bean b) Instance pooling for the bean c) Persistence d) Remote access e) Lifecycle management f) Database-connection pooling g) Security

What are types of J2EE clients?

a) Java-Web Start b) clients Applets c) Web applications d) Wireless clients

What is Deployment Descriptor?

A deployment descriptor is simply an XML(Extensible Markup Language) file with the extension of .xml.. Application servers reads the deployment descriptor to deploy the components contained in the deployment unit. As in: ejb-jar.xml file is used to describe the setting of the EJB.

What is JTA and JTS?

JTA stands for Java Transaction API and JTS stands for Java Transaction Service. JTA provides a standard interface which allows the developers to demarcate transactions . JTA is a high level transaction interface used by the application code to control the transaction.

What is JAXP?

The Java API for XML Processing (JAXP) enables applications to parse and transform XML documents independent of a particular XML processing implementation.

What is J2EE Connector architecture?

J2EE Connector Architecture (JCA) is a Java-based technology solution for connecting application servers and enterprise information systems (EIS) as part of enterprise application integration (EAI) solutions.

Differentiate JTS and JTA?

JTS shows the implementation of a Java transaction manager. JTS specifies the implementation of a Transaction Manager which supports the Java Transaction API (JTA) 1.0. The JTA shows an architecture for building transactional application servers and defines a set of interfaces for various components of this architecture. The components are: the application, resource managers, and the application server.

Can Entity Beans have no create() methods?

Entity Beans have no create() method, when entity bean is not used to store the data in the database. In this case entity bean is used to retrieve the data from database.

What are the call back methods in Session bean?

Callback methods are called by the container to notify the important events to the beans in its life cycle. The callback methods example are ejbCreate(), ejbPassivate(), and ejbActivate().

What is bean managed transaction?

In the EJB transactions can be maintained by the container or developer can write own code to maintain the transaction. If a developer doesn�t want a Container to manage transactions, developer can write own code to maintain the database transaction.

What are transaction isolation levels in EJB?

There are four levels : * Serializable * Committed Read * Repeatable Read * Uncommitted Read

What is "application client" ?

Application clients have access to some J2EE platform APIs.

What is "application client container" ?

A container that supports application client components.

What is "application client module" ?

A software unit that have one or more classes and an application client deployment descriptor.

What is "application component provider" ?

A vendor that provides the Java classes that implement components' methods, JSP page definitions, and any required deployment descriptors.

What are "application configuration resource file" ?

An XML file used to configure resources for a Java Server Faces application.

What is "archiving" ?

Process of saving the state of an object and restoring it.

What is "asant" ?

A Java-based build tool that can be extended using Java classes. The configuration files are XML-based, calling out a target tree where various tasks get executed.

What is "attribute"?

A qualifier on an XML tag that provides additional information to the client .

What is authentication ?

Process that verifies the identity of a user, device, or other entity in a computer system.

What is authorization ?

The process by which access to a method or resource is determined.

What is authorization constraint ?

An rule that determines who is permitted to access a Web resource collection.

What is B2B ?

B2B stands for Business-to-business process.

What is backing bean ?

The backing bean defines properties for the components on the page and methods that perform processing for the component.

What is basic authentication ?

An authentication mechanism in which a Web server authenticates an entity via a user name and password obtained using the Web application's built-in authentication mechanism.

What is bean-managed persistence ?

The mechanism whereby data transfer between an entity bean's variables and a resource manager is managed by the entity bean.


Monday, October 31, 2011

How to prevent Cross-site request forgery (CSRF) Attacks


Make sure form submissions that cause server-side changes use your own forms. There are two ways you can do this:

Check the referrer header. If it is not present, or if it does not show the correct URL as the referrer, reject the submission. This has the advantage of being simple and sane, but the disadvantage that users who have told their browsers to omit the referrer header (out of concern for privacy) or lie about the referrer (in order to gain access to porn sites that use the referrer for the wrong purpose) will have trouble. This strategy doesn't work if the form uses GET and the page can contain user-generated content with links.

Include a hidden field in the form and check its value when the form is submitted. A simple scheme is to use an MD5 hash of the login cookie, some information about the form, and a secret on the server. Another possibility is to use a randomly generated one-time key for every form you serve, assuming you have a sufficiently unpredictable source of random numbers. This has the disadvantage of making it unsafe for users to save the HTML for forms and upload them to, say, bug databases.


What is Cross-site request forgery (CSRF)


A Cross-site request forgery hole is when a malicious site can cause a visitor's browser to make a request to your server that causes a change on the server. The server thinks that because the request comes with the user's cookies, the user wanted to submit that form.

Depending on which forms on your site are vulnerable, an attacker might be able to do the following to your victims:

Log the victim out of your site. (On some sites, "Log out" is a link rather than a button!)
Change the victim's site preferences on your site.
Post a comment on your site using the victim's login.
Transfer funds to another user's account.
Attacks can also be based on the victim's IP address rather than cookies:

Post an anonymous comment that is shown as coming from the victim's IP address.
Modify settings on a device such as a wireless router or cable modem.
Modify an intranet wiki page.
Perform a distributed password-guessing attack without a botnet. (This assumes they have a way to tell whether the login succeeded, perhaps by submitting a second form that isn't protected against CSRF.)
CSRF attacks usually involve JavaScript to submit the cross-site form automatically. It is possible for a malicious site to make a user submit a form to another site even without JavaScript, however: form fields can be hidden and buttons can be disguised as links or scrollbars.


Tuesday, November 9, 2010

Simplifying Social Network Interactions with Spring


There is a good article on springsource which describes how Spring is Simplifying Social Network Interactions Socializing Spring Applications


Saturday, October 30, 2010

SocialAuth - Java Library for oAuth and OpenID providers


SocialAuth is a Java library for you if your web application requires:
  • Authenticating users through external oAuth providers like Yahoo, Google, Twitter, Facebbook etc as well as through OpenID providers like myopenid.com.
  • Easy user registration. All you need to do is create a page where users can click on buttons for the above providers or other supported providers. Just call SocialAuth and you can get all their profile details.
  • Importing contacts from Google, Yahoo or Hotmail. Support for importing friends from Facebook and followers from Twitter coming soon !

Why SocialAuth?
There are so many libraries out there which implement OpenID and oAuth, so why another library? There many practical challenges that we faced while doing the implementation of above use cases. None of them is insurmountable but the developer could spend a couple of weeks solving these, which we actually did and hence decided to make things better for the community.
  • There are many libraries for implementing Open ID and many for implementing oAuth. It becomes a difficult exercise to choose one that will do the integration quickly with the providers you want.
  • Some libraries do not implement all the features and it becomes known only in the later stages of implementation – for example we found out that openid4java does not implement the hybrid protocol. We also found out that it is not easy to integrate dyuproject library.
  • Even after implementing using the library, it does not work out of the box for all providers. There are always certain things specific to a certain provider. For example the scopes are different as well as some steps in authorization may be different.
  • Getting the actual data, for example contacts of a user is out of the scope of these protocols and hence most libraries do not implement this functionality.
So what we implemented is a wrapper that leverages these existing libraries, and works out of the box without requiring you to face the above challenges. You get the same interface to deal with integration of every provider.

More details : http://www.theserverside.com/news/thread.tss?thread_id=61205


Basic Java Questions(Core Java Faq) part 3


What is Constructor?
*       A constructor is a special method whose task is to initialize the object of its class.
*       It is special because its name is the same as the class name.
*       They do not have return types, not even void and therefore they cannot return values.
*       They cannot be inherited, though a derived class can call the base class constructor.
*       Constructor is invoked whenever an object of its associated class is created.

How does the Java default constructor be provided?
If a class defined by the code does not have any constructor, compiler will automatically provide one no-parameter-constructor (default-constructor) for the class in the byte code. The access modifier (public/private/etc.) of the default constructor is the same as the class itself.

Can constructor be inherited?
No, constructor cannot be inherited, though a derived class can call the base class constructor.

What are the differences between Contructors and Methods?

Constructors
Methods
Purpose Create an instance of a class Group Java statements
Modifiers Cannot be abstract, final, native, static, or synchronized Can be abstract, final, native, static, or synchronized
Return Type No return type, not even void void or a valid return type
Name Same name as the class (first letter is capitalized by convention) -- usually a noun Any name except the class. Method names begin with a lowercase letter by convention -- usually the name of an action
this Refers to another constructor in the same class. If used, it must be the first line of the constructor Refers to an instance of the owning class. Cannot be used by static methods.
super
Calls the constructor of the parent class. If used, must be the first line of the constructor
Calls an overridden method in the parent class
Inheritance
Constructors are not inherited
Methods are inherited

How are this() and super() used with constructors?
*       Constructors use this to refer to another constructor in the same class with a different parameter list.
*       Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.

What are the differences between Class Methods and Instance Methods?
Class Methods
Instance Methods
Class methods are methods which are declared as static. The method can be called without creating an instance of the class
Instance methods on the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword.
Instance methods operate on specific instances of classes.
Class methods can only operate on class members and not on instance members as class methods are unaware of instance members.
Instance methods of the class can also not be called from within a class method unless they are being called on an instance of that class.
Class methods are methods which are declared as static. The method can be called without creating an  instance of the class.
Instance methods are not declared as static.

How are this() and super() used with constructors?
*       Constructors use this to refer to another constructor in the same class with a different parameter list.
*       Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.

What are Access Specifiers?
One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. Java allows you to control access to classes, methods, and fields via so-called access specifiers..

What are Access Specifiers available in Java?
Java offers four access specifiers, listed below in decreasing accessibility:
*       Public- public classes, methods, and fields can be accessed from everywhere.
*       Protected- protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package.
*       Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.
*       Private- private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses.
 Situation 
 public 
 protected 
 default 
 private 
 Accessible to class
 from same package? 
yes
yes
yes
no
 Accessible to class
 from different package? 
yes
 no, unless it is a subclass 
no
no

What is final modifier?
The final modifier keyword makes that the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method.
*       final Classes- A final class cannot have subclasses.
*       final Variables- A final variable cannot be changed once it is initialized.
*       final Methods- A final method cannot be overridden by subclasses.

What are the uses of final method?
There are two reasons for marking a method as final:
*       Disallowing subclasses to change the meaning of the method.
*       Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.

What is static block?
Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main method the static block will execute.

What are static variables?
Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared by using the static keyword as a modifier.
              static type  varIdentifier;
where, the name of the variable is varIdentifier and its data type is specified by type.
Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables.

What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

What are static methods?
Methods declared with the keyword static as modifier are called static methods or class methods. They are so called because they affect a class as a whole, not a particular instance of the class. Static methods are always invoked without reference to a particular instance of a class.
Note:The use of a static method suffers from the following restrictions:
*       A static method can only call other static methods.
*       A static method must only access static data.
*       A static method cannot reference to the current object using keywords super or this.
*       reference to the current object using keywords super or this.


How to add a captcha to JSP(Adding captcha)



A captcha is an image with some modified text on it. They're usually used to prevent automated scripts from accessing certain parts of your site. For example, you'd add a captcha on a wiki edit page or a forum reply page so a spammer doesn't make a bunch of fake content on your site.
This page will teach you how to add a captcha to your site by using reCAPTCHA. reCAPTCHA is a free (and ad-free) widget that will generate captchas for you.
First things first; you will need to sign up for a reCAPTCHA account. Don't worry, this is very straightforward. Sign up for an account here:http://recaptcha.net/whyrecaptcha.html. After you sign up, you will be given a public and a private key. Write these down because you'll need them later.
The second thing you'll want to do is download a reCAPTCHA library that simplifies using the reCAPTCHA API in java. You can download that here:http://code.google.com/p/recaptcha/downloads/list. Download the zip that says "for Java". Extract the jar and put it in your classpath.
Now for some code. Add this to your ActionBean:
public String getReCaptchaHtml() {
ReCaptcha recaptcha = createReCaptcha();
return recaptcha.createRecaptchaHtml("You did not type the captcha correctly", new Properties());
}

private ReCaptcha createReCaptcha() {
String publicKey = //your public key
String privateKey = //your private key
return ReCaptchaFactory.newReCaptcha(publicKey, privateKey, true);
}
With this, we can add the reCAPTCHA widget to our JSP like so:
${actionBean.reCaptchaHtml}
But one thing remains: We don't have a way to tell if the user submitted the correct value. Lets assume the method that gets called on submit is named "submit". Here's how you would add a validation method that ensures that the captcha code was entered correctly:
@ValidationMethod(on = "submit")
public void captchaValidation(ValidationErrors errors) {
ReCaptchaResponse response = createReCaptcha().checkAnswer(context.getRequest().getRemoteAddr(),
context.getRequest().getParameter(
"recaptcha_challenge_field"),
context.getRequest().getParameter(
"recaptcha_response_field"));
if (!response.isValid()) {
errors.add(
"Captcha", new SimpleError("You didn't type the captcha correctly!"));
}
}
This will give you a completely functional captcha.