How can we find out the size of a java object??
Example:
class Person{
String name;
int age;
public Person(String n, int a){
The question is not meaningful, at least not without further context.
The notion of "size" in Java is only reasonably well defined for primitives: A byte is 8 bit (unsurprisingly) an int is 32 bit, a long 64bit, etc. (see e.g. http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html for a full list).
For object instances, it's more complicated, because:
java.lang.String, see http://en.wikipedia.org/wiki/String_interning ). So if you use x objects of size y, the total size may be smaller than x*yMaybe you could explain why you are interested in object sizes.
There are some rules of thumb for estimating the heap memory used by instances (e.g. in the Sun JVM, a java.lang.Object instance uses 8 byte), but these will depend on the JVM you use.
Generally, if you want to know about your heap usage, use a memory / heap profiler.
Edit:
Well, there is (as of JDK 6) a way to get an approximation of the amount of memory used by an object: http://download.oracle.com/javase/6/docs/api/java/lang/instrument/Instrumentation.html#getObjectSize%28java.lang.Object%29
It's still only an approximation...