Quick Refresh : JDK1.5 New Feature

Variable Argument (Varargs): 

The varargs allows the method to accept zero or multiple arguments. Before varargs either we use the 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 arguments we will have to pass in the method, varargs is the better approach. The advantage of Varargs is that we don't have to provide overloaded methods so less code.

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.
Syntax of varargs: The varargs uses ellipsis i.e. three dots after the data type. 
return_type method_name(data_type... variableName){}

void method(String... a, int... b){}//Compile time error
void method(int... a, String b){}//Compile time error

class VarargsExample1{
 static void display(String... values){
  System.out.println("display method invoked ");
 }

 public static void main(String args[]){

 display();//zero argument 
 display("my","name","is","varargs");//four arguments
 } 
}

Output:display method invoked
       display method invoked

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. The advantage of static import is that less coding is required if you have access to any static member of a class often. The disadvantage of static import is If you overuse the static import feature, it makes the program unreadable and unmaintainable.

import static java.lang.System.*;  
class StaticImportExample{
  public static void main(String args[]){
   
   out.println("Hello");//Now no need of System.out
   out.println("Java");

 } 
}

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 automatic conversion of wrapper class type into corresponding primitive type, is known as Unboxing. This is the new feature of Java5. So java programmer doesn't need to write the conversion code.

class UnboxingExample1{
  public static void main(String args[]){
Integer i=new Integer(50);
        int a=i;
        
        System.out.println(a);
 } 
}


Autoboxing can be performed with comparison operators -

class UnboxingExample1{
  public static void main(String args[]){
Integer i=new Integer(50);
        
        if(i<100){            //unboxing internally
        System.out.println(i);
        }
 } 
}

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 - If there is possibility of widening and boxing, widening beats boxing.

class Boxing1{
static void m(int i){System.out.println("int");}
static void m(Integer i){System.out.println("Integer");}


public static void main(String args[]){
short s=30;
m(s);
}
}


Output:int

Widening beats varargs - 

If there is a possibility of widening and varargs, widening beats var-args.

class Boxing2{
static void m(int i, int i2){System.out.println("int int");}
static void m(Integer... i){System.out.println("Integer...");}


public static void main(String args[]){
short s1=30,s2=40;
m(s1,s2);
}
}


Output:int int

Boxing beats varargs


class Boxing3{
static void m(Integer i){System.out.println("Integer");}
static void m(Integer... i){System.out.println("Integer...");}


public static void main(String args[]){
int a=30;
m(a);
}
}


Output:Integer



Method overloading with Widening and Boxing


class Boxing3{
static void m(Long l){System.out.println("Long");}


public static void main(String args[]){
int a=30;
m(a);
}
}

Output:Compile Time Error

Enum: 

An enum is a data type that contains a 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 implicitly. It is available from Java 5. Enums can be thought of as classes that have a fixed set of constants.  The enum can be defined within or outside the class because it is similar to a class.   The constructor of enum type is private if you don't declare private compiler internally have a private constructor. It means that we can not create the instance of enum by new keyword.
  • enum improves type safety
  • enum can be easily used in switch
  • enum can be traversed
  • enum can have fields, constructors and methods
  • enum may implement many interfaces but cannot extend any class because it internally extends Enum class
class EnumExample1{
public enum Season { WINTER, SPRING, SUMMER, FALL }
public static void main(String[] args) {
for (Season s : Season.values())
System.out.println(s);
}}


Output:WINTER
SPRING
SUMMER
FALL

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.

Initializing specific value to the enum constants:
The enum constants have an 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.


class EnumExample4{
enum Season{
WINTER(5), SPRING(10), SUMMER(15), FALL(20);
private int value;
private Season(int value){
this.value=value;
}
}
public static void main(String args[]){
for (Season s : Season.values())
System.out.println(s+" "+s.value);
}
}


Output:WINTER 5
SPRING 10
SUMMER 15
FALL 20


Applying enum on switch statement:
class EnumExample5{
enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}


public static void main(String args[]){
Day day=Day.MONDAY;
switch(day){
case SUNDAY:
System.out.println("sunday");
break;
case MONDAY:
System.out.println("monday");
break;
default:
System.out.println("other day");
}
}
}


Output: monday

Can we have abstract method in the enum?
Yes, ofcourse! we can have abstract methods and can provide the implementation of these methods.

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.

Syntax of for-each loop:   for(data_type variable : array | collection){}



Simple Example of for-each loop for traversing the array elements:
class ForEachExample1{
public static void main(String args[]){
int arr[]={12,13,14,44};
for(int i:arr){
System.out.println(i);
}
}
}

Output:12
13
14
44


Simple Example of for-each loop for traversing the collection elements:
import java.util.*;
class ForEachExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("vimal");
list.add("sonoo");
list.add("ratan");
for(String s:list){
System.out.println(s);
}
}
}

