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*/
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist