Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, September 2, 2010

Java Annotations Introduction

Annotations
Annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate.

Annotations have a number of uses, among them:
  • Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
  • Compiler-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
  • Runtime processing — Some annotations are available to be examined at runtime.
There are two types of annotations available:
  • Simple annotations: These are the basic types supplied with Tiger, which you can use to annotate your code only; you cannot use those to create a custom annotation type.
  • Meta-annotations: These are the annotation types designed for annotating annotation-type declarations. Simply speaking, these are called the annotations-of-annotations.
An annotation is the meta-tag that you will use in your code to give it some life.
Annotation type is used for defining an annotation.

Annotation Types
An
Annotation type definition takes an "at" (@) sign, followed by the interface keyword plus the annotation name.
 On the other hand, an annotation takes the form of an "at" sign (@), followed by the annotation type.

There are three annotation types:
  1. Marker: Marker type annotations have no elements, except the annotation name itself.
  2. Single-Element: Single-element, or single-value type, annotations provide a single piece of data only. This can be represented with a data=value pair or, simply with the value (a shortcut syntax) only, within parenthesis.
  3. Full-value or multi-value: Full-value type annotations have multiple data members. Therefore, you must use a full data=value parameter syntax for each member.

Example to Define an Annotation (Annotation type)

                public @interface MyAnnotation {

                          String doSomething();   
               }
Singel element Usage:
           MyAnnotation (doSomething="What to do") 
               public void mymethod() { .... }
multi-value  Usage
                     @MyAnnotation (doSomething="What to do", count=1,  date="09-09-2005")    
                    public void mymethod() {        ....     }  
Simple Annotations
There are three annotation types that are predefined by the language specification itself:        

      1. Deprecated
      2. Override
      3. Suppresswarnings
         @Deprecated annotation indicates that the marked element is deprecated and should no longer be used. The compiler generates a  warning  whenever a program uses a method, class, or field with the @Deprecated annotation.
        The Javadoc tag starts with a lowercase "d" and the annotation starts with an uppercase "D".    

 // Javadoc comment follows       
 /**        
 * @deprecated        
 * explanation of why it was deprecated        
 */       
 @Deprecated       
        static void deprecatedMethod() { }  
        @Override annotation informs the compiler that the element is meant to override an element declared in a superclass .   

 // mark method as a superclass method   
 // that has been overridden      
 @Override       
 int overriddenMethod() { }   
        @SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate.

          // use a deprecated method and tell      
   // compiler not to generate a warning      
   @SuppressWarnings("deprecation")       
   void useDeprecatedMethod() {           
    objectOne.deprecatedMethod(); 
    //deprecation warning - suppressed      
   }   

Meta-Annotations

Meta-annotations, which are actually known as the annotations of annotations, contain four types. These are:
  • Target
  • Retention
  • Documented
  • Inherited
The target annotation indicates the targeted elements of a class in which the annotation type will be applicable. It contains the following enumerated types as its value:
  • @Target(ElementType.TYPE)—can be applied to any element of a class
  • @Target(ElementType.FIELD)—can be applied to a field or property
  • @Target(ElementType.METHOD)—can be applied to a method level annotation
  • @Target(ElementType.PARAMETER)—can be applied to the parameters of a method
  • @Target(ElementType.CONSTRUCTOR)—can be applied to constructors
  • @Target(ElementType.LOCAL_VARIABLE)—can be applied to local variables
  • @Target(ElementType.ANNOTATION_TYPE)—indicates that the declared type itself is an annotation type
The retention annotation indicates where and how long annotations with this type are to be retained. In simple it indicates the scope of the annotation Type.
There are three values:
  • RetentionPolicy.SOURCE—Annotations with this type will be by retained only at the source level and will be ignored by the compiler
  • RetentionPolicy.CLASS—Annotations with this type will be by retained by the compiler at compile time, but will be ignored by the VM
  • RetentionPolicy.RUNTIME—Annotations with this type will be retained by the VM so they can be read only at run-time
The documented annotation indicates that an annotation with this type should be documented by the javadoc tool. By default, annotations are not included in javadoc. But if @Documented is used, it then will be processed by javadoc-like tools and the annotation type information will also be included in the generated document.

Inherited annotation

It is important to understand the rules relating to inheritance of annotations, as these have a bearing on join point matching based on the presence or absence of annotations.
By default annotations are not inherited.The annotation used on the super class doesn't get inherited to sub class,unless the annotation (@MyAnnotation used in the following example)used on super class has the @Inherited meta-annotation.
Annotation are not be inheritable in case of  extending Interface even if they have
@Inherited meta-annotation.

