Wednesday, February 14, 2018

Java new operator with example

In this post you will learn how to use new operator in java with example.In Java, a new object is created from a defined class by using the new operator. The new operator creates a new object from a specified class and returns a reference to that object. In order to create a new object of a certain type, we must immediately follow our use of the new operator by a call to a constructor for that type of object.

Let us understand this topic with the following example:

public class Demo
{
public static void main(String args[])
{
Counter c;//declares the variable c to be of type Counter that means c can refer to any Counter object
Counter d=new Counter();//creates a new Counter object and returns a reference to it
c=new Counter();//creates a new Counter object and returns a reference to it
d=c;
}
}

Calling the new operator on a class type causes three events to occur:

  • A new object is dynamically allocated in memory, and all instance variables are initialized to standard default values. The default values are null for object variables and 0 for all base types except boolean variables (which are false by default).
  • The constructor for the new object is called with the parameters specified. The constructor fills in meaningful values for the instance variables and performs any additional computations that must be done to create this object.
  • After the constructor returns, the new operator returns a reference (that is, a memory address) to the newly created object. If the expression is in the form of an assignment statement, then this address is stored in the object variable, so the object variable refers to this newly created object.

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...