Java is an Object Oriented programming language. We have to deal with primitive types and objects together.
Here autoboxing comes to play the role. It wraps the primitive data type into a object. There are wrapper classes for it.
For Example : -
public class FormatPrint {
public static void main(String[] args) {
System.out.printf("There is only %d thing.", 1);
}
}
The signature of the printf() is
printf(String format, Object... args)
But, inthe above example i have printed a integer value. This is called as autoboxing. This can be used in Generics,too.
Here is java normal java generic example : -
import java.util.ArrayList;
public class ManualBoxing {
public static void main(String[] args) {
ArrayList list = new ArrayList();
for(int i = 0; i < 10; i++){
list.add(new Integer(i));
}
}
}
But we don't need to "new Integer(i)". We can use autoboxing and simply the code as follow.
import java.util.ArrayList;
public class Autoboxing {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < 10; i++){
list.add(i);
}
}
}
For further details : -
http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html
No comments:
Post a Comment