-2
class Point{
   int x;
   int y;
   Point (int x,int y)
   {
      this.x=x;
       this.y=y;
   }
}




public static void main(String args[])
{
   Point p =new Point (2,3);
   Point p1 = new Point(2,4);
}

If I create two objects of this Point class and then again create another object of the Point class then will the last Point object that is p will get delete or will remain ??

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Clayton
  • 43
  • 3

2 Answers2

3

In Java, as in many other languages, there is something called "object scope", which actually represents the lifecycle of an object. In particular, if you instantiate an object inside a specific block of code, that represents the scope of your object, and your reference will be valid as long as the block is executed.
After reaching the first line outside that block, your reference is taken in charge by the "Gargage collector", which basically is the mechanism in Java responsible for cleaning up the memory from all those objects which don't have any reference inside your program and, thus, you don't need it anymore.
In your particular case, as there are the only two stetements of program, both references will be valid for the entire program.
However, there is a scenario in your simple program which can make you loose one reference see this piece of code:

 public class Point{
   int x;
   int y;
   Point (int x,int y)
   {
      this.x=x;
       this.y=y;
   }
}

public static void main(String args[])
{
   Point p =new Point (2,3);
   p = new Point(2,4);
}

As you see, because I have assigned the second object Point to the same reference p, the first one will be lost and, thus, automatically handed over to the garbage collector to be freed from the memory.

However, the above code was just one of the example of the technique you can use to make an object get taken in charge by the Garbage collector. I suggest that you have a look at the answer Deleting object in Java? where you will find more examples and different techniques.

Marco Tizzano
  • 1,726
  • 1
  • 11
  • 18
0

Java do remove object whenever they are not need anymore. In this case as long as your program runs inside the main method, the Point objects will not be removed.

TheCink09
  • 11
  • 1