Fill in the blank : Given two non-null String object with reference name apples and oranges, if apples _____________ oranges evaluates to true, then apples ______________ oranges must also evaluate to true.
A. ==, equals()
B. !=, equals()
C. equals(), ==
D. equals(), ==
I choose the option C. but it is wrong Why. can explain it.
It is as simple as if == returns true, that means the two objects referring to the same string in the pool as that is how String works if you defined it as follows:
String apple = "red";
String tomato = "red";
If == returns true, which it would in this case, equals() also will return true.
If you defined it as follows:
String apple = new String("red");
String tomato = new String("red");
Each reference will get a separate object in the memory and == will return false, but equals() will still return true and that is why your answer is not correct.
The == operator has nothing to do with the String pool; it tests whether the two memory locations are the same for any reference types.Neither s0 nor s1 is interned in the String pool, but that test will still print true. KeyboardInputs is a utility class of mine.
I agree with you. The == has nothing to do with the String pool, defining the String as String obj = "obj" does.
Doing so will set the value in the pool and will be available for any other String initialization using only = "obj".
The == will come next as it will be able to test that the two reference objects pointing to the same memory location, which is the value in the pool.
posted 4 weeks ago
Not certain, but I think String literals and other String compile‑time constants are put into the String pool when the class is loaded. As I said, not certain.