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