Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java integer type constant declaration - primitive or object?

Tags:

java

In Java, what's the benefit of int constant declared by an object way:

public final static Integer SOME_CONSTANT = Integer.valueOf(99);

instead of classic

public final static int SOME_CONSTANT = 99;

I know the basic difference between objects and primitives, also autoboxing. But I have seen this declaration in our company's code and I wonder, is there any particular reason of declaring integer constant as an object?

like image 451
Gondy Avatar asked Sep 28 '22 16:09

Gondy


2 Answers

It depends on how you plan to use the constant. If you have an API which requires an Integer, then using the int form will have a small performance penalty because of auto-boxing.

If you just need the primitive, the unboxing of Integer isn't very expensive but easy to avoid.

Also note that

Integer SOME_CONSTANT = Integer.valueOf(99);

is exactly the same as

Integer SOME_CONSTANT = 99;

The *.valueOf() methods were added the API to give the compiler a common way to auto-box primitives.

like image 76
Aaron Digulla Avatar answered Oct 12 '22 23:10

Aaron Digulla


There is actually some difference between the 2. Looking at the byte code will reveal that info.

public final static int SOME_CONSTANT = 99;

Will be a compile time constant. So the value of this thing will be available as part of the byte code itself.

Byte code :

 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);

Although instances of Integer class are immutable, they will not turn into compile time constants. They are run as part of the static initializer of the class.

Byte code :

 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
like image 31
TheLostMind Avatar answered Oct 12 '22 23:10

TheLostMind