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.

awfun
  • 2,316
  • 4
  • 31
  • 52
  • It is not a object. It's a local or class variable. – Saurabh Sharma Jan 09 '14 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. – user2336315 Jan 09 '14 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. – T.J. Crowder Jan 09 '14 at 12:38

4 Answers4

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.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
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.

blackpanther
  • 10,998
  • 11
  • 48
  • 78
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.

Qadir Hussain
  • 1,263
  • 1
  • 10
  • 26
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.

gowtham
  • 977
  • 7
  • 15
Saurabh Sharma
  • 489
  • 5
  • 20