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


Tip of the Day
Language: Java
Expertise: Intermediate
May 25, 2018

WEBINAR:

On-Demand

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


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 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

*/
M S Sridhar
 
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