Skip to main content

Posts

Showing posts with the label Autoboxing

Why does the autoboxing conversion sometimes return the same reference?

Although Java programming language is an object-oriented language, in a lot of cases that you would need to deal with primitive types. Before J2SE 5.0, working with primitive types required the repetitive work of conversion between the primitive types and their wrapper classes. In this FAQ, you will see how the new autoboxing feature in J2SE 5.0 handles conversions -- for example, between values of type int and values of type Integer . For example, class Program { public static void main(String[] args) { Integer i1 = 20; Integer i2 = 20; Integer i3 = 201; Integer i4 = 201; System.out.println(i1 == i2); System.out.println(i3 == i4); } } The output is true false What we have discovered is that for small integral values, the objects are cached in a pool much like String pool.

What is Autoboxing in Java?

Autoboxing Autoboxing, introduced in Java 5, is the automatic conversion the Java compiler makes between the primitive (basic) types and their corresponding object wrapper classes (eg, int and Integer, double and Double, etc). The underlying code that is generated is the same, but autoboxing provides a sugar coating that avoids the tedious and hard-to-read casting typically required by Java Collections, which can not be used with primitive types. Example With Autoboxing Without Autoboxing int i;  Integer j;  i = 1;  j = 2;  i = j;  j = i; int i;  Integer j;  i = 1;  j = new Integer(2);  i = j.intValue();  j = new Integer(i); Prefer primitive types Use the primitive types where there is no need for objects for two reasons. Primitive types may be a lot faster than the corresponding wrapper types, and are never slower. The immutability (can't be changed after creation) of the wrapper types may make it their use impossible. T...