Output:</strong>vimal
sonoo
ratan

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 annotations. Some annotations are applied to java code and some to other annotations. </p>

Built-In Annotations that are applied to java code
  • @Override - annotation assures that the subclass method is overriding the parent class method. If it is not so, a compile-time error occurs. Sometimes, we do a silly mistake such as spelling mistakes, etc. So, it is better to mark @Override annotation that provides assurance that the method is overridden. These kinds of errors will be caught at compile time then.
class Animal{
void eatSomething(){System.out.println("eating something");}
}

class Dog extends Animal{
@Override
void eatsomething(){System.out.println("eating foods");}//should be eatSomething
}

class Test{
public static void main(String args[]){
Animal a=new Dog();
a.eatSomething();
}}
Output: Comple Time Error

  • @SuppressWarnings - is used to suppress warnings issued by the compiler.
import java.util.*;
class Test{
@SuppressWarnings("unchecked")
public static void main(String args[]){

ArrayList list=new ArrayList();
list.add("sonoo");
list.add("vimal");
list.add("ratan");

for(Object obj:list)
System.out.println(obj);

}}
Now no warning at compile time. If you remove the @SuppressWarnings("unchecked") annotation, it will show warning at compile time because we are using non-generic collection.

  • @Deprecated - @Deprecated annotation marks that this method is deprecated so compiler prints warning. It informs the user that it may be removed in future versions. So, it is better not to use such methods.
class A{
void m(){System.out.println("hello m");}

@Deprecated
void n(){System.out.println("hello n");}
}

class Test{
public static void main(String args[]){

A a=new A();
a.n();
}}

At Compile Time:
Note: Test.java uses or overrides a deprecated API.<br>
Note: Recompile with -Xlint:deprecation for details.
At Runtime: hello n

Built-In Annotations that are applied to other annotations
  • @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 Types Where the annotation can be applied
TYPE class, interface or enumeration
FIELD fields
METHOD methods
CONSTRUCTOR constructors
LOCAL_VARIABLE local variables
ANNOTATION_TYPE annotation type
PARAMETER parameter


Example to specify annoation for a class:
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}


Example to specify annoation for a class, methods or fields
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@interface MyAnnotation{
int value1();
String value2();
}
  • @Retention- @Retention annotation is used to specify to what level annotation will be available.
RetentionPolicy Availability
RetentionPolicy.SOURCE refers to the source code, discarded during compilation. It will not be available in the compiled class.
RetentionPolicy.CLASS refers to the .class file, available to java compiler but not to JVM. It is included in the class file.
RetentionPolicy.RUNTIME refers to the runtime, available to java compiler and JVM.


Example to specify the RetentionPolicy
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}


Example of custom annotation: creating, applying and accessing annotation
//Creating annotation
import java.lang.annotation.*;
import java.lang.reflect.*;


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation{
int value();
}


//Applying annotation
class Hello{
@MyAnnotation(value=10)
public void sayHello(){System.out.println("hello annotation");}
}


//Accessing annotation
class Test{
public static void main(String args[])throws Exception{


Hello h=new Hello();
Method m=h.getClass().getMethod("sayHello");


MyAnnotation manno=m.getAnnotation(MyAnnotation.class);
System.out.println("value is: "+manno.value());
}}


Output:value is: 10


How built-in annotaions are used in real scenario?

In real scenario, java programmer only need to apply annotation. He/She doesn't need to create and access annotation. Creating and Accessing annotation is performed by the implementation provider. On behalf of the annotation, java compiler or JVM performs some additional operations.
  • @Inherited- By default, annotations are not inherited to subclasses. The @Inherited annotation marks the annotation to be inherited to subclasses.
@Inherited
@interface ForEveryone { }//Now it will be available to subclass also

@interface ForEveryone { }
class Superclass{}

class Subclass extends Superclass{}
  • @Documented - @Documented Marks the annotation for inclusion in the documentation.

Custom Annotation: 

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

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

Types of Annotation:  

There are three types of annotations
1) Marker Annotation - An annotation that has no method, is called marker annotation. For example:

@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:

@interface MyAnnotation{
int value();
}


We can provide the default value also. For example:
@interface MyAnnotation{
int value() default 0;
}


How to apply Single-Value Annotation
@MyAnnotation(value=10)



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

@interface MyAnnotation{
int value1();
String value2();
String value3();
}
}
We can provide the default value also. For example:
@interface MyAnnotation{
int value1() default 1;
String value2() default "";
String value3() default "xyz";
}


How to apply Multi-Value Annotation
@MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")

Comments

Popular posts from this blog

Ramoji Film City, Hyderabad, India

Ashtavinayak Temples | 8 Ganpati Temples of Maharashtra | Details Travel Reviews

Quick Refresh : Hibernate