@MyAnnotation    
 class Super {      
  @Oneway public void foo() {}    
 }
 class Sub extends Super {
  public void foo() {}
 }    
Then Sub does not have the MyAnnotation annotation, and Sub.foo() is not an @Oneway method, despite the fact that it overrides Super.foo() which is.
If an annotation type @MyAnnotation has the meta-annotation @Inherited then an annotation of that type on a class will cause the annotation to be inherited by sub-classes. So, in the example above, if the MyAnnotation type had the @Inherited attribute, then Sub would have the MyAnnotation annotation.
@Inherited annotations are not inherited when used to annotate anything other than a type.
 A type that implements one or more interfaces never inherits any annotations from the interfaces it implements(they are inheritable only if subclass extends another super class).


        Every compiler warning belongs to a category. The Java Language Specification lists two categories: "deprecation" and "unchecked." The  "unchecked" warning can occur when interfacing with legacy code written before the advent of generics .

         To suppress more than one category of warnings, use the following syntax:
 @SuppressWarnings({"unchecked", "deprecation"}) 
 
Annotation Processing:
            The more advanced uses of annotations include writing an annotation processor that can read a Java program and take actions based on its             annotations.
            To make annotation information available at runtime, the annotation type itself must be annotated with @Retention(RetentionPolicy.RUNTIME),
            as follows:
 import java.lang.annotation.*;     
 @Retention(RetentionPolicy.RUNTIME)   
 @interface AnnotationForRuntime {       
  // Elements that give information              
  // for runtime processing       
 }    

Resources


4)Java Custom Annotations (Has good Example on Inherited meta-annotation)
http://technicalmumbojumbo.wordpress.com/2008/01/13/java-custom-annotations/

**********************************************************************************************************************************************

Tuesday, April 13, 2010

Formatting(Precision) Java Double /Float Decimal Digits

Formatting( Precision ) Java Double Decimal Digits

Formatters converts a floating point/double value  to a string  with a specified number  of decimals.

For formatting the decimal part of double/Float we can use NumberFormat or DecimalFormat .

The difference between them is that
        NumberFormat is an abstract class.
        DecimalFormat is a concrete implementation of NumberFormat.

Using NumberFormat:

NumberFormat is the abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. NumberFormat also provides methods for determining which locales have number formats, and what their names are.
Number formats are generally not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally. 

    NumberFormat nfrmtr = NumberFormat.getNumberInstance();
    nfrmtr.setGroupingUsed(false);
    nfrmtr.setMaximumFractionDigits(2);
    nfrmtr.setMinimumFractionDigits(2);
    double dval = 0.0;
    System.out.println(nfrmtr.format(dval));

Using DecimalFormat:

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized. 

As DecimalFormat is implementing NumberFormat Class we can use the functions available in NumberFormat.

    DecimalFormat dfrmtr = new DecimalFormat("###.##");
    double dval = 0.0;
    System.out.println(dfrmtr.format(dval));     

Sample Program :

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class DecimalFormatter {
    public static void main(String srgs[]){
   
        DecimalFormat dfrmtr = new DecimalFormat("###.##");

        NumberFormat nfrmtr = NumberFormat.getNumberInstance();
        nfrmtr.setGroupingUsed(false);
        nfrmtr.setMaximumFractionDigits(2);
        dfrmtr.setMinimumFractionDigits(2);
       
        double dval = 0.0;
        for (int i = 0; i < 10; i++)
        {
            dval += 0.111;
            System.out.println(dval+" "+dfrmtr.format(dval)+"  "+nfrmtr.format(dval));           
        }
    }
}

Source NumberFormat
Source DecimalFormat

Friday, January 29, 2010

Comparison of Java ==, .equals(), compareTo(), and compare()

Source & Full Article


When you really need to know if two references are identical, use ==. But when you need to know if the objects themselves (not the references) are equal, use the  equals() method.


If you don't override a class's equals() method, you won't be able to use those objects as a key in a hashtable and you probably won't get accurate Sets, such that there are no conceptual duplicates.


Equality comparison: One way for primitives, Four ways for objects



Comparison Objects
a == b, a != b
Compares references, not values. The use of == with object references is generally limited to the following:
  • Comparing to see if a reference is null.
  • Comparing two enum values. This works because there is only one object for each enum constant.
  • You want to know if two references are to the same object
