Reputation: 79806
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?
Upvotes: 0
Views: 343
Reputation: 17587
You can pass java.lang.String
, a subtype of java.lang.Object
, because Liskov substitution principle says so.
Upvotes: 2
Reputation: 163308
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.
Upvotes: 2
Reputation: 351688
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.
Upvotes: 6
Reputation: 1897
A quoted string is an object. It is an instance of the String class.
Upvotes: 2