ajsie
ajsie

Reputation: 79806

equals() method?

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

Answers (5)

Chandra Patni
Chandra Patni

Reputation: 17587

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

Upvotes: 2

BobbyShaftoe
BobbyShaftoe

Reputation: 28499

A literal string is still of type String.

Upvotes: 1

Jacob Relkin
Jacob Relkin

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

Andrew Hare
Andrew Hare

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

rayd09
rayd09

Reputation: 1897

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

Upvotes: 2

Related Questions