His answer was: "in case here are few loops, you don't need to
repeatedly declare the same variable".. It's hard to argue with
lecturer as special then you are the first-year student from a foreng
country. But int is not taking so much memory plus java has a garbage
collector to clean memory..
Here is an ugly truth about learning to write software in academia. Odds are good that unless your department head is not only better than most lecturers, but assertive in defense of the students you're just going to lower your grade. When I was in college, one professor had a reputation for grading students down for using "advanced techniques." By that I mean chapters ahead of where he was lecturing. Even if they were able to fully articulate what they were doing with absolute precision, demonstrating that they weren't just copying and pasting.
The fact is that your professor is wrong for most common loops. Unless your code needs to reference the index variable later after the loop, it's best to just let the variable get removed with the scope change. For most practical loops, his way not only won't be necessary. It won't even be possible as today a lot of "for" loops are actually for-each loops like this
for (String s : someArray) {
System.out.println(s);
}
or (Groovy)
someArray.each { element ->
println element
}
UPDATE: Another thing that I think is deeply wrong the professor's argument is that it is in general bad form to leave state exposed unless absolutely necessary. As a general rule, this is a terrible idea for any language, but particularly for a garbage collected language. Since the variable is an int
and not an Integer
(primitive on the stack vs object on the heap for beginners reading this), it's less important in this case. However, when dealing with objects one should write code with an eye for making it trivial for the GC to say "this scope has exited, let's clean up everything inside it."
Over time, if you have a habit of keeping unnecessary state around, you run the risk of introducing memory leaks. Your habits might make it harder for the GC to do its job and on long running tasks that can lead to increased memory requirements and instability. You don't need to go Functional Language purist by any means, but you need to borrow the spirit of it which is regarding state as a necessary evil, not a blessing from Heaven.