When i make 2 object for a same class, and then i make one object equal to another, then changes made to one object affect another object also, then when i assign one object as "null" then why the change is not made to another object as well?
Here is my code for BoxMain.java

package object_assignment;

public class BoxMain 
{
 	public static void main(String[] args) 
	 {
	   	Box yellowbox=new Box();
	   	Box redbox=new Box();
	   	yellowbox.height=12;
	   	yellowbox.width=11;
	   	yellowbox.length=22;
	   	redbox=yellowbox;
	   	System.out.println("volume yellowbox="+(yellowbox.height*yellowbox.width*yellowbox.length));
	   	System.out.println("volume redbox="+(redbox.height*redbox.width*redbox.length));
	   	redbox.height=15;
	   	redbox.width=11;
	   	redbox.length=21;
		System.out.println("volume yellowbox="+(yellowbox.height*yellowbox.width*yellowbox.length));
	   	System.out.println("volume redbox="+(redbox.height*redbox.width*redbox.length));
	   	yellowbox.height=1;
	   	yellowbox.width=11;
	   	yellowbox.length=2;
	   	System.out.println("volume yellowbox="+(yellowbox.height*yellowbox.width*yellowbox.length));
	   	System.out.println("volume redbox="+(redbox.height*redbox.width*redbox.length));
	    redbox=null;
	    System.out.println("volume yellowbox="+(yellowbox.height*yellowbox.width*yellowbox.length));
	   	System.out.println("volume redbox="+(redbox.height*redbox.width*redbox.length));
	 }

Here is Box.java

package object_assignment;

public class Box 
{
  int height;
  int width;
  int length; 
}

So when this is executed it runs suucessfully but later causes an nullpointerexception.Now i know exception handling, but my doubt is that why the assignment of null to one aobject is not reflected in other object?

You are confusing Objects with variables. A variable is reference (pointer) to an Object. You can't assign null to an Object - that doesn't even make sense. You can assign null to a variable - it means that the variable stops referring to an Object and now refers to nothing.

Box yellowbox=new Box();
Box redbox=new Box();
...
redbox=yellowbox;

You create two Box objects by executing new Box() twice. Variable yellowbox refers to the first Box, and redbox refers to the second Box. But then you copy yellowbox to redbox, so now both variables refer to the same object (the first Box). You no longer have a reference to the second Box, so you can never use it in any way, and it will be garbage collected.
Some time later you assign

redbox=null;

Now redbox refers to nothing, and if you try to use it you will get a null pointer exception. The Object is not affected by that statement, and yellowbox continues to refer to it.

Ok Thanks i got it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.