In Java, what is the advantage of int constant being declared in the manner of the object:
public final static Integer SOME_CONSTANT = Integer.valueOf(99);
instead of the classic
public final static int SOME_CONSTANT = 99;
I know the main difference between objects and primitives, as well as autoboxing. But I saw this expression in our company code, and I wonder if there is any special reason for declaring an integer constant as an object?
It depends on how you plan to use the constant. If you have an API for which it is required Integer, then using the form intwill have a slight performance limitation due to automatic boxing.
Integer
int
If you just need a primitive, unpacking is Integernot very expensive, but it is easy to avoid.
,
Integer SOME_CONSTANT = Integer.valueOf(99);
Integer SOME_CONSTANT = 99;
*.valueOf() API, .
*.valueOf()
, , .. , int, Integer.
- , , . , Integer int. .
, -: , , .
- 2. , .
. , .
-:
public static final int SOME_CONSTANT; descriptor: I flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL ConstantValue: int 99
public final static Integer SOME_CONSTANT1 = Integer.valueOf(99);
Integer , . .
public static final java.lang.Integer SOME_CONSTANT1; descriptor: Ljava/lang/Integer; flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL static {}; descriptor: ()V flags: ACC_STATIC Code: stack=1, locals=0, args_size=0 0: bipush 99 2: invokestatic #14 // Method java/lang/Integer.valueO f:(I)Ljava/lang/Integer; 5: putstatic #20 // Field SOME_CONSTANT1:Ljava/lang /Integer; 8: return LineNumberTable: line 4: 0 line 5: 8 LocalVariableTable: Start Length Slot Name Signature
, . , , .
ob Integer- , , Integer. . : Java Integer:
JavaDoc valueOf Integer:
JavaDoc
valueOf
/** * Returns an {@code Integer} instance representing the specified * {@code int} value. If a new {@code Integer} instance is not * required, this method should generally be used in preference to * the constructor {@link #Integer(int)}, as this method is likely * to yield significantly better space and time performance by * caching frequently requested values. * * This method will always cache values in the range -128 to 127, * inclusive, and may cache other values outside of this range. * * @param i an {@code int} value. * @return an {@code Integer} instance representing {@code i}. * @since 1.5 */
, , int [-128, 127], , , , - . , , , (, , -.)
- valueOf, , , , Integer.valueOf vs new Integer.
Integer.valueOf
new Integer
Java - - ... , , ...
, ...
, , - , ...
int , , , Integer.
SOME_CONSTANT , , int.
SOME_CONSTANT
Integer . . API:
.