It is clearer now you have provided the output.
You can look at the compiled byte code to see why.
public static main([Ljava/lang/String;)V throws java/lang/Exception
L0
LINENUMBER 48 L0
ICONST_1
ISTORE 1
L1
LINENUMBER 54 L1
FRAME APPEND [I]
NEW Main$Robot
DUP
NEW java/lang/StringBuilder
DUP
INVOKESPECIAL java/lang/StringBuilder.<init> ()V
LDC "Rajni - "
INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
ILOAD 1
IINC 1 1
INVOKEVIRTUAL java/lang/StringBuilder.append (I)Ljava/lang/StringBuilder;
INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
INVOKESPECIAL Main$Robot.<init> (Ljava/lang/String;)V
ASTORE 2
L2
LINENUMBER 55 L2
LDC 1000
INVOKESTATIC java/lang/Thread.sleep (J)V
GOTO L1
L3
LOCALVARIABLE sdf [Ljava/lang/String; L0 L3 0
LOCALVARIABLE i I L1 L3 1
LOCALVARIABLE robot1 LMain$Robot; L2 L3 2
MAXSTACK = 4
MAXLOCALS = 3
The important line to note is the scope of the robot1
variable which is between L2
and L3
i.e. only during the Thread.sleep(1000);
and the local variable is out of scope as soon as the loop jumps back to L1
This means the variable in reality is available to be GC-ed at the top of the loop, not after the new Robot has been created as you might imagine.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…