0
SomeClass classvar = new SomeClass(); --> Object classvar = new SomeClass(); --> Object 2 

So what I understand about JAVA is that , in the first line, classvar object of SomeClass is created. In the next line, there is another object created of classvar.

My Question - What will be changed here? Will the reference of classvar object be updated due to second line ORR the object created in line 1 will be garbage collected?

EDIT: adding code tags

3
  • Do you mean SomeClass classvar = new SomeClass(); classvar = new SomeClass();? Commented Dec 23, 2014 at 22:56
  • And what is actually your question? I don't get it... Commented Dec 23, 2014 at 22:58
  • @Elist Thats fine. I got the answer.. I meant to ask what you wrote in your first comment. Commented Dec 23, 2014 at 23:01

2 Answers 2

2

I think you might be asking about:

SomeClass classvar = new SomeClass();// --> Object 1 classvar = new SomeClass();// --> Object 2 

And if that is the case, then the first SomeClass object that was created will lose its reference and will eventually be garbage collected (this means that the object is destroyed to free up memory).

And the classvar variable will now reference the second SomeClass object that was created.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. I was asking this same thing. Thank you.
1

That is a compile error you cannot have two variables of the same name in java

if you meant

SomeClass classvar = new SomeClass(); --> Object 1 classvar = new SomeClass(); --> Object 2 

then the first objects reference the the first Object will get overwritten with the new reference. And the next time the gc runs it will be deleted.

4 Comments

OK, What will happen in this case --> SomeClass var = new SomeClass(); var = new SomeClass(); Will there be two objects created, where the first object now have an empty reference?
@akshayrajkore what case?
change your question to reflect what you said in your comment because they don't match. see both of the current answers as mine and Andre perkins answers are basically the same
Done.. Thank You. Appreciate your help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.