dcsimg
LinkedIn
Google+
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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


advertisement
 

Tip: Effective Usage of Variables in Loops

Learn how to make effective usage of variables in loops.


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date