Java equivalents of malloc(), new, free() and delete (ctd)Continued from our introduction to memory management operators in C/C++ and Java. The new keywordThe new operator is somewhat similar in the two languages. The main difference is that every object and array must be allocated via new in Java. (And indeed arrays are actually objects in Java.) So whilst the following is legal in C/C++ and would allocate the array from the stack... // C/C++ : allocate array from the stack void myFunction() { int x[2]; x[0] = 1; ... } ...in Java, we would have to write the following: // Java : have to use 'new'; JVM allocates // memory where it chooses. void myFunction() { int[] x = new int[2]; ... } Internally, the JVM chooses where the memory is actually allocated (stack, "young generation" heap, "large object" heap etc). A super-optimised JVM could even allocate the two-element array to two registers if circumstances permitted. But to the programmer, the array is allocated from "the heap". Next: the delete operatorUnfortunately, the similarity between the new operator of C++ and Java is not shared by the delete operator, which Java does not have at all. On the next page, we discuss the reasons for the absence of this keyword, and what Java equivalents of the delete operator, if any, there are. Written by Neil Coffey. Copyright © Javamex UK 2008. All rights reserved. |