Sunday, March 13, 2011

JAVA 7 Features


Virtul Machine

JSR 292: Support for dynamically-typed languages (InvokeDynamic)

VM and language extensions to support the implementation of dynamically-typed languages at performance levels near to that of the Java language itself

Strict class-file checking [NEW]
Per the Java SE 6 specification, class files of version 51 (SE 7) or later must be verified with the typechecking verifier introduced by JSR 202 in Java SE 6; the VM must not fail over to the old inferencing verifier

Language

JSR 334: Small language enhancements (Project Coin)

A set of small language changes intended to simplify common, day-to-day programming tasks:

1.      Strings in switch statements
2.      Automatic resource management
3.      Improved type inference for generic instance creation ("diamond")
4.      Simplified varargs method invocation,
5.      Better integral literals,
6.       Improved exception handling (multi-catch)

Core

Upgrade class-loader architecture

Modifications to the ClassLoader API and implementation to avoid deadlocks in non-hierarchical class-loader topologies

Method to close a URLClassLoader

A method that frees the underlying resources, such as open files, held by a URLClassLoader

Concurrency and collections updates (jsr166y)

A lightweight fork/join framework, flexible and reusable synchronization barriers, transfer queues, a concurrent-reference HashMap, and thread-local pseudo-random number generators

Internationalization

Unicode 6.0

Upgrade the supported version of Unicode to 6.0

Locale enhancement

Upgrade the java.util.Locale class to support IETF BCP 47 and UTR 35 (CLDR/LDML)

Separate user locale and user-interface locale

Upgrade the handling of locales to separate formatting locales from user-interface language locales, as is done on Vista and later versions of Windows

I/O and Networking

JSR 203: More new I/O APIs for the Java platform (NIO.2)

New APIs for filesystem access, scalable asynchronous I/O operations, socket-channel binding and configuration, and multicast datagrams

NIO.2 filesystem provider for zip/jar archives

A fully-functional and supported NIO.2 filesystem provider for zip and jar files

SCTP (Stream Control Transmission Protocol)

An implementation-specific API for the Stream Control Transmission Protocol on Solaris

SDP (Sockets Direct Protocol)

Implementation-specific support for reliable, high-performance network streams over Infiniband connections on Solaris and Linux

Use the Windows Vista IPv6 stack

Upgrade the networking code to use the Windows Vista IPv6 stack, when available, in preference to the legacy Windows stack

TLS 1.2

Add support for TLS 1.2, which was standardized in 2008 as RFC 5246

Security & Cryptography

Elliptic-curve cryptography (ECC)

A portable implementation of the standard Elliptic Curve Cryptographic (ECC) algorithms, so that all Java applications can use ECC out-of-the-box

JDBC

JDBC 4.1

Upgrade to JDBC 4.1 and Rowset 1.1

Client

XRender pipeline for Java 2D

A new Java2D graphics pipeline based upon the X11 XRender extension, which provides access to much of the functionality of modern GPUs

Create new platform APIs for 6u10 graphics features

Create new platform APIs for features originally implemented in the 6u10 release: Translucent and shaped windows, heavyweight/lightweight mixing, and the improved AWT security warning

Nimbus look-and-feel for Swing

A next-generation cross-platform look-and-feel for Swing

Swing JLayer component

Add the SwingLabs JXLayer component decorator to the platform

Web

Update the XML stack

Upgrade the JAXP, JAXB, and JAX-WS APIs to the most recent stable versions

Management

Enhanced JMX Agent and MBeans [NEW]

An implementation-specific enhanced JMX management agent, ported from JRockit, which makes it easier to connect to the platform MBean server through firewalls, together with a richer set of MBeans which expose additional information about the internal operation of the VM

Deferred to JDK 8 or later

JSR 294: Language and VM support for modular programming

Enhancements to the Java language and virtual-machine specifications to support modular programming, at both compile time and run time

JSR 308: Annotations on Java types

An extension to the Java annotation syntax to permit annotations on any occurrence of a type

JSR TBD: Language support for collections

Literal expressions for immutable lists, sets, and maps, and indexing-access syntax for lists and maps

