Yes it will always return true. But static has nothing to do with it. It would always return true even if declared as an instance field. And using String FOO = new String("foo") would also return true because in all cases you are returning the same instance from func1() so you are basically doing:
System.out.println(FOO == FOO);
The difficulty is when you want to compare multiple different instances of "foo" to FOO.
String FOO = new String("foo"); // static or not
public String func1() {
return "foo";
}
System.out.println(func1() == FOO);
Prints false since "foo" is a string literal and as such is put in the string pool and FOO is not. So you're comparing a string pool reference to some other reference of the same String.
System.out.println(new String("foo") == new String("foo")); //false- different refs
System.out.println("foo" == "foo"); // true - same refs via string pool
prints
false
true
Remember, the same String literals always return the same reference.
System.out.println(System.identityHashCode("foo"));
System.out.println(System.identityHashCode("foo"));
System.out.println(System.identityHashCode("foo"));
System.out.println(System.identityHashCode("bar"));
System.out.println(System.identityHashCode("bar"));
System.out.println(System.identityHashCode("bar"));
prints something like
1995265320
1995265320
1995265320
746292446
746292446
746292446
FOOand the return value offunc1()are references to objects. Both of those will evaluate to the same reference value.if(func1() == FOO)becomesif(func1() == "foo")- as if the string is copied in as text (which makes me worry it's a different string object). Note: I am aware that optimizing compilers will make it the same object, my question is does the language spec guarantee this.