Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equals for a Class. Is == same as .equals

Tags:

java

Can we do a == on a Class variable instead of equals and expect the same result?

For example:

Class clazz = xyz; 

Case A:

if(clazz == Date.class) { // do something } 

Case B:

if(Date.class.equals(clazz)) { // do something } 

Are Case A and Case B functionally same?

like image 732
Ramesh Avatar asked Sep 06 '11 15:09

Ramesh


People also ask

What is the difference between using == and .Equals on an object?

The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.

Why use .Equals instead of == Java?

Operators are generally used for primitive type comparisons and thus == is used for memory address comparison and equals() method is used for comparing objects. Show activity on this post. Both == and . equals() refers to the same object if you don't override .

What does .Equals mean in Java?

The equals() method compares two strings, and returns true if the strings are equal, and false if not.

Is .Equals the same as == C#?

Difference between == and . Equals method in c# The Equality Operator ( ==) is the comparison operator and the Equals() method in C# is used to compare the content of a string. The Equals() method compares only content.


1 Answers

Class is final, so its equals() cannot be overridden. Its equals() method is inherited from Object which reads

public boolean equals(Object obj) {     return (this == obj); } 

So yes, they are the same thing for a Class, or any type which doesn't override equals(Object)

To answer your second question, each ClassLoader can only load a class once and will always give you the same Class for a given fully qualified name.

like image 110
Peter Lawrey Avatar answered Oct 03 '22 21:10

Peter Lawrey