5

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?

Gondy
  • 4,925
  • 4
  • 40
  • 46
  • 1
    possible duplicate of [1 Using int vs Integer](http://stackoverflow.com/questions/10623682/using-int-vs-integer) [2 Using int vs Integer](http://stackoverflow.com/questions/423704/int-or-integer) – sharif2008 Jun 09 '15 at 09:24
  • [What is the best way to implement constants in Java](http://stackoverflow.com/questions/66066/what-is-the-best-way-to-implement-constants-in-java?rq=1) – moffeltje Jun 09 '15 at 09:25

9 Answers9

4

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.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
4

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
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • It's an `Integer`, not an `int`, so it won't be a compile time constant (boxing, etc..) – Tobb Jun 09 '15 at 10:10
  • 1
    @Tobb - That's what I am telling :) . A `static final Integer` is not a *constant* and hence the code will run slower when compared to `public static int` – TheLostMind Jun 09 '15 at 10:48
2

As a rule, one uses the second way of declaring constants, i.e. the one using a primitive int, not the boxed Integer.

One exception to this rule is when you place your constants in collections, and your constants are outside the range of numbers for which the objects are automatically interned. Your code may save a few CPU cycles here and there, so it would be fair to consider making your constants Integer instead of int. This lets you save on autoboxing costs when placing such constants into collections.

Generally, though, this comes across as a micro-optimization: unless you place your primitive constant in a collection inside a tight loop that takes a significant percentage of time, there would be no performance differences between the code with these two declarations.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

The Integer constant can be null, and so you don't need a special value for invalid, or not yet set fields. But according to constants this fact is no good argument.

The benefits ob Integer constants is that they have Methods on them, for parsing, and lots more and that the Integer constant pool can be used. For more informations take a look at this post: Java Integer: Constant Pool

duffy356
  • 3,678
  • 3
  • 32
  • 47
0

From the JavaDoc of the valueOf-method in the Integer class:

/**
 * 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
 */

So, it seems to be somewhat of a gain when the value of the int is [-128, 127], but in my opinion this is in most cases negliable, due to the high performance of computers these days. If you have a very, very performance-critical application you could gain from using it, otherwise I would just go with what provides the best readability (which is in my opinion auto-boxing.)

If auto-boxing uses the valueOf-method as it's being said in another answer, then there is no difference of course, the comparison above would then be Integer.valueOf vs new Integer.

Tobb
  • 11,850
  • 6
  • 52
  • 77
0

Java is a object oriented language... There are many tasks which could be performed on object but not on primitive data type...

For example Collections can only store objects...

You should see your company's next code maybe they would have used that constant as object somewhere or may be for future use they would have declared it as object...

Shailesh Yadav
  • 1,061
  • 1
  • 15
  • 30
-1

Since a int is a primitive it cannot have any methods called on it, unlike the Integer object.

Daniel
  • 1
-2

If you want to use SOME_CONSTANT to perform some operations, then I think declaring it as an int is better.

assylias
  • 321,522
  • 82
  • 660
  • 783
FireOct
  • 1
  • 1
-4

The Integer class offer some useful methods. For more information se the API : Integer Reference

Hope this help.

Daniele
  • 93
  • 6