How big is an Object in Java? Why Java neglects sizeof?
I had used C, C++ programming languages in past. I have made several projects in both the prgramming languages. But now I have been given o new project to be made using Java. The problem is that while working on this project I have learnt that Java doesnot has any sizeof() operator as we have in C. Is there any other altenative for this ? Why Java doesnot has a sizeof() operator?
Re: How big is an Object in Java? Why Java neglects sizeof?
The other way instead of using the sizeof() operator which Java doesnot support you can do the following:
Code:
static Runtime rt = Runtime.getRuntime();
.
.
.
long begin, finish;
Object O;
rt.gc();
begin = rt.freememory();
O = new Object();
finish = rt.freememory();
System.out.println("This had taken " + (begin-finish) + "bytes.");
This method although has a short coming that a garbage collection could occur in the middle of the code which you are instrumenting. This will throw off the byte count.
Re: How big is an Object in Java? Why Java neglects sizeof?
Initially when Sun developed Java there was absolutely no way to measure the size of an object. Memory allocation and object construction in Java are both binded together. Thus, making it difficult to get the size of the object. Programmers later on developed an indirect way to get the size of the object. This was by measuring the difference in the memory used by the program before and after creating the object. This difference thus indicated the actual size memory of that object.
Re: How big is an Object in Java? Why Java neglects sizeof?
A programming language like C has a sizeof operator. This is because the C user has to manage calls to malloc(). And this is since the size of primitive types is not standardized. Whereas in Java the allocation of memeory and construction of object are both binded together This is the reason why Java doesnot needs a sizeof operator.
Re: How big is an Object in Java? Why Java neglects sizeof?
instead of size of() JAVA uses .length() as follows:
int[] cars = {"ford", "chevy", "honda"};
for(int j = 0; j <= cars.length; j++)
System.out.print(cars);
that will take the array length and use that as the size of