Showing posts with label Java Allocating Memory using Operator new. Show all posts
Showing posts with label Java Allocating Memory using Operator new. Show all posts

Saturday, 30 May 2015

Java Allocating Memory using Operator new

The memory for Java objects is always allocated dynamically with the help of new operator. For
example, an instance/object of the class Box can be created as follows:

Box box = new Box();

For the sake of understanding we can compare new operator with the malloc() of C. In the above
example, new operator will allocate memory for an object of class Box and return its reference, which is then assigned to reference type variable box. The reference type variable box will now refer to an object of type Box as shown below:

The new Operator


It is important to understand that new allocates memory for an object during runtime. Since memory is finite, it is possible that new may not be able to allocate memory for an object because in-sufficient memory exists. If this happens, a run-time error will occur.