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.


J2SE 4 Features

The important feature of J2SE 4 is assertions. It is used for testing.

Assertion:

Assertion is a statement in java. It can be used to test your assumptions about the program.
While executing assertion, it is believed to be true. If it fails, JVM will throw an error named AssertionError. It is mainly used for testing purpose.


Advantage of Assertion:

It provides an effective way to detect and correct programming errors.



Syntax of using Assertion:

There are two ways to use assertion. First way is:


  1. assert expression;  

and second way is:


assert expression1 : expression2;  

Where not to use Assertion:



There are some situations where assertion should be avoid to use. They are:
  1. According to Sun Specification, assertion should not be used to check arguments in the public methods because it should result in appropriate runtime exception e.g. IllegalArgumentException, NullPointerException etc.
  2. Do not use assertion, if you don't want any error in any situation.

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 (Advanced or Enhanced For loop):

The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.

Advantage of for-each loop:

  • It makes the code more readable.
  • It elimnates the possibility of programming errors.


Syntax of for-each loop:

  1. for(data_type variable : array | collection){}  


Variable Argument (Varargs):

The varrags allows the method to accept zero or muliple arguments. Before varargs either we use overloaded method or take an array as the method parameter but it was not considered good because it leads to the maintenance problem. If we don't know how many argument we will have to pass in the method, varargs is the better approach.

Advantage of Varargs:

We don't have to provide overloaded methods so less code.

Syntax of varargs:

The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:

  1. return_type method_name(data_type... variableName){}  


Rules for varargs:

While using the varargs, you must follow some rules otherwise program code won't compile. The rules are as follows:
  • There can be only one variable argument in the method.
  • Variable argument (varargs) must be the last argument.


Static Import:

The static import feature of Java 5 facilitate the java programmer to access any static member of a class directly. There is no need to qualify it by the class name.

Advantage of static import:

  • Less coding is required if you have access any static member of a class oftenly.

Disadvantage of static import:

  • If you overuse the static import feature, it makes the program unreadable and unmaintainable.

What is the difference between import and static import?

The import allows the java programmer to access classes of a package without package qualification whereas the static import feature allows to access the static members of a class without the class qualification. The import provides accessibility to classes and interface whereas static import provides accessibility to static members of the class.

Autoboxing and Unboxing:



The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and opposite operation is known as unboxing. This is the new feature of Java5. So java programmer doesn't need to write the conversion code.


Advantage of Autoboxing and Unboxing:

No need of conversion between primitives and Wrappers manually so less coding is required.

Autoboxing and Unboxing with comparison operators

Autoboxing can be performed with comparison operators.

Autoboxing and Unboxing with method overloading

In method overloading, boxing and unboxing can be performed. There are some rules for method overloading with boxing:
  • Widening beats boxing
  • Widening beats varargs
  • Boxing beats varargs

Method overloading with Widening and Boxing

Widening and Boxing can't be performed

Enum

An enum is a data type which contains fixed set of constants. It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The enum constants are static and final implicitely. It is available from Java 5. Enums can be thought of as classes that have fixed set of constants.


Points to remember for Enum:

  1. enum improves type safety
  2. enum can be easily used in switch
  3. enum can be traversed
  4. enum can have fields, constructors and methods
  5. enum may implement many interfaces but cannot extend any class because it internally extends Enum class

What is the purpose of values() method in enum?

The java compiler internally adds the values() method when it creates an enum. The values() method returns an array containing all the values of the enum.



Internal code generated by the compiler for the above example of enum type

The java compiler internally creates a static and final class that extends the Enum class


Defining enum:

The enum can be defined within or outside the class because it is similar to a class.

Initializing specific value to the enum constants:

The enum constants have initial value that starts from 0, 1, 2, 3 and so on. But we can initialize the specific value to the enum constants by defining fields and constructors. As specified earlier, Enum can have fields, constructors and methods.

Can we create the instance of enum by new keyword?

No, because it contains private constructors only.


Can we have abstract method in enum?

Yes, ofcourse! we can have abstract methods and can provide the implementation of these methods.



Applying enum on switch statement

We can apply enum on switch statement



Java Annotation

Annotation is a tag that represents the metadata. It is attached with class, interface, methods or fields to indicate some additional information that can be used by java compiler and JVM.



Built-In Annotations


There are several built-in annoations. Some annotations are applied to java code and some to other annotations.

Built-In Annotations that are applied to java code

  • @Override
  • @SuppressWarnings
  • @Deprecated

Built-In Annotations that are applied to other annotations

  • @Target
  • @Retention
  • @Inherited
  • @Documented


Custom Annotation



We can create the user-defined annotations also. The @interface element is used to declare an annotation. For example:


  1. @interface MyAnnotation{}  


Points to remember for annotation signature


There are few points that should be remembered by the programmer.
  1. Method should not have any throws clauses
  2. Method should return one of the following: primitive data types, String, Class, enum or array of these data types.
  3. Method should not have any parameter.
  4. We should attach @ just before interface keyword to define annotation.
  5. It may assign a default value to the method.


Types of Annotation


There are three types of annotations.
  1. Marker Annotation
  2. Single-Value Annotation
  3. Multi-Value Annotation

1) Marker Annotation


An annotation that has no method, is called marker annotation. For example:

  1. @interface MyAnnotation{}  

The @Override and @Deprecated are marker annotations.


2) Single-Value Annotation

An annotation that has one method, is called Single-Value annotation. For example:

  1. @interface MyAnnotation{  
  2. int value();  
  3. }  

