File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Question on for loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Question on for loop" Watch "Question on for loop" New topic

Question on for loop

Manikandan Dharmarajan

Joined: Jan 31, 2002
Posts: 6
I have a question on for loop
I have to create an objects, String and primitive which has to be made as null ( or default values) at starting of each for loop iteration. note that these variables are not used outside the for loop.
I can do this in two ways.
1. MyClass myobj = new MyClass();
String str = "sample";
int a = 5;
for (......)
myobj = null;
str = null;
a = 0;
// code assign values to str, obj, a for this iteration and it must made null again for next iteration
Note that I need to take care of reinitializing every stuff to default values or null when I enter next time into the loop. Even if I forget a single variable reinitialization, that will have stale data as the scope of the variable is not within the loop
or in an other way
2) Since I dont use these variables outside the loop, part of my mind insists on keeping them within the loop. This way, the ojects and primitives live and die within the loop.
for (.....)
String str = null;
int a = 0;
MyClass myobj = new MyClass();
This seems to be an obvious,easy and sensible way particularly when these are not used outside the for loop.
But , part of my mind says that I am doing Object creation and new primitive creation everytime i enter into the loop, which I feel is an inefficient coding ( creating an object variable from the scratch each time ) .

Question is
a) whether there is any significant difference in both ways ?
b) Is the second way inefficient or is it the right way to do it?
c) Are there any performance issues related to both ways
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Performance should not be an issue. Write code for humans to read first, computers to run second. I agree the second syntax says what you are doing better. Putting the variable scope explicitly inside the loop is a good thing to help document what you meant to do and prevent mistakes using the variables outside the loop.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link:
subject: Question on for loop
It's not a secret anymore!