== and .equals clone()

Can someone tell me precisely the difference between == and .equals(). Also, tell me what is clone() do.

Who is Participating?
Jim CakalicConnect With a Mentor Senior Developer/ArchitectCommented:
That is correct. When used with references, the '==' operator will return true only when the two object references are the same. That is to say, both references are to the same object on the heap. In contrast, the equals method permits individual classes to define what constitutes object equality at the value level.

The example cited in the previous post was Strings. Two string objects are equal per the equals operator (==) when they refer to the same actual String object in memory. Two separate String objects may be equal in value/contents and that can be determined by using the equals method.

It should be noted that the java.lang.Object default implementation of the equals method returns true for object references x and y only if x and y refer to the same object. So if a class or one of its superclasses does not override the equals method, the default implementation provided by Object will be used, thus making the equals operator and equals method functionally equivalent.

As for clone, this method, when implemented by a class, permits a copy of an object to be created and returned without calling any constructors. This typically requires creating a new instance of the class and copying of internal data structures. Depending on the network of contained objects, the clone can be either shallow or deep. A shallow clone results in two objects that refer to the same dependent objects. As for example if you were to clone a Vector, both Vectors would refer to the same collection of objects that existed at the time of the cloning. A deep copy would clone/copy the underlying objects as well resulting in separate and distinct object networks. For design guidance and implementation examples of clone, see:

Best regards,
Jim Cakalic
For strings I believe == checks if the object is the same and .equals checks for the same value.

For instanse
String one = "value";
String two = "value";

if (one == "value")    // false

if (one.equals("value") // true
All Courses

From novice to tech pro — start learning today.