JSR TBD: Project Lambda

Lambda expressions (informally, "closures") and defender methods for the Java programming language

Modularization (Project Jigsaw)

A simple, low-level module system focused upon the goal of modularizing the JDK, and the application of that system to the JDK itself

JSR 296: Swing application framework

An API to define the basic structure of a typical Swing application, thereby eliminating lots of boilerplate code and providing a much-improved initial developer experience

Swing JDatePicker component

Add the SwingLabs JXDatePicker component to the platform



Thursday, June 3, 2010

Singleton - Multiple Users [Thread Safe]

Following is the way by which we can use Singleton Design pattern for multiple users.

public class Singleton {
         private volatile static Singleton singleton; //volatile is needed so that multiple thread can reconcile the instance
         private Singleton(){
         }

         public static Singleton getSingleton(){ //synchronized keyword has been removed from here
         if(singleton = = null)
         {          //needed because once there is singleton available no need to aquire monitor again & again as it is costly
                synchronized(Singleton.class)
                {
                        //this is needed if two threads are waiting at the monitor at the time when singleton was getting instantiated
                      if(singleton==null)
                      {      
                              singleton= new Singleton();
                       }
                  }
          }
          return singleton;
    }
}

Thursday, May 13, 2010

wait(), notify() and notifyAll()

The wait(), notify() and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods.

Monday, May 10, 2010

Volatile Modifiers in Java

Volatile Modifier

       The volatile modifier requests the Java Virtual Machine to always access the shared copy of the variable so the its most current value is always read. If two or more threads access a member variable, and one or more threads might update that variable’s value, and all of the threads do not use synchronization to read and/or write the variable value, then that member variable must be declared volatile to ensure all threads should get the updated value.
       We will discuss the java volatile modifier using following example.
       In our example, we take two threads Thread T1 and Thread T2 accessing member variable x of class C and here Thread T1 is not using synchronization and Thread T2 uses synchronization. If Thread T2 updates value of variable x from 0 to 1. But if the variable x is not declared as volatile then meanwhile Thread T1 tried to access variable then it will get value of variable x as 0. But as variable x is updated to 1 by Thread T2, To avoid this mess the variable x should be declared as volatile so Thread T1 should get updated value 1.

Thursday, May 6, 2010

HashMap vs ConcurrentHashMap

Both HashMap and ConcurrentHashMap are inherits some characteristics of Hashtable. But they have some prominent differences in context with performance, scalability.

HashMap
  1. Since Java 1.2
  2. Allows null key and value
  3. Poor performance in highly threaded applications
  4. Not much scalable
  5. Throws a ConcurrentModificationException
  6. Faster in non-multi threading applications

ConcurrentHashMap
  1. Since Java 1.5
  2. Doesn't allow null key or value
  3. Better performance in Highly threaded applications
  4. Highly scalable
  5. Do not throw ConcurrentModificationException
  6. Slower in non-multi threading applications


Wednesday, May 5, 2010

Read value from Java properties

Here, you will find the source code to read value of the key from properties file. java.util.Properties class extends Hashtable. Properties class creates the properties file which stores key - value pair using Hashtable. To retrieve value from properties file we have to follow following steps.
  1. Create an object of Properties class.
  2. Load properties file using FileInputStream into properties object.
  3. Get value from properties object using getProperty() method passing key as an input.
