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.
Here are some example programs that uses the new operator :
- Get Input from User
- Add two Numbers
- Check Even or Odd
- Print Table of Number
- Print Prime Numbers
- Find Factorial of Number
- Find HCF LCM
- Print Fibonacci Series
- Check Palindrome or Not
- Find ncR nPr
- Transpose Matrix
- Multiply two Matrices
- Three Dimensional Array Program
« Previous Tutorial Next Tutorial »