0

How can we judge the size of Integer Class Object ? for example : Integer i = new Integer(10); so in the above case what is the size of 'i'. Does it valid ??

Raymond Chen
  • 44,448
  • 11
  • 96
  • 135
katanor
  • 1
  • 2
  • What programming language? What do you mean by "size"? – Raymond Chen Sep 17 '14 at 13:52
  • Related to Java .Size here indicate how much memory does Integer Object occupy at runtime . – katanor Sep 17 '14 at 13:55
  • Depending on the scenario, it could be zero (enregistered), or it could be very large (boxed). Why does it matter to you? – Raymond Chen Sep 17 '14 at 14:19
  • See this http://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object – Nabin Sep 17 '14 at 14:22
  • Writing `new Integer(10)` is [probably a bad idea](https://stackoverflow.com/questions/2974561/new-integer-vs-valueof). Especially if you are concerned about memory usage. Use `Integer.valueOf(10)` instead. – 5gon12eder Sep 17 '14 at 14:44

1 Answers1

1

Java has a pool of Integer constants between -128 and 128. Integer values in that range don't take up any additional space.

Integer values outside that range take as much space as an object header + 4 bytes. How big that is depends on your JVM and settings. Look at http://sourceforge.net/projects/sizeof or https://code.google.com/p/memory-measurer if you want to programmatically measure the size.

Edit: Note that Integer i = new Integer(10); will not use the object constant pool. That's why you should always use Integer.valueOf(x) instead of new Integer(x) when instantiating. Note also that autoboxing already does the right thing, so Integer i = 10 will also use the constant pool.

llogiq
  • 13,815
  • 8
  • 40
  • 72