-2

I know that in Java we can use generic data types for various reasons. However, in terms of data storage. If a primitive int in Java can store up to 2,147,483,647 signed values, does this same storage capacity apply for the Integer generic type? Also, does the data type chosen in a program affect the runtime in any way? Or does it more so affect the space-time complexity of a program? My main question is that if I stick with a data type that is rather small but appropriate for my programs needs, than will it by any means help my program run faster?

  • As per javadocs *The Integer class wraps a value of the primitive type int in an object.* If you want bigger use BigInteger – Scary Wombat Feb 19 '20 at 02:51
  • This might answer your main question about speed https://stackoverflow.com/questions/5069489/performance-of-built-in-types-char-vs-short-vs-int-vs-float-vs-double – Zen Monkey Feb 19 '20 at 02:56
  • This is a similar question but Java specific https://stackoverflow.com/questions/19155035/which-of-the-following-is-the-fastest-data-type-in-java – Zen Monkey Feb 19 '20 at 03:01

2 Answers2

1

Yes, the limitations are still there.

You shouldn't treat Integer like this magical object, all it is is an object that holds an int called value. So, without auto-boxing and unboxing, you could technically create your own Integer wrapper class. What to take away is Integer is pretty much the exact same as int, except it's an object.

About your main question about the speed, Integer is just a tiny bit slower, but I don't think you should worry about it. It's only slower because Objects need to be allocated in the heap space.

0

Yes, the same limitations apply.

You can see the source of the Integer class here:

http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/Integer.java

Line 840 shows that an Integer is backed by a simple int:

private final int value;

So whatever restrictions an int has, an Integer also has.

Malcolm Crum
  • 4,345
  • 4
  • 30
  • 49