5 Replies Latest reply: Oct 13, 2009 5:42 PM by EJP RSS

    (Final) primitive used inside anonymous block

    807580
      Hello,
      I found a strange behavior when I use primitive variable inside the anonymous code.
      public class Test {
           
           
           private Runnable printer;
           
           public void print(final int i){
                if (printer == null){
                     printer = new Runnable() {
                          
                          public void run() {
                               System.out.println(i);
                          }
                     };
                }
                new Thread(printer).run();
           }
           
           
           public static final void main(String[] aregs){
                Test t = new Test();
                for (int i = 0; i <10 ; i++){
                     t.print(i);
                }
           }
      }
      It is always printing 0!!
      It keeps the first value of the variable when I make the printer as member! I know that the variable [i] is marked as final,*
      But even though; (final) makes sure that this parameter will not change, so logically it should print [i] according to the passed value, am I right? Can somebody explain?


      Thanks

      Bassel