1

Is there any difference between

for (...) {
  String temp = "temp";
}

and

String temp;
for (...) {
  temp = "temp";
}

I mean, does Java waste many resources creating/deleting objects in loop?

Thank you.

3
  • It is not a object. It's a local or class variable. Jan 9, 2014 at 12:36
  • 1
    I wouldn't rely on this and prefer readability. If temp has to be used only in the for loop, use the first. Jan 9, 2014 at 12:36
  • Your question only shows setting temp to a literal string, making it a loop-invariant. Is it really? There's a big difference between that and just about anything else you might do with temp. I'd clarify the question if I were you. Jan 9, 2014 at 12:38

4 Answers 4

3

The difference is in scope of variable.

  • Defined inside loop means visible only inside the loop.

  • Defined outside the loop means visible inside and outside the loop.

does Java waste many resources creating/deleting objects in loop?

if defined inside the loop then it will be re-intialized with every iteration, which means an extra executable statement. If you want to re-intialize it with each iteration then good otherwise move it out to save wasted cpu for that statement.

0
1

The only difference is the issue of scope. With the variable being declared outside the for-block, the variable (object reference) can be accessed outside the for-loop block.

If the object reference variable is declared inside the for-loop, then it can only be accessed within the for-loop block.

0

First the two scope variables.

  1. define inside the loop will be visible only to loop.
  2. define outside the loop will be visible to inside and outside the loop

Java waste many resources creating/deleting

Java creates as many objects of String as many times you are iterating your loop but the reference will be same. So its a bit resource and memory consuming. Use StringBuilder or StringBuffer.

0
for (...) 

{

String temp = "temp";

}

In this case your temp would be available only for For loop

String temp;

for (...)

 {

  temp = "temp";

}

And here If you are writing this code inside a method then it would be available throughout the method.

Note:- Local variables are created in Stack and are removed after execution of that method.

Not the answer you're looking for? Browse other questions tagged or ask your own question.