0

I am new to Java.

I want to ask about object initialization. First, I make a class.

public class A {

    ....

}

Then at the main class, the A class is instantiated.

A a = new A();

Now, the question is, whether these two codes are the same?

A aa = a;

and

A aa = new A();
1
  • Not the same - in first case - two references point to the same object, in the second case, two separate A objects. Commented Apr 29, 2014 at 9:01

4 Answers 4

1
A aa = a 

will make a reference to object a, however

A aa = new A();

will make a new object of type A.

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

Comments

0

No they are totally different!

A aa = a;

Then aa and a refert to the same object in memory.

A aa = new A();

Then aa is a new object. And you have now two objects on the stack.

Comments

0
A a = new A();
A aa = a;

aa refers to the same object a.

A aa = new A();

about statement created new object of type A which is different from the a.

Comments

0

No, they are different. While A aa = new A(); creates a new Object of type A, A aa = a; just passes the reference of a to aa, which means, those two point to the same Object. You can verify this by printing the hashcode of a and aa.

In the first case A aa = a; calling hashCode() on both aa and a will yield the same result, since both point to the same Object.

In your second case A aa = new A(); calling hashCode() will yield different results, since you're creating a whole new instance of A.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.