You hit some dark corners...

jabber (jabber)
<本文发表于: 相约加拿大:枫下论坛 >
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

if(s==null) {
//do sth

if(s1==s2) {
//do sth

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:

new Timer().start();

System.out.println(new String("abc").toUpperCase());
<本文发表于: 相约加拿大:枫下论坛 >

2001-1-3 -04:00

回到话题: Help: the following doesn't compile, why?

回到论坛: HOME枫下论坛枫下论坛主坛工作学习IT技术讨论