We can provide the default value also. For example:

  1. @interface MyAnnotation{  
  2. int value() default 0;  
  3. }  

How to apply Single-Value Annotation

Let's see the code to apply the single value annotation.

  1. @MyAnnotation(value=10)  

The value can be anything.

3) Mulit-Value Annotation


An annotation that has more than one method, is called Multi-Value annotation. For example:

  1. @interface MyAnnotation{  
  2. int value1();  
  3. String value2();  
  4. String value3();  
  5. }  
  6. }  
We can provide the default value also. For example:

  1. @interface MyAnnotation{  
  2. int value1() default 1;  
  3. String value2() default "";  
  4. String value3() default "xyz";  
  5. }  


How to apply Multi-Value Annotation


Let's see the code to apply the multi-value annotation.

  1. @MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")  


Built-in Annotations applied to other annotations (custom annotations)


  • @Target
  • @Retention
  • @Inherited
  • @Documented


@Target

@Target tag is used to specify at which type, the annotation is used.
The java.lang.annotation.ElementType enum declares many constants to specify the type of element where annotation is to be applied such as TYPE, METHOD, FIELD etc. Let's see the constants of ElementType enum:


Element TypesWhere the annotation can be applied
TYPEclass, interface or enumeration
FIELDfields
METHODmethods
CONSTRUCTORconstructors
LOCAL_VARIABLElocal variables
ANNOTATION_TYPEannotation type
PARAMETERparameter

Example to specify annoation for a class


  1. @Target(ElementType.TYPE)  
  2. @interface MyAnnotation{  
  3. int value1();  
  4. String value2();  
  5. }  


Example to specify annoation for a class, methods or fields


  1. @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})  
  2. @interface MyAnnotation{  
  3. int value1();  
  4. String value2();  
  5. }  

@Retention


@Retention annotation is used to specify to what level annotation will be available.
RetentionPolicyAvailability
RetentionPolicy.SOURCErefers to the source code, discarded during compilation. It will not be available in the compiled class.
RetentionPolicy.CLASSrefers to the .class file, available to java compiler but not to JVM . It is included in the class file.
RetentionPolicy.RUNTIMErefers to the runtime, available to java compiler and JVM .

Example to specify the RetentionPolicy


  1. @Retention(RetentionPolicy.RUNTIME)  
  2. @Target(ElementType.TYPE)  
  3. @interface MyAnnotation{  
  4. int value1();  
  5. String value2();  
  6. }  

Generics in Java

The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
Before generics, we can store any type of objects in collection i.e. non-generic. Now generics, forces the java programmer to store specific type of objects.

Advantage of Java Generics

There are mainly 3 advantages of generics. They are as follows:

1) Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects.
2) Type casting is not required: There is no need to typecast the object.
Before Generics, we need to type cast.

  1. List list = new ArrayList();  
  2. list.add("hello");  
  3. String s = (String) list.get(0);//typecasting  

After Generics, we don't need to typecast the object.

  1. List<String> list = new ArrayList<String>();  
  2. list.add("hello");  
  3. String s = list.get(0);  

3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime.

  1. List<String> list = new ArrayList<String>();  
  2. list.add("hello");  
  3. list.add(32);//Compile Time Error  

Syntax to use generic collection

  1. ClassOrInterface<Type>  

Simple example to use Generics

  1. ArrayList<String>  

Generic class

A class that can refer to any type is known as generic class. Here, we are using T type parameter to create the generic class of specific type.
Let’s see the simple example to create and use the generic class.

Creating generic class:

  1. class MyGen<T>{  
  2. T obj;  
  3. void add(T obj){this.obj=obj;}  
  4. T get(){return obj;}  
  5. }  

The T type indicates that it can refer to any type (like String, Integer, Employee etc.). The type you specify for the class, will be used to store and retrieve the data.

Using generic class:

Let’s see the code to use the generic class.

  1. class UseGen{  
  2. public static void main(String args[]){  
  3. MyGen<Integer> m=new MyGen<Integer>();  
  4. m.add(2);  
  5. //m.add("vivek");//Compile time error  
  6. System.out.println(m.get());  
  7. }}  
Output:2

Understanding Type Parameters

The type parameters naming conventions are important to learn generics thoroughly. The commonly type parameters are as follows:
  1. T - Type
  2. E - Element
  3. K - Key
  4. N - Number
  5. V - Value
  6. S,U,V etc. - 2nd, 3rd, 4th types


Generic Method

Like generic class, we can create generic method that can accept any type of argument.
Let’s see a simple example of java generic method to print array elements. We are using here E to denote the element.


Covariant Return Type


The covariant return type specifies that the return type may vary in the same direction as the subclass.
Before Java5, it was not possible to override any method by changing the return type. But now, since Java5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type


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)


{ 2 comments... read them below or Comment }

  1. Java training in chandigarh
    Great wordpress blog here.. It's hard to find quality writing like yours these days. I really appreciate people like you! take care

    ReplyDelete
  2. Java training in chandigarh
    I love your blog.. very nice colors & theme. Did you create this website yourself? Plz reply back as I'm looking to create my own blog and would like to know where u got this from. thanks

    ReplyDelete

About This Site

Howdy! My name is Suersh Rohan and I am the developer and maintainer of this blog. It mainly consists of my thoughts and opinions on the technologies I learn,use and develop with.

Blog Archive

Powered by Blogger.

- Copyright © My Code Snapshots -Metrominimalist- Powered by Blogger - Designed by Suresh Rohan -