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();
}

Recommended Answers

All 2 Replies

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.

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
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.