Prakash Raman
Prakash Raman

Reputation: 13933

.class == .class vs .class.toString() vs .class.toString()

I was playing around with Classname.class and Classname.class.toString() and found something unusual.

.class seems to equate to .class when run on the same Class. Although .class.toString() does not equate to the .class.toString() on the same class. Why would this be.

Please see my code below

public class HelloWorld{

    public static void main(String []args){
        if(String.class.toString() == String.class.toString())
            System.out.println("toString(): Yes they are the same");
        else
            System.out.println("toString(): They are not the same ?");

        System.out.println("=============================");

        if(String.class == String.class)
            System.out.println(".class: Yes they are the same");
        else
            System.out.println(".class: They are not the same");
    }
}

Output:

sh-4.3# javac HelloWorld.java                                                                                                                            
sh-4.3# java -Xmx128M -Xms16M HelloWorld       

toString(): They are not the same ?                                                                                                                      
=============================                                                                                                                            
.class: Yes they are the same

Upvotes: 1

Views: 78

Answers (3)

David Pérez Cabrera
David Pérez Cabrera

Reputation: 5068

Here, You're comparing references, not string content, and the references are not equals.

String.class.toString() == String.class.toString()

You must compare with equals:

String.class.toString().equals(String.class.toString())

Or You can compare with advance feature of string, like this:

String.class.toString().intern() == String.class.toString().intern()

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361849

Why do you expect that one toString() invocation would return the exact same object as a second invocation? Neither Object.toString() nor Class.toString() specifies in their Javadoc API documentation that the same String object will be returned in successive invocations.

Without a reason to do otherwise, one must assume the default contract that String instances must be compared with equals().

Upvotes: 2

Raman Shrivastava
Raman Shrivastava

Reputation: 2953

Because you don't use == operator to compare strings. Use .equals() method instead.

Upvotes: 4

Related Questions