0

What is the best approach of writing java code in following 2...... ? What happens at jvm level in each case ?

1.

for(int i=0;i<10;i++)
{
	MyClass m = new MyClass();
	m.doSomething();
}

2.

MyClass m;
for(int i=0;i<10;i++)
{
	m = new MyClass();
	m.doSomething();
}
3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by javaAddict
0

No difference. local variables get their stack addresses at the method level, so there is, truely no difference. Unless, of course, you wish to use that variable outside of the for loop.

Edited by masijade: n/a

0

I believe that they are both the same when it comes to the number of Objects created.
The difference is the scope of the "MyClass" instance. In the second case you can use the "m" outside the for-loop. With the first case you cannot.
The second case is useful when you want to create an Object inside a "block" and use it outside that block:

This will not work

try {
   BufferedReader [B]reader[/B] = new BufferedReader(....);
} catch (IOException e) {

} finally {
    [B]reader[/B].close(); //WRONG the reader was declared in the "try", so you cannot close it in the "finally".
}

This will

BufferedReader [B]reader[/B] = null;
try {
   [B]reader[/B] = new BufferedReader(....);
} catch (IOException e) {

} finally {
    if ([B]reader[/B]!=null) [B]reader[/B].close(); //You created it in the try and you close it in the finally. Will work because it was declared outside
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.