1

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
Prakash Raman
  • 13,319
  • 27
  • 82
  • 132
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Vince Jun 30 '15 at 19:24

3 Answers3

4

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

Raman Shrivastava
  • 2,923
  • 15
  • 26
2

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().

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1

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()
David Pérez Cabrera
  • 4,960
  • 2
  • 23
  • 37