Showing posts with label Java 5 New Features. Show all posts
Showing posts with label Java 5 New Features. Show all posts

Thursday, 4 August 2016

Java Autoboxing and Unboxing Example

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 Java 5.  So java programmer doesn't need to write the conversion code.


public class AutoboxingAndUnboxing {

public static void main(String[] args) {
int a=100;
Integer n=new Integer(a);  // Boxing

System.out.println("BOXING : "+n);

int x = n;  // Un boxing

System.out.println("UNBOXING : "+x);
}

}


Java Static Import Example

Static Import help to access any static member of class directly.Advantage of using this is that programmers require less code.

import static java.lang.System.*;
public class StaticImport {

public static void main(String[] args) {
out.println("Hello Static Import Example");  // STATIC IMPORT
}

}

Tuesday, 2 August 2016

Java Variable Argument Example


Variable Argument (Varargs)  allows the method to accept zero or multiple arguments.This is a better approach If, we don't know how many parameters we will have to pass in method.
Syntax for variable args 
method_return_type method_name(datatype... variable_name){}
Rules of variable arguments :
** There can be only one variable argument in method signature.
** If providing multiple arguments in method signature then varargs will always be last argument.

public class VariableArgument {
static void show(String... str){
for(String s:str){
System.out.println(s);
}
}
static void show(String str,int... num){
for(int i : num){
System.out.println(i);
}
}
public static void main(String[] args) {
System.out.println("Method With Variable Args\n");
show();  // Method with no argument
show("a","b","c","d");  // Method with argument
System.out.println("Method With Variable Args And Other arguments\n");
show("pushkar",4,5,5);
}
}

Java Enums Example


Enum in java is a data type that contains fixed set of constants.
Enum can be introduce inside or outside the class.
For calling enums use this syntx enum_name.variable_name.
Enum can used with switch statement.
Enum have constructor ,methods and data members.
Enum may implement many interfaces but cannot extend any     class because it internally extends Enum class.


enum week {
sun,mon,tue,wed,thu,fri,sat;
week(){
System.out.println("ENUM CONSTRUCTOR");
}
public void show(){
System.out.println("ENUM METHOD");
}
};

public class EnumExample {

public static void main(String[] args) {

System.out.println("CALLING SINGLE VARIABLE FROM ENUM : "+week.mon);
System.out.println("ENUM LENGTH  : "+week.values().length);

week.sun.show();

System.out.println("CALLING ALL VARIABLE FROM ENUM : ");
for(week w : week.values()){
System.out.println(w);
}
}
}