Change boxing or Unboxing Setting in eclipse in java - Advantages



We may set up our eclipse to find out when boxing or unboxing is done >
Go to windows, preferences
type error,
select Errors/warnings,

type boxing and
then select Error, warning or ignore (By default its ignore).



Example - If you select warning, then eclipse will warn you whenever any Autoxing or unboxing is done.>
Example 1 - Autoboxing Example 1 >


You may write such code where we won’t rely on Java compiler to perform Autoxing  -
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class Autoboxing{
   public static void main(String[] args) {
         
          int i = 12;
          Integer iObject = Integer.valueOf(i); // This is Autoboxing
   }
}
In the above program by using Integer.valueOf(i) we can ensure that one Integer object is formed.
Note : You may not rely on  Integer.valueOf(i) method every time to count number of objects formed because Java caches Integer objects formed from primitive int values between values -128 to 127. Hence, Integer.valueOf method returns cached object(if any) for primitive int values between values -128 to 127. Read this post for more details.


Example 2 - Unboxing Example 1 >


You may write such code where we won’t rely on Java compiler to perform unboxing  -
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class Unboxing{
   public static void main(String[] args) {
         
          Integer iObject = Integer.valueOf(12); // equivalent to >  Integer iObject = 12;  
          int i = iObject.intValue(); // This is Unboxing
   }
}
In the above program by using intValue() we can ensure that one Integer object is converted into primitive data type.

Example - If you select error, then eclipse will show error whenever any Autoxing or unboxing is done(It won’t be the compilation error) >
You can see red mark when autoxing is done.

Possible advantages of changing Autoboxing and unboxing setting in eclipse >
  • Keep track of number of objects formed in program - It can help developer in keeping easy track of number of primitives converted into wrapper objects, accordingly developer may manage heap or enforce early garbage collection.


  • Keep track of number of objects converted into primitives - Developer can keep track of such conversion easily, avoid them if possible and optimize performance.

RELATED LINKS>

Autoboxing and unboxing in java - How it works internally in detail with 10 examples- Widening, AutoBoxing and Var-args

Java caches Integer objects formed from primitive int values between values -128 to 127

10 points on why we are still using primitive data types in java ? When to use primitive type and wrapper classes?

Method overloading with Widening, Autoboxing and Var-args - Who beats whom in java?


eEdit
Must read for you :