a.equals(b)
Compares values for equality. Because this method is defined in the Object class, from which all other classes are derived, it's automatically defined for every class. However, it doesn't perform an intelligent comparison for most classes unless the class overrides it. It has been defined in a meaningful way for most Java core classes. If it's not defined for a (user) class, it behaves the same as ==.
It turns out that defining equals() isn't trivial; in fact it's moderately hard to get it right, especially in the case of subclasses. The best treatment of the issues is in Horstmann's Core Java Vol 1. [TODO: Add explanation and example]
a.compareTo(b)
Comparable interface. Compares values and returns an int which tells if the values compare less than, equal, or greater than. If your class objects have a natural order, implement the Comparable<T> interface and define this method. All Java classes that have a natural ordering implement this (String, Double, BigInteger, ...).
compare(a, b)
Comparator interface. Compares values of two objects. This is implemented as part of the Comparator<T>sort() or for use by sorting data structures such as TreeMap and TreeSet. You might want to create a Comparator object for the following. interface, and the typical use is to define one or more small utility classes that implement this, to pass to methods such as
  • Multiple comparisons. To provide several different ways to sort something. For example, you might want to sort a Person class by name, ID, age, height, ... You would define a Comparator for each of these to pass to the sort() method.
  • System class. To provide comparison methods for classes that you have no control over. For example, you could define a Comparator for Strings that compared them by length.
  • Strategy pattern. To implement a strategy pattern, which is a situation where you want to represent an algorithm as an object that you can pass as a parameter, save in a data structure, etc.
If your class objects have one natural sorting order, you may not need this.

Monday, January 18, 2010

Definitions of JRE JDK JVM J2SE J2EE

Java SE Overview

There are two principal products in the Java SE platform family: Java SE Runtime Environment (JRE) and Java Development Kit (JDK).



Java Runtime Environment (JRE)
The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. In addition, two key deployment technologies are part of the JRE: Java Plug-in, which enables applets to run in popular browsers; and Java Web Start, which deploys standalone applications over a network. It is also the foundation for the technologies in the Java 2 Platform, Enterprise Edition (J2EE) for enterprise software development and deployment. The JRE does not contain tools and utilities such as compilers or debuggers for developing applets and applications.
Java Development Kit (JDK)
The JDK is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications. The conceptual diagram above illustrates all the component technologies in Java SE platform and how they fit together.

Java SE API

The Java SE application programming interface (API) defines the manner by which an applet or application can make requests to and use the functionality available in the compiled Java SE class libraries. (The Java SE class libraries are also part of the Java SE platform.)
The Java SE API consists of core technologies, Desktop (or client) technologies, and other technologies.
  • Core components provide essential functionality for writing powerful enterprise-worthy programs in key areas such as database access, security, remote method invocation (RMI), and communications.
  • Desktop components add a full range of features to help build applications that provide a rich user experience – deployment products such as Java Plug-in, component modeling APIs such as JavaBeans, and a graphical user interface.
  • Other components round out the functionality.
Java Virtual Machine
The Java Virtual Machine is responsible for the hardware- and operating system-independence of the Java SE platform, the small size of compiled code (bytecodes), and platform security.
Java Platform Tools
The Java SE platform works with an array of tools, including Integrated Development Environments (IDEs), performance and testing tools, and performance monitoring tools.

Java EE Overview

The Java 2 Platform, Enterprise Edition (J2EE) defines the standard for developing multitier enterprise applications. The J2EE platform simplifies enterprise applications by basing them on standardized, modular components, by providing a complete set of services to those components, and by handling many details of application behavior automatically, without complex programming.

The J2EE platform takes advantage of many features of the Java 2 Platform, Standard Edition (J2SE), such as "Write Once, Run Anywhere" portability, JDBC API for database access, CORBA technology for interaction with existing enterprise resources, and a security model that protects data even in internet applications. Building on this base, the Java 2 Platform, Enterprise Edition adds full support for Enterprise JavaBeans components, Java Servlets API, JavaServer Pages and XML technology. The J2EE standard includes complete specifications and compliance tests to ensure portability of applications across the wide range of existing enterprise systems capable of supporting the J2EE platform. In addition, the J2EE specification now ensures Web services interoperability through support for the WS-I Basic Profile.
The J2EE specification also supports emerging Web Services technologies through inclusion of the WS-I Basic Profile . WS-I Basic Profile compliance means that the developers can build applications on the J2EE platform as Web services that interoperate with Web services from non-J2EE compliant environments.

With simplicity, portability, scalability, and legacy integration, the J2EE platform is the platform for enterprise solutions.

For more info
                    Source(J2SE) sun.com
                    Source(J2EE) sun.com

Thursday, December 24, 2009

Java’s String pooling


