Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

size of reference

 
amar nath jha
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any way to know the size of reference in java?

example:

Light light = new Light();

can we know the size of light .
 
Pravin Jain
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
have a look at

campfire stories
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reference (as opposed to the object instance) is four bytes. This should be specified somewhere in the JVM specification. In some cases it may actually take up more than four bytes - e.g. 8 bytes on a 64-bit machine - but it will still behave as if it's only got four bytes available.
 
Bert Bates
author
Sheriff
Posts: 8900
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,

I'm a little suspicious of this question I guess it might be interesting from a trivia perspective, but, unlike the C language, there is absolutely nothing you can do, programmatically, with this information. I think that Jim is right, for most JVMs, but certainly there is no guaranteed correct answer to this question. Also, I wonder if Jim's answer is less likely to be true in J2ME environments?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Coming from other languages with a sizeOf operator or function, I missed the feature in Java. A few times it has seemed important to know things like "how big is your Session data" on a web server. But we're really gotten along quite well without knowing exact byte counts.

If you have to hunt down large objects that cause memory trouble or evaluate whether one design uses more memory than another we could talk through some tricks with garbage collector logs and such. The Java Specialist newsletter has done some work with this, too.

But, in short, the number of bytes used by an object is not something Java folks tend to need to know in detail.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic