Java new Operator

The new operator allocates memory dynamically for an object. Here is the general form to use new operator in Java:

class-var = new classname();

Here, class-var is the variable of the class type being created. The classname is the name of the class that is being instantiated.

The class name followed by the parentheses determines the constructor for the class. A constructor defines what occurs whenever an object of a class is created.

Constructors are an crucial part of all the classes and have many significant attributes.

Most real-world classes explicitly define its own constructors inside their class definition. However, if no explicit constructor is stated, then Java will automatically supply a default constructor. This is the case with Box. For now, we will use the default constructor. Shortly, you will see how to define your own constructors.

It is important to understand that the new operator/keyword allocates memory for an object during run time. The advantage of this approach is that your program can create as many/few objects as it needs during the execution of your program. However, since memory is finite, it is possible that the new will not be able to allocate memory for an object because insufficient memory exists. If this will happen, a run-time exception will occur.

Examples

Here are some example programs that uses the new operator :

Java Online Test


« Previous Tutorial Next Tutorial »