Sunday, February 8, 2009

Var-Args in Java 5

Java 5 allows methods to take variable number of arguments

Pre Java 5 Example
void doSomething(int i, int j){
Save as Draft

}

This method will be called as follows:
doSomething(10, 20);

Using Java 5, you can declare doSomething method by giving variable arguments as follows:

void doSomething(int... i){
}

And at the time of calling the method, pass any number of arguments as you want.

doSomething(10);
doSomething(10,20);
and so on....

Declaration rules for var-args:
  1. Var-arg Type: When you declare var-args in method, you must specify type of arguments method can receive.
  2. Syntax: Var-args should be declared with type followed by three dots (...) and then name of array that will hold the parameters
  3. Positioning and number of var-args parameters: Var-args must be the last argument in a method signature and you can have only one var-arg in a method.

Monday, February 2, 2009

Autoboxing in Java 5

Hi,
In this post, I am going to discuss about Autoboxing but before that let me explain Wrapper classes. The main purpose of wrapper classes:
Java programmers often need some mechanism to wrap primitive values in an object so that the primitives can be used in activities reserved for objects, like adding into and retreiving from the collections, returning object from a method etc. Wrapper classes serves this.
With the help of autoboxing and unboxing (features provided by Java 5), most of the wrapping features, that user needs to do manually are now handled automatically.

Using Java 4, you may want to use wrapper classes as follows:

Integer x = new Integer(100); // make it
int y = x.intValue(); // unwrap it
y++; // increment the value
x = new Integer(y); // re-wrap it
System.out.println(y); // print it

Using Java 5 (Autoboxing feature), you may want to use wrapper classes as follows:

Integer y = new Integer(100);
y++;
System.out.println(y);
Both examples produce the output:

101