The below code will help to understand more...

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class PropertiesReadTest {

    public static void main(String[] args) {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("C:\\temp\\test.properties"));
            String value = properties.getProperty("key");
            System.out.println("Value = " + value);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output is shown here in following image





Tuesday, May 4, 2010

Source code to read content of File

Here you will find the source code to read the content of file.

Steps
  1. Create the FileReader object using file name as an input to FileReader constructor.
  2. Pass that FileReader object to BufferedReader.
  3. Read the line from BufferedReader object till readline gets null.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReadTest {

    public static void main(String[] args) {
         try {
            BufferedReader br = new BufferedReader(new FileReader("C:\\temp\\test.txt"));
            String line = "";
            while((line = br.readLine()) != null)
            {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Monday, May 3, 2010

Access file using JSP & Servlets

Given source code used for accessing file from server using

Servlets


String path = getServletContext( ).getRealPath ("xyz.xml" ) ;
System.out.println ( path ) ;
File file = new File ( path ) ;

JSP
String path = application.getRealPath ("xyz.xml" ) ;
System.out.println ( path ) ;
File file = new File ( path ) ;

In above jsp code, "application" is jsp implicit object.



Friday, April 30, 2010

Java pass by value or pass by reference

  • Java manipulates objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.
  • Java is strictly pass-by-value, exactly as in C.
  • Java has pointers and is strictly pass-by-value.


Thursday, April 29, 2010

Encapsulation in JAVA

Encapsulation in java means declare instance variables of class as private and access that instance variables using public methods.
Following is the example which shows that Person class having name and age are private instance variables and those are accessed by public getter and setter methods.

public class Person {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}


OOPs concepts in JAVA

  • Abstraction: Hides certain details and only show the essential features of the object.
  • Encapsulation: The internal representation of an object is generally hidden from view outside of the object's definition.
  • Inheritance: Defines relationships among classes in an object-oriented language.  
  • Polymorphism: Define more than one method with the same name.


    finally block not executed

    Finally block is always executed except some of the following cases.
    • If the JVM exits while the try or catch code is being executed, then the finally block may not execute. 
              e.g. System.exit(0);
    • If the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues. 
             e.g. Thread.interrupted();


    J2EE Design Patterns

    1. Business Delegate
    2. Composite Entity
    3. Composite View
    4. Data Access Object (DAO)
    5. Fast Lane Reader
    6. Front Controller
    7. Intercepting Filter
    8. Model-View-Controller
    9. Service Locator
    10. Session Facade
    11. Transfer Object
    12. Value List Handler
    13. View Helper

    Tuesday, April 20, 2010

    Static vs Transient variables

    Static variables
    • Static variables are class variables.
    • Static variables can be serialized.
    • static modifier applies to static variables.
           class TestClass{
              static int testVariable;
              . . .
          }

    Transient variables
    • Transient variables are member or instance variables of class.
    • Transient variables can not be serialized.
    • transient modifier applies to transient variables.
           class TestClass{
              transient int testVariable;
              . . .
          }

    Thursday, April 15, 2010

    JDK 5 Enhancements in Java Language


    1.      Generics - This is an 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.
    e.g.
    Previously
    Array List numbers = new ArrayList();

    Now in JDK 5.0
    Array List<Integer> numbers = new ArrayList<Integer> ();

    2.      Enhanced for Loop - This new language construct eliminates the drudgery and error-proneness of iterators and index variables when iterating over collections and arrays.
    e.g.      
    Previously
    Iterator itr = numbers.iterator();
    while
     (itr.hasNext()) 
    {
          Integer element = (Integer)itr.next();
          System.out.println (number);
    }

    Now in JDK 5.0
    for (Integer number: numbers)
    {
                System.out.println (number);
    }

    3.      Autoboxing/Unboxing - This facility eliminates the drudgery of manual conversion between primitive types (such as int, long) and wrapper types (such as Integer, Long).
    e.g.      
    int number = 1;
    Previously
    Integer number2 = (Integer) number;

    Now in JDK 5.0
    Integer number2 = number;

    4.      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.
    e.g.
    Previously
    public static final int SEASON_WINTER = 0;
    public static final int SEASON_SPRING = 1;
    public static final int SEASON_SUMMER = 2;
    public static final int SEASON_FALL   = 3;

    Now in JDK 5.0
    enum Season {WINTER, SPRING, SUMMER, FALL}

    5.      Varargs - This facility eliminates the need for manually boxing up argument lists into an array when invoking methods that accept variable-length argument lists.
    e.g.
    Previously
    Object[] arguments = {
        new Integer(7),
        new Date(),
        "a disturbance in the Force"
    };

    String result = MessageFormat.forma("At {1,time} on {1,date}, there was {2} on planet "
         + "{0,number,integer}.", arguments);

    Now in JDK 5.0
    Using Varargs no need to create object array separately, we can give arguments directy.

    String result = MessageFormat.format("At {1,time} on {1,date}, there was {2} on planet "
        + "{0,number,integer}.",
        7, new Date(), "a disturbance in the Force");

    6.      Static Import - This facility lets you avoid qualifying static members with class names without the shortcomings of the "Constant Interface antipattern."
    e.g.
    Previously
    double r = Math.cos(Math.PI * theta);

    Now in JDK 5.0
    import static java.lang.Math.*;
    Once the static members have been imported, they may be used without qualification or class names:
    double r = cos(PI * theta);

    7.      Annotations (Metadata) - 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.
    Now in JDK 5.0
    public @ interface Test{}





    Wednesday, April 14, 2010

    Retrieve key from HashMap using value

    Below is the code to retrieve the key from HashMap using value
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    import java.util.Map.Entry;

    public class TestClass {

        public static void main(String[] args) {
            Map<Integer, Person> people = new HashMap<Integer, Person>();
            Person person1 = new Person();
            person1.setName("Mack");
            person1.setPost("Dev");
           
            Person person2 = new Person();
            person2.setName("John");
            person2.setPost("Dev");
           
            people.put(1, person1);
            people.put(2, person2);

            Set<Entry<Integer, Person>> peopleSet = people.entrySet();
            for (Entry<Integer, Person> entry : peopleSet) {
                Integer key = entry.getKey();
                Person value = entry.getValue();
                if (value.equals(person2)) {
                    System.out.println("Key = " + key);
                }
            }
        }
    }


    Tuesday, April 13, 2010

    Servlet Chaining

    Servlet Chaining means the output of one servlet given as a input to another servlet. Servlet Aliasing allows us to invoke more than one servlet in sequence when the URL is opened with a common servlet alias. The output from first Servlet is sent as input to other Servlet and so on. The Output from the last Servlet is sent back to the browser. The entire process is called Servlet Chaining.

    How to do Servlet Chaining in Servlet Programming?

    Using include
    RequestDispatcher rd = req.getRequestDispatcher("SecondServlet"); 
    rd.include(request, response);

    Using forward
    RequestDispatcher rd = req.getRequestDispatcher("SecondServlet"); 
    rd.forward(request, response);



    Monday, April 12, 2010

    JDBC driver types

    JDBC drivers are divided into four types.
    • Type 1: JDBC-ODBC Bridge
    • Type 2: Native-API/partly Java driver
    • Type 3: Net-protocol/all-Java driver
    • Type 4: Native-protocol/all-Java driver

    Java Database Connectivity (JDBC)

    JDBC is Java Database Connectivity helps to write java applications using databases.

    Steps to use JDBC in java applications as follows
    1. Load the JDBC driver.
    2. Define the connection URL.
    3. Establish the connection.
    4. Create a statement object.
    5. Execute a query or update.
    6. Process the results.
    7. Close the connection. 
    try {
                Class.forName("driveClassName");
                Connection con = DriverManager.getConnection(
                        "jdbc:driveName:databaseName", "login", "password");

                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT * FROM Table");
                while (rs.next()) {
                    int a = rs.getInt("column1");
                    String b = rs.getString("column2");
                    float c = rs.getFloat("column3");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                // close the connection
            }





    Serialization and Deserialization

    1. Serialization is the process of transforming an in-memory object to a byte stream
    2. An object is serialized by writing it to an ObjectOutputStream. 
    3. Serialization Code 
               FileOutputStream out = new FileOutputStream("test.txt" );
               ObjectOutputStream oos = new ObjectOutputStream( out );
               oos.writeObject(new String ());
               oos.close ();
    1. Deserialization is the inverse process of reconstructing an object from a byte stream to the same state in which the object was previously serialized. 
    2. An object is deserialized by reading it from an ObjectInputStream.
    3. Deserialization Code
    FileInputStream in = new FileInputStream( "test.txt" );
    ObjectInputStream ois = new ObjectInputStream( in );
    String s = (String) ois.readObject();
    ois.close();