• Post Reply Bookmark Topic Watch Topic
  • New Topic

the correct place to declare the variable for multiple uses  RSS feed

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in the below two code samples,

which is the correct way of declaring variable which is used multiple times.
declare it outside the for loop or inside the for loop?


//code sample A
String str;
for(int i=0;i<array.length;i++){
str=array[i];

//do something with str
}


//code sample B
for(int i=0;i<array.length;i++){
String str=array[i];

//do something with str
}


i have read something about immutable property of string and memory management and i am not very clear of the concept. so got this doubt.
i will be greatfull, if you can clear this doubt. thanks in advance

 
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this scenario what is important is the scope of the str variable and not immutable property or memory.
If you define it as #2, str scope is limited to the for loop. As in #1, it cannot be accessed from outside the loop.
 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
siresha tumma wrote:which is the correct way of declaring variable which is used multiple times.

As Maneesh said, there is no real "correct way"; it depends entirely on what you need to do.

That said, a general rule of thumb is that: "scope should be as tight as possible".
You may have also heard the phrase: "define fields as close to where they're used as possible".

They're all just guidelines though - usually to help avoid confusion, or to save you having to hunt for a definition - it doesn't mean that one particular way is "correct".

So, taking the above guideline, if 'str' isn't needed outside the loop - or for more than a single iteration of the loop - then my preference would be for sample B.

HIH

Winston
 
siresha tumma
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you very much for the reply. now i can code without hesitation.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!