There are a few key pieces of information that you need to understand to be able to answer this question. Some of this information is fair game for the exam and some is not.
Let's start with what
is fair game for the exam. Strings are immutable. That means that a String object can never be changed. So what happens when you invoke a method such as "replace" which seems to change the String? Well, it returns a brand new String object, of course. You see that with the first couple lines of your example - even though invoked replace() on s1, you see a couple lines later that s1 has remained unchanged.
Secondly, you must understand how the "==" operator works. With primitive types, it will check to see if the values of those primitives are the same. With reference types, however, it checks to see if the two reference variable refer to the same object. Note that it doesn't check to see if the two objects are "equal," it checks to see if both variables refer to the same object. It's really checking the reference value of each variable. You can read
this for some more info, if you'd like.
So now we'll look at the information that
isn't on the exam. Because Strings are immutable in
Java, there is an optimization that is used to save space - the String literal pool. The String literal pool is basically a table of constants. Any time a String literal is found in your code, a new entry is added to the pool and that String object is created on the heap. From that point on, if you have the same String literal in your code, that literal will reference the exact same object as the previous one, thus saving some memory space.
So, what does that mean for your code? Well, look at these lines:
The String "arit" is a String literal so this is added to the String literal pool. As s3 and s4 both refer to this String literal, they both refer to the
exact same object. The variable s2 refers to a String object with the contents "arit", but it didn't get this value from a String literal so it actually references a different object on the heap than s3 and s4.
Now, in the final 2 lines, we're using the "==" operator, which is checking reference values, not the contents of the String objects. If any two reference variables reference the same object, this operator will return true. Otherwise, it will return false.
As we already saw, s3 and s4 reference the same variable so this line returns true. The variable s2, on the other hand, refers to a different String object (even though it contains the same value) so the second comparison returns false.
For an added exercise, try this and see if you can explain the results: