dcsimg
 

Submitted by: M S Sridhar(sridhar.ms@gmail.com)

Friday May 25th 2018 by M S Sridhar

Language: Java, Expertise: Intermediate - Learn how to make 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

*/
Home
Mobile Site | Full Site
Copyright 2018 © QuinStreet Inc. All Rights Reserved