Monday 2 June 2014

New Features in Java

New Features in Java
There are many new features that have been added in java. There are major enhancement made in Java5, Java6 and Java7 like auto-boxinggenericsvar-argsjava annotationsenumpremain method etc.
Most of the interviewers ask questions from this chapter.


Do You Know ?
1.    How to create generic class and generic method in java ?
2.    What is annotation and how to create custom annotation ?
3.    What is the advantage of assertion and where we should not use it ?
4.    What is variable argument and what rules are defined for variable argument ?
5.    What is the difference between import and static import ?
6.    How autoboxing is applied in method overloading. Which concept beats autoboxing ?
7.    What is enum type and how to specify specific value to the enum constants ?

J2SE 4 Features
The important feature of J2SE 4 is assertions. It is used for testing.
  • Assertion (Java 4)

J2SE 5 Features
The important features of J2SE 5 are generics and assertions. Others are auto-boxing, enum, var-args, static import, for-each loop (enhanced for loop etc.
  • For-each loop (Java 5)
  • Varargs (Java 5)
  • Static Import (Java 5)
  • Autoboxing and Unboxing (Java 5)
  • Enum (Java 5)
  • Covariant Return Type (Java 5)
  • Annotation (Java 5)
  • Generics (Java 5)

JavaSE 6 Features
The important feature of JavaSE 6 is premain method (also known as instrumentation).
  • Instrumentation (premain method) (Java 6)

JavaSE 7 Features
The important features of JavaSE 7 are try with resource, catching multiple exceptions etc.
  • String in switch statement (Java 7)
  • Binary Literals (Java 7)
  • The try-with-resources (Java 7)
  • Caching Multiple Exceptions by single catch (Java 7)
  • Underscores in Numeric Literals (Java 7)

JavaSE 8 Features
Let’s look at 5 features that we feel are an absolute must for you to know about:
1. Lambda expressions
Even if we really didn’t want to go mainstream here, there’s little doubt that from a developer’s perspective, the most dominant feature of Java 8 is the new support for Lambda expressions. This addition to the language brings Java to the forefront of functional programming, right there with other functional JVM-based languages such as Scala and Clojure.
We’ve previously looked into how Java implemented Lambda expressions, and how it compared to the approach taken by Scala. From Java’s perspective this is by far one of the biggest additions to the language in the past decade.
At minimum, it’s recommended you become familiar with the Lambda syntax, especially as it relates to array and collection operations, where Lambdas have been tightly integrated into the core language libraries. It is highly likely that you’ll start seeing more and more code like the snippet below in both 3rd party and within your organization’s code.
1.Map<Person.Sex, List<Person>> byGender =
2.roster.stream().collect(Collectors.groupingBy(Person::getGender));
* A pretty efficient way of grouping a collection by the value of a specific class field.
2. Parallel operations
With the addition of Lambda expressions to arrays operations, Java introduced a key concept into the language of internal iteration. Essentially as developers we’re used to use loop operations as one of the most basic programming idioms, right up there with if and else.
The introduction of Lambda expressions turned that paradigm around with the actual iteration over a collection over which a Lambda function is invoked is carried out by the core library.
You can think of this as an extension of iterators where the actual operation of extracting the next item from a collection on which to operate is carried out by an iterator. An exciting possibility opened by this design pattern is to enable operations carried out on long arrays such as sorting, filtering and mapping to be carried out in parallel by the framework. When dealing with server code that’s processing lengthy collections on a continuous basis, this can lead to major throughput improvements with relative work from your end.
Here’s the same snippet as above, but using the framework’s new parallel processing capabilities -
1.ConcurrentMap<Person.Sex, List<Person>> byGender =
2.roster.parallelStream().collect(
3.Collectors.groupingByConcurrent(Person::getGender))
* It’s a fairly small change that’s required to make this algorithm run on multiple threads.
3. Java + JavaScript =
Java 8 is looking to right one of its biggest historical wrongs – the ever growing distance between Java and JavaScript, one that has only increased in the past few years. With this new release, Java 8 is introducing a completely new JVM JavaScript engine – Nashorn. This engine makes unique use of some of the new features introduced in Java 7 such as invokeDynamic to provide JVM-level speed to JavaScript execution right there with the likes of V8 and SpiderMonkey.
This means that the next time you’re looking to integrate JS into your backend, instead of setting up a node.js instance, you can simply use the JVM to execute the code. The added bonus here is the ability to have seamless interoperability between your Java and JavaScript code in-process, without having to use various IPC/RPC methods to bridge the gap.
4. New date / time APIs
The complexity of the current native Java library API has been a cause of pain for Java developers for many years. Joda time has been filling this vacuum for years now, and with Java 8. An immediate question that arose early on was why didn’t Java 8 adopt Joda as its native time framework. Due to what was perceived as a design flaw in Joda, Java 8 implemented its own new date / time API from scratch. The good news is that unlike Calendar.getInstance(), the new APIs were designed with simplicity in mind, and clear operations to operate on manipulated values in both human readable and machine time formats.

5. Concurrent accumulators
One of the most common scenarios in concurrent programming is updating of numeric counters accessed by multiple threads. There have been many idioms to do this over the years, starting from synchronized blocks (which introduce a high level of contention), to read/write locks to AtomicInteger(s). While the last ones are more efficient, as they rely directly on processor CAS instructions, they require a higher degree of familiarity to implement the required semantics correctly.
With Java 8 this problem is solved at the framework level with new concurrent accumulator classes that enable you to very efficiently increase / decrease the value of a counter in a thread safe manner. This is really a case where it’s not a question of taste, or preference – using these new classes in your code is really a no-brainer.
Are there any other language features you think every developers should know about? Add them in the comments section.


Sunday 12 January 2014

Loading JDBC drivers

Loading JDBC drivers
I split these examples into two specific categories which are good and dumb.  

class dr1
{
    public static void main(String args[]) throws Exception
    {
        Class.forName("oracle.jdbc.driver.OracleDriver");
    }
}


class dr2
{
    public static void main(String args[]) throws Exception
    {
        // Choosing the driver at runtime
        Class.forName(args[0]);
    }
}


class dr3
{
    public static void main(String args[]) throws Exception
    {
        // Choosing the driver at runtime by a temporary
        // property
        Class.forName(System.getProperty("my.driver"));
    }
}

For executing this, you should write

java -Dmy.driver=oracle.jdbc.driver.OracleDriver dr3

The -D option is followed by the property name (without space) and =followed by the driver class. Don't forget the class name. It is damn important!

Note: The second, third and fourth ways have a common problem. Here if we aren't decisive about which driver to use and give it at runtime we need to change the URL (to connect to the database) too. Because, different drivers have different urls. So, there must be some conditional logic written which connects to the database via appropriate URL corresponding to the given class name. This becomes a bit messy. Isn't it?


class dr4
{
    public static void main(String args[])
    {
        // Choosing the driver at runtime by a permanent
        // property
        System.out.println("Driver loaded "+System.getProperty("jdbc.drivers"));
    }
}

Well, where is the code? I'll explain, everything lies in executing the program. You should execute this in this way.

java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver dr4

Now, this loads the driver. The jdbc.drivers is an environment property of Java that corresponds to the JDBC drivers. The default value for this property is null. While executing, you are changing its value to the driver class name.

3 Dumb ways


class dr5
{
    public static void main(String args[])
    {
        // Creating an object for the driver class
        new oracle.jdbc.driver.OracleDriver();
    }
}

I call this dumb because, we are creating an object for this class which is absolutely unnecessary. Here is a simple question to you

Why create an object for a class when you are not going to use it? If you want to load the static block of the class? Isn't it enough to load the class into the memory using Class.forName() instead of creating an object for it?


class dr6
{
    public static void main(String args[]) throws Exception
    {
        // Using the registerDriver
        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    }
}

This way is double-dumb because you are loading the driver twice. Yes, thestatic block of the oracle.jdbc.driver.OracleDriver already contains a call to the registerDriver(). The statement, new oracle.jdbc.driver.OracleDriver(); loads it into memory (therefore, static block is executed) and creates an object for the driver class and then register the driver.


class dr7 extends oracle.jdbc.driver.OracleDriver
{
    public static void main(String args[])
    {
        System.out.println("Driver is loaded.");
    }
}