• Post Reply Bookmark Topic Watch Topic
  • New Topic

To the get the size of a data type.  RSS feed

 
Sunesh Kumar
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friends,

How to find the datatype size in JAVA
for ex: int ->4bytes like that....


I tried for the method getSize(); but no use...

Can you please provide any idea...


Bye
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This has been discussed many times on JavaRanch. Please search the various forums, or use Google, to find full discussion.

The short answer is that you cannot find the size in memory of a Java data type, and 99% of the time, you do not need to do so. For the 1%, there are ways you can use to estimate it, but do be sure you really need to do so.

Do you, by any chance, come from a C or C++ programming background?
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are looking for the size of primitives, it should be in just about any reference book or web site on java. I'd try googling or the wikipedia.

If you need to know the size of a class (either one you create or one provided by a third party), I would say "why do you think you need to know?", as there is probably a better way of doing what you think you need to do.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by fred rosenberger:
If you are looking for the size of primitives, it should be in just about any reference book or web site on java. I'd try googling or the wikipedia.


I'm sure you know, but the Original Poster may not know that the specified sizes are not necessarily the sizes in memory.

For instance, a Java "int" has to represent a 32-bit signed integer. That does not mean that it has to take up 32 bits in memory. It cannot take up less, because that is (almost) impossible. It can take up more than 32 bits, and might well actually do so, on a 64-bit or better machine.

Perhaps the data type most likely to take up more memory than its apparent size would suggest is "short". This represents a 16-bit signed integer, but might very well be stored in a 32-bit memory word.

Generally, though, you should not worry about this stuff. Java tells you exactly what the data types represent, and it rarely matters what happens in the real memory.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!