A string pool is a collection of references to String objects.
Strings, even though they are immutable, are still objects like any other in Java. Objects are created on theheap and Strings are no exception.
So, Strings that are part of the "String Literal Pool" still live on the heap, but they have references to them from the String Literal Pool.

When a .java file is compiled into a .class file, any String literals are noted in a special way, just as all constants are. When a class is loaded (note that loading happens prior to initialization), the JVM goes through the code for the class and looks for String literals. When it finds one,  it checks to see if an equivalent String is already referenced from the heap. If not, it creates a String instance on the heap and stores a reference to that object in the constant table. Once a reference is made to that String object, any references to that String literal throughout your program are simply replaced with the reference to the object referenced from the String Literal Pool.
If you use the new keyword, a new String object will be created. Note that objects are always on the heap - the string pool is not a separate memory area that is separate from the heap.
The string pool is like a cache. If you do this:
String s = "abc";
String p = "abc";
then the Java compiler is smart enough to make just one String object, and s and p will both be referring to that same String object. If you do this:
String s = new String("abc");
then there will be one String object in the pool, the one that represents the literal "abc", and there will be a separate String object, not in the pool, that contains a copy of the content of the pooled object. Since String is immutable in Java, you're not gaining anything by doing this; calling new String("literal") never makes sense in Java and is unnecessarily inefficient.
Note that you can call intern() on a String object. This will put the String object in the pool if it is not already there, and return the reference to the pooled string. (If it was already in the pool, it just returns a reference to the object that was already there). See the API documentation for that method for more info.
Java String intern Function
public String intern() 
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.


Friday, November 27, 2009

Servlet Container & Request processing

Why we need Container for Servlets?

    Servlets don't have main() method,They run under
    control of another java application called container.
    Ex: Tomcat

When Server gets request for servlet the server handovers
the request to container in which Servlet is deployed.

In simple "Container manages and runs the Servlet".

Advantages of using Container:

Communication
The container provides easy way of communication between servlets and web server.

Life-cycle Management:
The container controls the life cycle of servlet.
    Loading classes.
    Instantiating and initializing the servlet.
    Invoking servet methods ie  like init service & destroy .
    Destroying servlets for garbage collection ( Resource management ).

Threading support:
Container automatically creates a new java thread for every
request it receives.The thread dies when servlet completes
running the HTTP service method.
  
Security:   
    Container provides XML based configuration for security configuration and
modification of servlet with out changing the java code of servlet.
  
JSP support:
    Container takes care of converting JSP code into java.      

Handling the request:

When user request for Dynamic content
1)Container gets request  for servlet.
2)Container creates HTTPServletResponse and HTTPResponse objects.
3)Based on the requested URL Container maps the request to a  sevlet
and creates a thread for the request  and  passes the references of
HTTPServletResponse and HTTPResponse objects.
4)Container calls the service(),Which in-turn calls the doXXX()
methods based on the request type.
5)the doXXX() method constructs the dynamic page into HTTPResponse object.
6)When response is sent to client container deletes the objects and thread.

Thursday, November 19, 2009

Creating jasper reports in 4 simple steps


Download the jasper reports Lib and Source from here.
Intro:

    JasperReports is an open-source Java class library
    designed to aid developers with the task of adding
    reporting capabilities to Java applications.
    JasperReports is licensed under the Lesser GNU Public License (LGPL).
Features:
    It has flexible report layout.
    It is capable of presenting data textually or graphically.
    It allows developers to supply data in multiple ways.
    It can accept data from multiple datasources.
    It can generate watermarks.
    It can generate subreports.
    It is capable of exporting reports to a variety of formats.
Flow chart of Jasper Reports Creation
    We can Create Jasper report in Following four steps.


Create JRXML files:
    The first step is to create a report template
    as an XML file.Even though JasperReports'
    report templates are XML files,template filenames
    are given an extension of .jrxml.
    JasperReports XML templates are commonly referred to as JRXML files
Compile JRXML files to create Jasper File :
    JRXML files are compiled into a JasperReports
    native binary template.The resulting compiled
    template is commonly known as the Jasper
    file, and is typically saved to disk with a .jasper extension.
Fill The report:
    The Jasper file is then used to generate the final report,
    by providing it with its required data.
    This process is known as filling the report.
Display the report:
    Filled reports can be saved to disk in a JasperReports 

    native format. Reports saved in this format are known
    as JasperPrint files.
    JasperPrint file names have a .jrprint extension.
    JasperPrint files can be exported to other
    formats so that they can be opened with commonly
    available tools like PDF viewers and word processors.