2

I am a little confused, I learned that Strings are objects, therefore to compare them you should use String#equals.

My question is: if I have a String as an attribute, is it an object?

To clarify my question:

Class A {
    public String nom; 
    A(nom) {
        this.nom = nom;
    }
 }

... and in the main method:

 A a = new A("Sara");
 A b = new A("Youssef");
 A c = new A("Sara");

 a.nom == b.nom; ==> false
 a.nom == c.nom; ==> true

Therefore, is the comparison of Strings' values more like c++, i.e. not about their references?

Mena
  • 47,782
  • 11
  • 87
  • 106
  • 2
    A String is an object regardless of where it is defined. Class level, method level, etc.. Your code won't compile by the way because you need to declare the parameter type of your constructor `A(String nom)` – Kon Jan 13 '16 at 00:41
  • That main function is probably faulty. You should not compare Strings in Java using `==` (you could, the compiler won't complain, but most likely it won't work properly). – Thilo Jan 13 '16 at 00:42
  • @Yoda not sure this is a real duplicate. More like a counter-example, where the `==` operator returns `true` arbitrarily in my opinion. I.e. OP seems aware of the requirement to use `equals` for `String` comparison. – Mena Jan 13 '16 at 00:44
  • More likely duplicate of [What is the difference between “text” and new String(“text”)?](http://stackoverflow.com/q/3052442/5037042) – Iltis Jan 13 '16 at 00:45
  • By the way the syntax is correct and it did compile for that reason i asked – Badr Mohamed Jan 13 '16 at 00:47
  • There is plenty of info on this in the canonical string compare Q&A. If it's still not clear, highlight a specific remark you have. – Jeroen Vannevel Jan 13 '16 at 00:49

1 Answers1

3

Assuming your constructor assigns its argument value to the instance variable nom...

The fact that a.nom == c.nom is arbitrary and due to the fact that literal "Sara" has been interned (or cached).

This doesn't mean you should ever expect consistent results when comparing Strings other than with the equals method.

Mena
  • 47,782
  • 11
  • 87
  • 106
  • Thank u for the reply would you please clarify this part "The fact that a.nom == c.nom is arbitrary and due to the fact that literal "Sara" has been interned (or cached)." – Badr Mohamed Jan 13 '16 at 00:55
  • @BadrMohamed you can refer to [this](http://stackoverflow.com/questions/10578984/what-is-string-interning) SO question about Java `String` interning (and its top-rated answer) for more information. – Mena Jan 13 '16 at 00:57
  • Last question : when you use Assignment operator this.nom = nom; is it like nom=new String("nom") or nom="nom" – Badr Mohamed Jan 13 '16 at 01:29
  • More like the latter: the idiom assigns as a value to this nom the reference of given argument nom. – Mena Jan 13 '16 at 07:37