dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Effective Usage of Variables in Loops

Learn how to make effective usage of variables in loops.


advertisement

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 VariablesInLoop
1 : StringValue-1
2 : StringValue-2
3 : StringValue-3
4 : StringValue-4
5 : StringValue-5
6 : StringValue-6
7 : StringValue-7
8 : StringValue-8
9 : StringValue-9
10 : StringValue-10

1 : StringValue-1
2 : StringValue-2
3 : StringValue-3
4 : StringValue-4
5 : StringValue-5
6 : StringValue-6
7 : StringValue-7
8 : StringValue-8
9 : StringValue-9
10 : StringValue-10

*/

 

Visit the DevX Tip Bank

 



   
Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date