＜本文发表于: 相约加拿大:枫下论坛 www.rolia.net/f ＞
Java is a very "simple" language.
In Java, if you create an Object and don't assign it to some reference, it will be an "orphan" Object. It means it is abandoned and it is subject to garbage collection. Of course, JVM can generate some internal references for an Object, but this is transparent to us, application programmers.
You have listed 4 cases. 2), 3) and 4) are meaningless, no matter what results you get.
Operator == is used to check if two references point to the same Object in the same JVM. In your case 2-4, you played the game agaist this rule. In some case, you pass because of the internal implementaion of JVM. In practice, no Java programmers write code of type 2), 3) and 4).
Now about your case 1). You created two different Objects (Strings) in JVM. They have two different references "s1" and "s2". You compared s1 and s2. This should return false. However, you don't pick up this return value, so your comparison is much ado about nothing. In other word, your comparison has no effects.
Reference is widely used in the conditionals such as
I advise you stop thinking about case 2, 3, and 4). You cannot find similar code in practice. Thinking about them does not help you understand Java.
In Passing, I mention the folllowing is OK though we don't give a reference to the created Object. See:
System.out.println(new String("abc").toUpperCase());＜本文发表于: 相约加拿大:枫下论坛 www.rolia.net/f ＞