tags:

views:

100

answers:

5

shouldn´t one pass an object to equal?

    String hej = pets.getBark();
    if(hej.equals("woff"))

why are you able to pass a string woff?

+2  A: 

A quoted string is an object. It is an instance of the String class.

rayd09
+5  A: 

If I understand your question properly you are wondering why a literal string value can be passed to a method that accepts an argument of type String. This is because a string literal is a shorthand for a String instance (either a new instance or a previously created instance that has been preserved by means of interning):

The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Andrew Hare
+2  A: 

Under the hood, a string literal ( text inside quotes ) automatically is replaced by String instance. ( a string literal is shorthand for new String )

That is why this code works: String hello = "hello";

So,

 String hej = pets.getBark();
 if( hej.equals( new String("woff") ) ) {}

is identical to the code you provided.

Jacob Relkin
It's actually not exactly the same as that, due to string interning, IIRC.
Noon Silk
+1  A: 

A literal string is still of type String.

BobbyShaftoe
+2  A: 

You can pass java.lang.String, a subtype of java.lang.Object, because Liskov substitution principle says so.

Chandra Patni
Not what the OP asked, but still a good point.
Jacob Relkin