devxlogo

Effective Usage of Variables in Loops

Effective Usage of Variables in Loops

For effective usage of variables in loops, it is advised to create variables outside of loops and use them in the loops. This helps save lot of memory and makes the execution faster.

The code below shows both the incorrect and correct ways of doing so:

public class VariablesInLoop{   public static void main(String args[])   {      VariablesInLoop variablesInLoop = new VariablesInLoop();      variablesInLoop.proceed();   }      private void proceed()   {      //For loop with incorrect variable usage.      //You should not create a variable within a loop       for (int i=0; i       {         String strValue = "StringValue-" + ++i ;         System.out.println(i + " : " + strValue);      }      System.out.println();      //For loop with correct variable usage.      //You should use a variable created outside a loop       String strValue;      for (int i=0; i       {         strValue = "StringValue-" + ++i ;         System.out.println(i + " : " + strValue);      }   }}/*

Expected output:

[root@mypc]# java VariablesInLoop1 : StringValue-12 : StringValue-23 : StringValue-34 : StringValue-45 : StringValue-56 : StringValue-67 : StringValue-78 : StringValue-89 : StringValue-910 : StringValue-101 : StringValue-12 : StringValue-23 : StringValue-34 : StringValue-45 : StringValue-56 : StringValue-67 : StringValue-78 : StringValue-89 : StringValue-910 : StringValue-10*/

devx-admin

Share the Post: