HELP: decleration and intialization in loops?
Hi,
i was using
Code:
for ( i = 0; i < 10; i++ )
{
MyClass myClassObject = new MyClass();
--
processing.....
}
but later on i was told that i have to use;
Code:
MyClass myClassObject = null;
for ( i = 0; i < 10; i++ )
{
myClassObject = new MyClass();
--
processing.....
}
Both of the codes are producing the same result. Then why we should use the later one. Please let me know if you have know answer/reason. :eek:
Thanks
Rakesh
Thanks, further clarification Looping
Yes, now i got that,
I am using the object withtin a single method, so no need to define it outside the method, and no need to make it global for the whole class.
But i was asking whether we should declare and intialize the object inside the Loop ( for / while ) , or should we declare it outside the loop and intialize later on in the loop. Or it doesn't matter at all?:eek:
Please see the first post. there i have clearly explained what i am asking now.:rolleyes:
Thanks Eranga for your replies, hope to see the next reply soon
Rakesh:)
Now that was really Cool.
First of all thank you very much for the support.
Here is my code.
Code:
resultSet = preparedStatement.executeQuery(); // can be more than 100
while(resultSet.next()) {
ReportResultBean reportBean = new ReportResultBean();
/* All the Setters of the bean will be here */
searchResultList.add( reportBean );
}
Now if you
declare and initialize reportBean before loop, and try to add this in List, then the result will not be what you are expecting.
declare reportBean before loop and initialize initialize the bean inside loop , and try to add this in List, or
declare and initialize reportBean inside loop , and try to add this in List, then
result will be fine.
Waiting for the expert comments,
Rakesh
searchResultList is a List
Code:
searchResultList is one of your method right? If so why don't you ReportResultBean use there. I'm confusing with your code.
searchResultList is not any method, it is an ArrayList
Code:
List searchResultList = new ArrayList();
hope it is clear now.. waiting for reply
Thanks
Also if searchResultList would be a method i don't know how do we use it like searchResultList.add ( xyz ); i guess it should be searchResultList().add(xyz), in that case :D